body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Am experimenting with the <a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8" rel="nofollow noreferrer">IAsyncEnumerable interface</a> and <a href="https://docs.microsoft.com/en-us/dotnet/standard/io/pipelines" rel="nofollow noreferrer">PipeReader class</a>. Have come up with the following to decode a stream of bytes into chunks of characters and am able to decode all of my test files successfully but that doesn't mean that one hasn't thought of every edge case.</p> <p>Of main concern to me is the final call to <code>Convert</code> that is intended to flush any remaining characters in the decoder. As far as I can tell this call does absolutely nothing with my test data and I don't know enough to contrive an example. My code is loosely based on the example provided <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.decoder.convert" rel="nofollow noreferrer">here</a> but has been altered because it seems incorrect to use <code>charsRead - charIndex</code>; as the latter variable is set via <code>charIndex += charsUsed</code>. If one understands the example correctly then <code>charsRead</code> represents the number of <strong>bytes</strong> that were read while <code>charsUsed</code> actually represents the number of <strong>characters</strong> that were written. 1 byte is not always equivalent to 1 char, unless I'm mistaken, so one adjusted things accordingly.</p> <p>Am not sure if my logic is totally sound and hoping one of you can enlighten me...</p> <p><strong>Code:</strong></p> <pre><code>public static async IAsyncEnumerable&lt;ReadOnlyMemory&lt;char&gt;&gt; DecodeAsync(this PipeReader pipeReader, Decoder decoder) { var decodedBlock = new ArrayBufferWriter&lt;char&gt;(); var readResult = await pipeReader.ReadAsync(); if (!readResult.IsCompleted) { do { var encodedBlock = readResult.Buffer; try { var isDecodingCompleted = false; if (!isDecodingCompleted) { do { decoder.Convert( bytes: in encodedBlock, charsUsed: out _, completed: out isDecodingCompleted, flush: false, writer: decodedBlock ); yield return decodedBlock.WrittenMemory; decodedBlock.Clear(); } while (!isDecodingCompleted); } } finally { pipeReader.AdvanceTo(encodedBlock.End); } readResult = await pipeReader.ReadAsync(); } while (!readResult.IsCompleted); decoder.Convert( bytes: in ReadOnlySequence&lt;byte&gt;.Empty, charsUsed: out var numberOfCharsUsed, completed: out _, flush: true, writer: decodedBlock ); if (0 &lt; numberOfCharsUsed) { yield return decodedBlock.WrittenMemory; } } } </code></pre> <p><strong>Example Usage:</strong></p> <pre><code>public static async IAsyncEnumerable&lt;ReadOnlyMemory&lt;char&gt;&gt; ReadLinesAsync(this PipeReader pipeReader, Decoder decoder) { var isLineFeedCharacterHandlingEnabled = true; var stringBuilder = new StringBuilder(); await foreach (var chunk in pipeReader.DecodeAsync(decoder)) { var newLineIndex = chunk.Span.IndexOfAny('\n', '\r'); var offset = 0; if (-1 != newLineIndex) { do { if (isLineFeedCharacterHandlingEnabled) { if (0 == stringBuilder.Length) { yield return chunk.Slice(offset, newLineIndex); } else { stringBuilder.Append(chunk.Slice(offset, newLineIndex)); yield return stringBuilder.ToString().AsMemory(); stringBuilder.Clear(); } } isLineFeedCharacterHandlingEnabled = ('\r' != chunk.Span[offset..][newLineIndex]); offset += (newLineIndex + 1); newLineIndex = chunk.Span[offset..].IndexOfAny('\n', '\r'); } while (-1 != newLineIndex); } stringBuilder.Append(chunk[offset..]); } if (0 &lt; stringBuilder.Length) { yield return stringBuilder.ToString().AsMemory(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T08:39:15.843", "Id": "529084", "Score": "0", "body": "Why do you call the `pipeReader.AdvanceTo` in a `final` block? Why do you want to advance in case of exception?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:23:15.373", "Id": "529151", "Score": "1", "body": "@PeterCsala [The documentation](https://docs.microsoft.com/en-us/dotnet/standard/io/pipelines#pipereader) seems to indicate that it is the intended pattern to follow. `**Always** call PipeReader.AdvanceTo after calling PipeReader.ReadAsync. This lets the PipeReader know when the caller is done with the memory so that it can be tracked.`" } ]
[ { "body": "<p>Whenever you see 3+ levels of indentation then it is a good sign to do some refactoring :D</p>\n<p>After making some simple transformations I've ended up with this version</p>\n<pre><code>public static async IAsyncEnumerable&lt;ReadOnlyMemory&lt;char&gt;&gt; DecodeAsync(this PipeReader pipeReader, Decoder decoder)\n{\n var decodedBlock = new ArrayBufferWriter&lt;char&gt;();\n ReadResult readResult;\n \n while(!(readResult = await pipeReader.ReadAsync()).IsCompleted)\n {\n var encodedBlock = readResult.Buffer;\n try\n {\n var isDecodingCompleted = false;\n do\n {\n decoder.Convert(bytes: in encodedBlock, charsUsed: out _,\n completed: out isDecodingCompleted, flush: false, writer: decodedBlock);\n\n yield return decodedBlock.WrittenMemory;\n decodedBlock.Clear();\n } while (!isDecodingCompleted);\n \n }\n finally\n {\n pipeReader.AdvanceTo(encodedBlock.End);\n }\n } \n\n decoder.Convert(bytes: in ReadOnlySequence&lt;byte&gt;.Empty, charsUsed: out var numberOfCharsUsed,\n completed: out _, flush: true, writer: decodedBlock);\n\n if (0 &lt; numberOfCharsUsed)\n {\n yield return decodedBlock.WrittenMemory;\n }\n}\n</code></pre>\n<ul>\n<li>Rather than having a <code>do</code>-<code>while</code>, where the last statement is a new <code>ReadAsync</code> I suggest to convert it to a simple <code>while</code> loop</li>\n<li>With this approach you don't need the most outer guard: <code>if (!readResult.IsCompleted)</code></li>\n<li>Your most inner guard: <code>if (!isDecodingCompleted)</code> just dose not make sense, you have just declared the variable as <code>false</code> in the previous line, so your guard expression will be always <code>true</code>.</li>\n</ul>\n<p>You can apply the same transformations for the <code>ReadLinesAsync</code> as well.</p>\n<hr />\n<p>As I've indicated in the comment section, I don't see the point why would you want to advance the <code>pipeReader</code> if you have failed to decode.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:43:20.057", "Id": "529156", "Score": "1", "body": "Thanks for the feedback! The silly outer guards are [loop inversions](https://en.wikipedia.org/wiki/Loop_inversion) that have been done by hand; is a bad habit one picked up that is likely unnecessary in .NET 6. As for the `AdvanceTo` call, I addressed that above. Don't like it myself but seems to be what MS expects us to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:12:59.137", "Id": "529340", "Score": "0", "body": "@Kittoes0124 I've never encountered with the loop inversion concept before. For me it seems like a micro-optimization for this use case. Your method is I/O and memory bound, so optimizing for CPU instructions seems a bit counter-productive for me. But this is just my opinion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T08:48:36.830", "Id": "268325", "ParentId": "268298", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T16:01:02.047", "Id": "268298", "Score": "2", "Tags": [ "c#", "asynchronous", "iterator" ], "Title": "Using the Decoder class in a streaming context" }
268298
<p>I wanted to allow my website visitors (any Tom, Dick &amp; Harry) submit their links to my webpage for output on my page. I thought it's best to parse user submitted urls before echoing their submitted urls on my page. Best to parse the urls as I won't know what urls they will be submitting nor the structures of their urls.</p> <p>A user could theoretically visit my page and inject some Javascript code using, for example:</p> <pre><code>?search=&lt;script&gt;alert('hacked')&lt;/script&gt; </code></pre> <p>You understand my point.</p> <p>I needed to write php script that when users submit their urls, then my php script parses their urls and encodes them by adding urlencode, rawurlencode, intval in the appropriate places before outputting them via htmlspecialchars. Another wrote this following script. Problem is, it outputs like so:</p> <p>http%3A%2F%2Fexample.com%2Fcat%2Fsubcat?var_1=value+1&amp;var2=2&amp;this_other=thing&amp;number_is=13</p> <p>It should output like this:</p> <p><a href="http://example.com/cat/subcat?var_1=value+1&amp;var2=2&amp;this_other=thing&amp;number_is=13" rel="nofollow noreferrer">http://example.com/cat/subcat?var_1=value+1&amp;var2=2&amp;this_other=thing&amp;number_is=13</a></p> <p>NOTE:</p> <pre><code>$url = $_POST[url]; //User Submitted Url. </code></pre> <p>This is their code .... Third Party Code:</p> <pre><code>function encodedUrl($url){ $query_strings_array = []; $query_string_parts = []; // parse URL &amp; get query $scheme = parse_url($url, PHP_URL_SCHEME); $host = parse_url($url, PHP_URL_HOST); $path = parse_url($url, PHP_URL_PATH); $query_strings = parse_url($url, PHP_URL_QUERY); // parse query into array parse_str($query_strings, $query_strings_array); // separate keys &amp; values $query_strings_keys = array_keys($query_strings_array); $query_strings_values = array_values($query_strings_array); // loop query for($i = 0; $i &lt; count($query_strings_array); $i++){ $k = urlencode($query_strings_keys[$i]); $v = $query_strings_values[$i]; $val = is_numeric($v) ? intval($v) : urlencode($v); $query_string_parts[] = &quot;{$k}={$val}&quot;; } // re-assemble URL $encodedHostPath = rawurlencode(&quot;{$scheme}://{$host}{$path}&quot;); return $encodedHostPath . '?' . implode('&amp;', $query_string_parts); } $url1 = 'http://example.com/cat/subcat?var 1=value 1&amp;var2=2&amp;this other=thing&amp;number is=13'; $url2 = 'http://example.com/autos/cars/list.php?state=california&amp;max_price=50000'; // run urls thru function &amp; echo // run urls thru function &amp; echo echo $encoded_url1 = encodedUrl($url1); echo '&lt;br&gt;'; echo $encoded_url2 = encodedUrl($url2); echo '&lt;br&gt;'; ?&gt; </code></pre> <p>So, I changed following of their's:</p> <pre><code>$encodedHostPath = rawurlencode(&quot;{$scheme}://{$host}{$path}&quot;); </code></pre> <p>to this of mine (my amendment):</p> <pre><code>$encodedHostPath = rawurlencode(&quot;{$scheme}&quot;).'://'.rawurlencode(&quot;{$host}&quot;).$path; </code></pre> <p>And it seems to be working. As it's outputting:</p> <p><a href="http://example.com/cat/subcat?var_1=value+1&amp;var2=2&amp;this_other=thing&amp;number_is=13" rel="nofollow noreferrer">http://example.com/cat/subcat?var_1=value+1&amp;var2=2&amp;this_other=thing&amp;number_is=13</a></p> <p>Q1A. But I am not sure if I put the raw_urlencode() in the right places or not and so best you check.</p> <p>Q1B. Also, wondering should not the $path be inside raw_urlencode like so ?</p> <pre><code>raw_urlencode($path) </code></pre> <p>Note however that, it doesn't output the links right.</p> <p>Q2. Anyway, I'm wondering whether I should add htmlspecialchars() or not to output the user submitted links. So wondering whether or not to change their following line:</p> <pre><code>// run urls thru function &amp; echo echo $encoded_url1 = encodedUrl($url1); echo '&lt;br&gt;'; // run urls thru function &amp; echo echo $encoded_url2 = encodedUrl($url2); echo '&lt;br&gt;'; ?&gt; </code></pre> <p>to this (my amendment) instead:</p> <pre><code>// run urls thru function &amp; echo echo $link1 = '&lt;a href=' .htmlspecialchars($encoded_url1) .'&gt;' .htmlspecialchars($encoded_url1) .'&lt;/a&gt;'; echo '&lt;br/&gt;'; // run urls thru function &amp; echo echo $link2 = '&lt;a href=' .htmlspecialchars($encoded_url2) .'&gt;' .htmlspecialchars($encoded_url2) . '&lt;/a&gt;'; echo '&lt;br&gt;'; </code></pre> <p>I'd appreciate anyone editing my code by adding any necessary parts that I missed (htmlspecialchars(), intval(), urlencode(), raw_urlencode(), etc. and deleting unnecessary parts.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T23:24:47.577", "Id": "529196", "Score": "0", "body": "So are we mostly reviewing third party code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T20:12:23.160", "Id": "529321", "Score": "0", "body": "@mickmacusa, third parties on forum gave code to help me out but they had flaws. When I asked them to fix they all went silent. Then it took me weeks to fix. Now, you are reviewing my fix. If you say the fix is ok then I take your word for it. Else, I hesitate to accept my fix. I still a beginner level student at procedural style programming. Not at oop yet. Yes, most of the code was written by third party in the programming forum. I mentioned above, what I amended as the fix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T02:12:41.033", "Id": "529715", "Score": "0", "body": "My suggestion is to write unit tests for each case, then either verify that your code already passes each test, or modify the code so that it does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T16:55:00.037", "Id": "529853", "Score": "0", "body": "@CJ Dennis, So you didn't review it then ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T22:13:34.443", "Id": "529897", "Score": "0", "body": "The problem is that this site is for _working_ code that you want to refactor, not for fixing incorrect behaviour. If you want a code review, stay here. If you want to fix your code, ask your question on [SO]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T18:45:55.140", "Id": "268303", "Score": "1", "Tags": [ "php", "html5", "integer" ], "Title": "Displaying Submitted Links Securely On Your Pages" }
268303
<p>First, some background on what I am actually trying to do here: I am trying to open an Excel Workbook from Python, then run certain macros within that workbook, but with a timeout feature, so that, if any macro takes longer than a specified time limit, the execution will be stopped. I have been using as a starting point the code from this very helpful thread, which does this on Windows using multiprocessing combined with a ThreadPoolExecutor.</p> <p><a href="https://codereview.stackexchange.com/questions/142828/python-executer-that-kills-processes-after-a-timeout">Python Executer that kills processes after a timeout</a></p> <p>However, I am coming across an issue when I try to adapt this to running an Excel macro in the subprocess. It seems that when I open an Excel Workbook in the main process, the subprocess does not have access to it, and when I try to call an Excel macro from the subprocess, it will reopen the same workbook again in a new instance of Excel and run the macro on that workbook instead. I do not want to have to reopen my Workbook every time I call a macro, as I may run the same macro 50+ times on the same workbook before finishing. I only want the macro runs to be limited to a timer, not the workbook opening.</p> <p>I've replicated the issue as simply as I can in the code below. Any help would be appreciated.</p> <pre><code>import datetime import os from concurrent.futures import ThreadPoolExecutor import multiprocessing import typing import win32com.client as win32 macro_timeout = 5 * 60 #seconds for Excel Macro to work before terminating test_workbook = 'C:\Python Test\WorkbookForMacro.xlsb' #Workbook with simple macro #Define Exception class to exit out of the while loop below if a PlanKey times out class MacroTimeoutException(Exception): pass #Define Executor class to call a target function with a timeout parameter and cleanup class ProcessKillingExecutor: &quot;&quot;&quot; The ProcessKillingExecutor works like an `Executor &lt;https://docs.python.org/dev/library/concurrent.futures.html#executor-objects&gt;`_ in that it uses a bunch of processes to execute calls to a function with different arguments asynchronously. But other than the `ProcessPoolExecutor &lt;https://docs.python.org/dev/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor&gt;`_, the ProcessKillingExecutor forks a new Process for each function call that terminates after the function returns or if a timeout occurs. This means that contrary to the Executors and similar classes provided by the Python Standard Library, you can rely on the fact that a process will get killed if a timeout occurs and that absolutely no side can occur between function calls. Note that descendant processes of each process will not be terminated – they will simply become orphaned. &quot;&quot;&quot; def __init__(self, max_workers: int=None): print(datetime.datetime.now()) print(&quot;Class - Entering __init__\n&quot;) self.processes = max_workers or os.cpu_count() def map(self, func: typing.Callable, iterable: typing.Iterable, timeout: float=None, callback_timeout: typing.Callable=None, daemon: bool = True ) -&gt; typing.Iterable: print(datetime.datetime.now()) print(&quot;Class - Entering map\n&quot;) &quot;&quot;&quot; :param func: the function to execute :param iterable: an iterable of function arguments :param timeout: after this time, the process executing the function will be killed if it did not finish :param callback_timeout: this function will be called, if the task times out. It gets the same arguments as the original function :param daemon: define the child process as daemon &quot;&quot;&quot; executor = ThreadPoolExecutor(max_workers=self.processes) params = ({'func': func, 'fn_args': p_args, &quot;p_kwargs&quot;: {}, 'timeout': timeout, 'callback_timeout': callback_timeout, 'daemon': daemon} for p_args in iterable) return executor.map(self._submit_unpack_kwargs, params) def _submit_unpack_kwargs(self, params): &quot;&quot;&quot; unpack the kwargs and call submit &quot;&quot;&quot; print(datetime.datetime.now()) print(&quot;Class - Entering _submit_unpack_kwargs\n&quot;) return self.submit(**params) def submit(self, func: typing.Callable, fn_args: typing.Any, p_kwargs: typing.Dict, timeout: float, callback_timeout: typing.Callable[[typing.Any], typing.Any], daemon: bool): print(datetime.datetime.now()) print(&quot;Class - Entering submit\n&quot;) &quot;&quot;&quot; Submits a callable to be executed with the given arguments. Schedules the callable to be executed as func(*args, **kwargs) in a new process. :param func: the function to execute :param fn_args: the arguments to pass to the function. Can be one argument or a tuple of multiple args. :param p_kwargs: the kwargs to pass to the function :param timeout: after this time, the process executing the function will be killed if it did not finish :param callback_timeout: this function will be called with the same arguments, if the task times out. :param daemon: run the child process as daemon :return: the result of the function, or None if the process failed or timed out &quot;&quot;&quot; p_args = fn_args if isinstance(fn_args, tuple) else (fn_args,) print(datetime.datetime.now()) print(&quot;Class - submit - p_args&quot;) print(p_args) print(&quot;&quot;) print(datetime.datetime.now()) print(&quot;Class - submit - create queue\n&quot;) queue = multiprocessing.Queue() print(datetime.datetime.now()) print(&quot;Class - submit - create Process\n&quot;) p = multiprocessing.Process(target=self._process_run, args=(queue, func, fn_args,), kwargs=p_kwargs) print(datetime.datetime.now()) print(&quot;Class - submit - set daemon\n&quot;) if daemon: p.deamon = True print(datetime.datetime.now()) print(&quot;Class - submit - start process\n&quot;) p.start() print(datetime.datetime.now()) print(&quot;Class - submit - join process\n&quot;) p.join(timeout=timeout) print(datetime.datetime.now()) queueTrue = str(queue.empty()) print(f'queue.empty() status: {queueTrue}') print(&quot;Class - submit - Return queue if queue.empty is False\n&quot;) if not queue.empty(): return queue.get() tim = callback_timeout.__name__ print(datetime.datetime.now()) print(f&quot;Class - submit - callback_timeout = {tim}. Call func if Exists\n&quot;) if callback_timeout: callback_timeout(*p_args, **p_kwargs) p_isalv = str(p.is_alive()) print(datetime.datetime.now()) print(f&quot;Class - submit - Process p is_alive? {p_isalv}. Kill process if True\n&quot;) if p.is_alive(): p.terminate() p.join() print(datetime.datetime.now()) print(&quot;Class - submit - raising exception after terminating process\n&quot;) raise MacroTimeoutException @staticmethod def _process_run(queue: multiprocessing.Queue, func: typing.Callable[[typing.Any], typing.Any]=None, *args, **kwargs): &quot;&quot;&quot; Executes the specified function as func(*args, **kwargs). The result will be stored in the shared dictionary :param func: the function to execute :param queue: a Queue &quot;&quot;&quot; f.write(str(datetime.datetime.now()) + &quot;\n&quot;) f.write(&quot;Class - Entering _process_run\n\n&quot;) queue.put(func(*args)) #Launch Excel in the main process and set it to visible xl = win32.DispatchEx('Excel.Application') xl.Application.visible = True #Defining function for subprocess to run def run_macro(macro_call): f.write(str(datetime.datetime.now())) f.write('\n') f.write('SubProcess - Run macro\n' + str(test_workbook.split(os.sep)[-1] + macro_call) + '\n\n') xl.Application.Run(test_workbook.split(os.sep)[-1] + macro_call) f.write(str(datetime.datetime.now())) f.write('\n') f.write('SubProcess - Macro successfully run!\n\n') #Defining function to run if macro times out def timeout_cleanup(macro_call): print(datetime.datetime.now()) print('SubProcess - Timed Out! Initiate cleanup code\n') print(datetime.datetime.now()) print('Main - Opening Debugging file\n') f = open(&quot;C:\Python Test\PythonTimeoutSubprocessDebug.txt&quot;,&quot;w+&quot;) print(datetime.datetime.now()) print('Main - Opening Workbook\n') wb = xl.Workbooks.Open(os.path.abspath(test_workbook), False, True, None, None, None, True) print(datetime.datetime.now()) print('Main - WorkbookModel Opened!\n') macro_call = '!TestingMacro.MultiplyNumber' try: if __name__ == &quot;__main__&quot;: print(datetime.datetime.now()) print('Main - Create subprocess to run Excel Macro in') print('') executor = ProcessKillingExecutor(max_workers=2) generator = executor.map(run_macro, [(macro_call)], timeout=macro_timeout, callback_timeout=timeout_cleanup) for elem in generator: pass #Clean up Excel wb.Close(SaveChanges=False) wb = None xl.Application.Quit() print(datetime.datetime.now()) print('Main - Closing Debugging file') print('') f.close() print(datetime.datetime.now()) print('Main - Made it to the end!') print('') except MacroTimeoutException: #If any of the macros timed out, exit the loop print(datetime.datetime.now()) print('Main - Closing Debugging file') print('') f.close() print(datetime.datetime.now()) print(&quot;Main - Timed out. Cleaning up Excel\n&quot;) wb.Close(SaveChanges=False) wb = None xl.Application.Quit() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T21:41:40.040", "Id": "529069", "Score": "0", "body": "Welcome to Code Review! Is the code working correctly to the best of your knowledge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T01:56:38.750", "Id": "529078", "Score": "0", "body": "Yes, the code works and runs the macro fine - the issue is just that running the macro in the subprocess opens a new instance of Excel, rather than the workbook Python has already opened in the main process." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T21:14:56.703", "Id": "268307", "Score": "0", "Tags": [ "python", "multiprocessing" ], "Title": "Running an Excel Macro from a Child Process Using Multiprocessing Cannot Access Excel Object in Main Process" }
268307
<p>I have written the following class used to get the metadata out of an internet radio station. It takes a Node Stream and transforms it to grab the metadata out of the mp3 stream and then removes the metadata bytes from the stream so it isn't audibly heard. If you need to know the Shoutcast metadata protocol, see here: <a href="https://web.archive.org/web/20111128170936/https://www.smackfu.com/stuff/programming/shoutcast.html" rel="nofollow noreferrer">https://web.archive.org/web/20111128170936/https://www.smackfu.com/stuff/programming/shoutcast.html</a></p> <pre><code>class SpliceMetadata extends Transform { private META_INT : number = null; private byteCounter: number = 0; private iterator: number = 0; private tempBuffer: string = &quot;&quot;; private updateFn: (song: NowPlaying) =&gt; void = null; constructor(META_INT: number, fn: (song: NowPlaying) =&gt; void, opts?: TransformOptions) { super({ ...opts}) this.META_INT = META_INT; this.updateFn = fn; } private extractSongTitle(raw: string): NowPlaying { let np: NowPlaying = {title: null, artist: null, albumArtUrl: null}; let rawProc : string[] = raw.split(`'`)[1].split('-'); if(rawProc[1]) { np.title = rawProc[1].trim(); np.artist = rawProc[0].trim(); return np; } else { return null; } } _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback) { let hexArray = chunk.toString('hex').match(/.{2}/g); let filteredChunk: string = ''; chunk.forEach((byte, index) =&gt; { if(this.byteCounter === this.META_INT) { this.byteCounter = 0; this.iterator = byte * 16; } else if(this.iterator &gt; 0) { this.iterator--; if(byte !== 0) { this.tempBuffer += String.fromCharCode(byte); } if(this.iterator === 0) { this.updateFn(this.extractSongTitle(this.tempBuffer)); this.tempBuffer = &quot;&quot;; } } else { filteredChunk += hexArray[index]; this.byteCounter++; } }) this.push(Buffer.from(filteredChunk, 'hex')); callback(); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T21:24:28.173", "Id": "268308", "Score": "1", "Tags": [ "node.js", "typescript", "stream", "audio" ], "Title": "Getting metadata out of a Shoutcast stream" }
268308
<p>I'm working on creating code with a nice balance between concise and readable. How would you improve this Laravel code block to make it more compact and readable?</p> <pre><code> public function canEdit(Request $request) { $canEdit = Permission::canEdit( $request-&gt;user(), $request-&gt;siteModel ); $statusCode = ($canEdit) ? 200 : 403; return Response() -&gt;json([ 'can-edit' =&gt; $canEdit ], $statusCode); } </code></pre> <p>Really looking forward for some comments / suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T08:43:32.673", "Id": "529085", "Score": "1", "body": "I don't see much to review here. Outside of declaring `$payload['can-edit'] = ...` and removing the parentheses from `$statusCode`, I don't think there is anything to change. I mean, even `$payload['can-edit']` is a subject decision to declutter the `->json()` parameters -- which I probably wouldn't do personally." } ]
[ { "body": "<p>I agree with mickmackusa that your code is pretty good overall. If you wanted to condense it, you can refactor to something like below:</p>\n<pre class=\"lang-php prettyprint-override\"><code>public function canEdit(Request $request) {\n $canEdit = Permission::canEdit($request-&gt;user(), $request-&gt;siteModel);\n\n return response()-&gt;json(['can-edit' =&gt; $canEdit], $canEdit ? 200 : 403);\n}\n</code></pre>\n<ul>\n<li>Placing the opening brace on the same line as your <code>canEdit()</code> definition can help condense, but if you use a newline, keep it consistent</li>\n<li>Both the <code>$canEdit = ...;</code> definition and <code>return response()-&gt;json(..);</code> statements are under the recommended 80 characters line length, so removing the line breaks is fine</li>\n<li>The definition of <code>$statusCode</code> can be removed in favour of an in-line ternary as the 2nd parameter to your <code>json()</code> method, as defining a variable for a single use is unnecessary</li>\n<li>You can add or remove a line-break between your two statements, I prefer an empty line before <code>return</code>, but depends on your configuration/consistency</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T09:18:42.360", "Id": "529225", "Score": "1", "body": "Nice suggestions. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:10:19.370", "Id": "268347", "ParentId": "268311", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T22:00:01.883", "Id": "268311", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Method in Laravel to give a JSON response indicating whether the user may edit" }
268311
<p>Following is my working application that contains a Search Container, a Sorting Container and a listing Container.</p> <p>Based on Search and Sort the listing data changes in the listing container.</p> <p>The application works fine though I noticed in my Search container whenever I am changing the input value in an input box, select component is re rendering and vice versa(check console).</p> <p>Is there any pattern or modification I can do to minimise the re renders in the application ?</p> <p>Working Demo - <a href="https://ojlrd.csb.app/" rel="nofollow noreferrer">https://ojlrd.csb.app/</a></p> <p>Codesandbox - <a href="https://codesandbox.io/s/rerender-ojlrd?file=/src/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/rerender-ojlrd?file=/src/index.js</a></p> <hr /> <p>Code -</p> <p><strong>Page.js</strong></p> <pre><code>const Page = () =&gt; { const [pageData, setPageData] = useState({ search: {}, sort: { sortBy: '' } }); const getData = useCallback((type, data) =&gt; { setPageData(prevVal =&gt; { return { ...prevVal, [type]: {...data} } }) }, [setPageData]); return ( &lt;div className=&quot;container&quot;&gt; &lt;SearchContainer getData={getData} /&gt; &lt;SortingContainer getData={getData} /&gt; &lt;ListingContainer urlData={pageData} /&gt; &lt;/div&gt; ); }; export default Page; </code></pre> <p><strong>SearchContainer.js</strong></p> <pre><code>const SearchContainer = ({ getData = () =&gt; {} }) =&gt; { const [searchData, setSearchData] = useState({ search1: '', search2: '13', search3: '', search4: '44' }); useEffect(() =&gt; { getData('search', searchData); }, [searchData, getData]); const eventHandler = e =&gt; { setSearchData(prevVal =&gt; { return { ...prevVal, [e.target.name]: e.target.value } }) } return ( &lt;div className=&quot;container-search&quot;&gt; &lt;h3&gt;Search container&lt;/h3&gt; &lt;div className=&quot;container-search-actions&quot;&gt; &lt;Input initialValue='' label='Input 1' name=&quot;search1&quot; eventHandler={eventHandler} /&gt; &lt;Select label='Select 2' name=&quot;search2&quot; options={[ {label: 'Label 11', value: '11'}, {label: 'Label 12', value: '12'}, {label: 'Label 13', value: '13'}, {label: 'Label 14', value: '14'} ]} selectedValue='13' eventHandler={eventHandler} /&gt; &lt;Input initialValue='' label='Input 3' name=&quot;search3&quot; eventHandler={eventHandler} /&gt; &lt;Select label='Select 4' name=&quot;search4&quot; options={[ {label: 'Label 41', value: '41'}, {label: 'Label 42', value: '42'}, {label: 'Label 43', value: '43'}, {label: 'Label 44', value: '44'} ]} selectedValue='44' eventHandler={eventHandler} /&gt; &lt;/div&gt; &lt;/div&gt; ) } export default SearchContainer; </code></pre> <p><strong>SortingContainer.js</strong></p> <pre><code>const SortingContainer = ({ getData = () =&gt; {} }) =&gt; { const [sortData, setSortData] = useState({ sortBy: 'desc' }) useEffect(() =&gt; { getData('sort', sortData); }, [sortData, getData]); const eventHandler = e =&gt; { setSortData(prevVal =&gt; { return { ...prevVal, [e.target.name]: e.target.value } }) } return ( &lt;div className=&quot;container-sorting&quot;&gt; &lt;Select label='Sort By' name='sortBy' options={[ {label: 'Ascending', value: 'asc'}, {label: 'Descending', value: 'desc'} ]} selectedValue='desc' eventHandler={eventHandler} /&gt; &lt;/div&gt; ); } export default SortingContainer; </code></pre> <p><strong>ListingContainer.js</strong></p> <pre><code>const ListingContainer = ({ urlData }) =&gt; { const createURL = (urlData) =&gt; { const { search, sort } = urlData; let url = &quot;/api?&quot;; [search, sort].forEach((element) =&gt; { for (const [key, value] of Object.entries(element)) { url += `&amp;${key}=${value}`; } }); return url; }; return ( &lt;div className=&quot;container-listing&quot;&gt; This is a listing container &lt;p&gt;URL Formed - &lt;/p&gt; &lt;p className=&quot;bold&quot;&gt;{createURL(urlData)}&lt;/p&gt; &lt;/div&gt; ); }; export default ListingContainer; </code></pre>
[]
[ { "body": "<p>I was able to resolve this by adding a <code>memo</code> wrapper around the components' <code>export</code> statements, then passing in a compare function that returns <code>true</code>. The components were re-rendering each time the <code>eventHandler</code> function was re-created when the state of the parent changed on each input.</p>\n<p>Since you pass no dynamic data in, there is no reason for these components to re-render except when their own state is updated.</p>\n<p><a href=\"https://codesandbox.io/s/48qge\" rel=\"nofollow noreferrer\">See a working example here.</a></p>\n<p><strong>Input.js</strong></p>\n<pre><code>...\nexport default memo(Input, () =&gt; true);\n</code></pre>\n<p><strong>Select.js</strong></p>\n<pre><code>...\nexport default memo(Select, () =&gt; true);\n</code></pre>\n<p><a href=\"https://reactjs.org/docs/react-api.html#reactmemo\" rel=\"nofollow noreferrer\">Source</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T17:02:00.713", "Id": "268407", "ParentId": "268313", "Score": "3" } } ]
{ "AcceptedAnswerId": "268407", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T22:35:45.513", "Id": "268313", "Score": "4", "Tags": [ "javascript", "performance", "html", "react.js", "jsx" ], "Title": "Reduce multiple re rendering of components in React" }
268313
<p>So, I just managed to finish a problem that was proposed to me, and I find it very difficult since I started learning looping with <code>for</code> and using <strong>lists</strong> recently, I thought about sharing the problem and my solution with you guys so you could give me some advice on how I should make my code better or different ways to solve the problem, hopefully you guys can help me, thank you for your attention and sorry if I made some mistakes, I am new to programming.</p> <p><em><strong>Question</strong></em></p> <blockquote> <p>Write a function that receives a list with natural numbers, verify if such list has repeated numbers, if so remove them. The function should return a correspondent list with no repeated elements. The list should be returned in ascending order.</p> </blockquote> <pre><code>def remove_repeated_numbers(z): x = 1 for i in z: y = x while y &lt;= (len(z) - 1): if i == z[y]: del z[y] y = (y - 1) #Once z[y] is deleted, should check same spot again y = (y + 1) x = (x + 1) list_finished = sorted(z[:]) return list_finished def main(): run = True z = [] while run: u = int(input(&quot;Entry value: &quot;)) if u != 0: z.append(u) else: run = False print(remove_repeated_numbers(z)) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:44:27.363", "Id": "529082", "Score": "0", "body": "You may be interested in the SO question [What is the cleanest way to do a sort plus uniq on a Python list?](//stackoverflow.com/q/2931672/4850040)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T12:26:45.807", "Id": "529113", "Score": "1", "body": "Do you know that your ENTIRE script can be replaced with this ONE-liner: `sorted(set(l))`? This is extremely basic, `set` is a built-in data type that is ordered without duplicates with fast membership checking that is exactly what is designed to do this sort of thing, and then you just need to use `sorted` function to return a sorted (shallow) copy of the list. Type casting is by far the most efficient and readable way to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:44:06.207", "Id": "529138", "Score": "0", "body": "@XeнεiΞэnвϵς I tried your `sorted(set(l))`. Didn't work. Got `NameError: name 'l' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:43:50.567", "Id": "529157", "Score": "0", "body": "@BolucPapuccuoglu `NameError: name 'z' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:46:44.180", "Id": "529161", "Score": "0", "body": "Oh boy I did not knew that @XeнεiΞэnвϵς LOL, but I just figured it out, anyways, I'm pretty sure the Question wanted me to do it by myself, but anyways thank you for your tip." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:48:48.410", "Id": "529163", "Score": "3", "body": "@BolucPapuccuoglu Yeah, but XeнεiΞэnвϵς said to replace ENTIRE script with that (shouting already theirs)." } ]
[ { "body": "<p>It's a good start. Depending on what class this is for, the person (teacher?) who proposed this question to you might care about time complexity of your solution. Your solution is going to have a number of problems there, since:</p>\n<ul>\n<li><code>del z[y]</code> is linear-time (&quot;O(n)&quot;)</li>\n<li>That occurs within a loop over the list, within <em>another</em> loop over the list, making the solution worst-case cubic if I'm not mistaken.</li>\n</ul>\n<p>The trivial and common solution is to scrap the whole routine and replace it with calls to two built-ins:</p>\n<pre><code>from typing import Iterable, List\n\n\ndef remove_repeated_numbers(numbers: Iterable[int]) -&gt; List[int]:\n return sorted(set(numbers))\n</code></pre>\n<p>I will leave it as an exercise to you to read the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">documentation</a> and determine the complexity of this implementation.</p>\n<p>This will construct a set from the numbers, which guarantees uniqueness but not order; and then constructs a sorted list from that. Interpreted literally, the question doesn't call for the existence of a <code>main</code> but I don't know how picky the problem is.</p>\n<p>Other things to note:</p>\n<ul>\n<li>Don't use single-letter variables</li>\n<li>Add type hints for greater clarity</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T03:04:23.770", "Id": "268317", "ParentId": "268315", "Score": "7" } }, { "body": "<p>The first thing to know about Python is that most basic operations on lists have helper built-ins. Your code could use <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set()</code></a> as the holding structure which will ensure uniqueness for you without any work.</p>\n<p>With that out of the way, I think your assignment is more about showing your work so let's take that view on it:</p>\n<ul>\n<li>Your <code>run</code> variable is not needed. You can use <a href=\"https://www.w3schools.com/python/ref_keyword_break.asp\" rel=\"nofollow noreferrer\"><code>break</code> keyword</a> to get out of the <code>while</code> loop.</li>\n<li>You should try to do the early escape first in conditions to avoid nesting. In your case, you can say &quot;if input is 0, break&quot; then everything below assumes that value is not 0 so you don't need an <code>else</code>.</li>\n<li>Double loop is overkill. <code>if &lt;numer&gt; not in &lt;array&gt;:</code> then add the number to array. It's slow but easy. You can do better with a set or a dictionary but that's excessive work for what you are doing.</li>\n<li>If you're working in Python avoid index-based iteration. You can/should use iterables: <code>for value in entered_data:</code>.</li>\n<li>Finally, avoid short names on variables. They create unmaintainable code and keep mental overhead high.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T03:14:46.930", "Id": "268319", "ParentId": "268315", "Score": "3" } }, { "body": "<h1>Add some unit tests</h1>\n<p>Are we sure that the function works? Will it still work when we make changes (perhaps to improve its performance)?</p>\n<p>Python comes with some <em>unit-testing</em> facilities to help us ensure that we don't break the function. One that's very easy to use is <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a>, which lets us put the tests right by the code itself.</p>\n<p>We could start by testing an empty list:</p>\n<pre><code>def remove_repeated_numbers(z):\n &quot;&quot;&quot;\n Return a sorted copy of the input list, with duplicates removed.\n\n &gt;&gt;&gt; remove_repeated_numbers([])\n []\n &quot;&quot;&quot;\n ⋮\n ⋮\n</code></pre>\n<p>We write each test as a line beginning with <code>&gt;&gt;&gt;</code> and an expression to evaluate, with the expected result on the following line.</p>\n<p>We can run the tests with some easy boilerplate (which we don't need to understand right now):</p>\n<pre><code>if __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n<p>To be sure that our tests work properly, let's add a test that we know will fail:</p>\n<pre><code>&gt;&gt;&gt; remove_repeated_numbers([])\nNone\n</code></pre>\n<p>That gives us a useful diagnostic:</p>\n<pre class=\"lang-none prettyprint-override\"><code>**********************************************************************\nFile &quot;268315.py&quot;, line 7, in __main__.remove_repeated_numbers\nFailed example:\n remove_repeated_numbers([])\nExpected:\n None\nGot:\n []\n**********************************************************************\n</code></pre>\n<p>Let's remove that, and add some more tests:</p>\n<pre><code> &gt;&gt;&gt; remove_repeated_numbers([0])\n [0]\n &gt;&gt;&gt; remove_repeated_numbers([0, 0])\n [0]\n &gt;&gt;&gt; remove_repeated_numbers([0, 1])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_numbers([1, 0])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_numbers([0, 0, 1, 1, 1])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_numbers([0, 1, 1, 1, 0])\n [0, 1]\n &quot;&quot;&quot;\n</code></pre>\n<p>That's good, and we now have more confidence in what we're doing.</p>\n<hr />\n<p>We can now change the implementation to use a <code>set</code>, as suggested in a different answer, but I'll propose a smaller change, and that is to sort the input first:</p>\n<pre><code>for i in sorted(z):\n</code></pre>\n<p>That initially seems like it's making more work (after all, the input could be much longer than the output), but it will reduce the later operations, because now all the duplicates are adjacent, so we don't need to examine the whole list to find them.</p>\n<p>Now, instead of the expensive <code>del z[y]</code> (which needs to shuffle all the subsequent elements in the list), we can copy to a new list to return to the user. Note that this changes the behaviour - I believe for the better. The code presented modifies the actual array passed to the function (though the modified array is only deduplicated, not sorted). It's generally less surprising to return a copy so that the original data is unchanged.</p>\n<p>Just to demonstrate, try this code with the function as posted:</p>\n<pre><code>a = [ 2, 1, 1, 2]\nprint(remove_repeated_numbers(a))\nprint(a)\n</code></pre>\n<p>With this code, the function returns <code>[1, 2]</code> and <code>a</code> is changed to <code>[2, 1]</code>.</p>\n<p>So let's create our result array:</p>\n<pre><code>result = []\n⋮\nreturn result\n</code></pre>\n<p>Now our loop is very simple: for each element we see, if it's the same as the one we most recently added to <code>result</code>, then ignore it, else add it to <code>result</code>:</p>\n<pre><code>for i in sorted(z):\n if i != result[-1]:\n result.append(i)\n</code></pre>\n<p>That's not quite right, because <code>result</code> starts off empty. We need to always include the first element, so we must change the test to also succeed when <code>result</code> is empty - i.e. <code>not result</code>:</p>\n<pre><code>for i in sorted(z):\n if not result or i != result[-1]:\n result.append(i)\n</code></pre>\n<p>I think that's easier to understand than code that <code>del</code>etes items from the input list.</p>\n<hr />\n<h1>Full modified code</h1>\n<p>For reference, here's the full program from this approach:</p>\n<pre><code>def remove_repeated_elements(input_list):\n &quot;&quot;&quot;\n Return a sorted copy of the input list, with duplicates removed.\n\n &gt;&gt;&gt; remove_repeated_elements([])\n []\n &gt;&gt;&gt; remove_repeated_elements([0])\n [0]\n &gt;&gt;&gt; remove_repeated_elements([0, 0])\n [0]\n &gt;&gt;&gt; remove_repeated_elements([0, 1])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_elements([1, 0])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_elements([0, 0, 1, 1, 1])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_elements([0, 1, 1, 1, 0])\n [0, 1]\n &gt;&gt;&gt; remove_repeated_elements(['review', 'code', 'code', 'review'])\n ['code', 'review']\n &quot;&quot;&quot;\n result = []\n for element in sorted(input_list):\n if not result or result[-1] &lt; element:\n result.append(element)\n return result\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n<p>Note that I changed the name slightly, as this will work with any type that can be ordered (such as strings - see the last test), not just numbers. The answer that recommends using <code>set</code> also works with more than just numbers (but requires a type that can be hashed, as well as ordered).</p>\n<p>I also changed the test to use <code>&lt;</code>, so it will work for any (admittedly theoretical, and highly improbable) type that can be sorted but not compared for inequality.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T09:40:01.050", "Id": "529086", "Score": "0", "body": "I really like this answer, and I suspect indeed the eliminating the duplicates in a sorted list is the core of the exercise -- otherwise it could just as well require the elements to be returned in the order they were in the initial list. I do find `not result` slightly difficult to read, and would favor `len(result) == 0` instead as I find it more \"immediate\" in meaning; is `not result` considered more idiomatic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T10:36:08.210", "Id": "529090", "Score": "1", "body": "There's [some debate on what's preferred](https://lwn.net/Articles/868490/) - some Python people prefer the length test and others the truth test. My opinion on that isn't very strong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:20:01.407", "Id": "529135", "Score": "2", "body": "Since `sorted` only require comparison via `__lt__`, you could write `result[-1] < element` for the rare cases `__ne__` is not defined. Also, what's the rationale of using `result += [element]` rather than `result.append(element)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:27:44.150", "Id": "529136", "Score": "0", "body": "@301: Both good points - I'll modify accordingly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:43:00.590", "Id": "268323", "ParentId": "268315", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T01:09:09.133", "Id": "268315", "Score": "6", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Remove repeated numbers from a list" }
268315
<p>I am using the following one-liner to remove duplicate non-empty lines without sorting:</p> <pre class="lang-sh prettyprint-override"><code>perl -ne 'if ( /^\s*$/ ) { print } else { print if ! $x{$_}++}' </code></pre> <p>Empty (whitespace-only) lines are to be retained.</p> <p>However, this code seems bulky, specially the <code>$x{$_}++</code> part.</p> <p>Is there any way I can make this code more readable and understandable?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:12:15.673", "Id": "529080", "Score": "2", "body": "I'm not sure what you mean by `$x{$_}++` being bulky. It seems pretty small for what it does. Does it take too much memory? What's bulky about it? In terms of readability, is changing it from a one-liner to a script on the table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:16:01.740", "Id": "529081", "Score": "0", "body": "@mdfst13 if I look at `$x{$_}++`, after few days, I will not understand what it is actually doing. Maybe, this is due to my lack of understanding of perl. But a more understandable syntax will be much helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:42:31.273", "Id": "529343", "Score": "0", "body": "Break it into two parts then, where latter one is `$x{$_} += 1;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:01:44.240", "Id": "533808", "Score": "0", "body": "`!$seen{$_}++` is a common idiom. Yes, it is bulky, but it's something you should learn to recognize" } ]
[ { "body": "<p>Why not just</p>\n<pre><code>print if /^\\s*$/ || ! $SEEN{$_}++\n</code></pre>\n<p>I don't see the point of nesting here. You want to print if the line is empty or if it has not been seen previously. So say that. If you still don't find this readable and readability is your main concern, change it from a one-liner to a script. Something like</p>\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\n\nmy $WHITESPACE = qr{\\s*};\nmy $EMPTY_LINE = qr{^$WHITESPACE$};\n\nmy %seen;\n\nwhile (my $line = &lt;&gt;) {\n # add comments as necessary\n print $line if $line =~ m{$EMPTY_LINE} || ! $seen{$line}++;\n}\n\n# one line version\n# perl -ne 'print if /^\\s*$/ || ! $SEEN{$_}++'\n</code></pre>\n<p>Now you can see that an empty line is defined as having only whitespace between the beginning and the end.</p>\n<p>It would be better to use constants or Readonly for the patterns, but I don't remember the syntax well enough without running it.</p>\n<p>There's a seen hash.</p>\n<p>We read every line either from STDIN or the files in the arguments.</p>\n<p>We print if the line matches an empty line or if it is not seen. At the end, if we wanted, we would could print how many times each line was seen.</p>\n<p>If that doesn't read naturally to you, add comments for the parts that you won't understand later.</p>\n<p>Unwrapping <code>$seen{$line}++</code>. The <code>++</code> is a post increment. It increments the value of the variable and then returns the previous value of the variable. In this case, the first time that a particular <code>$line</code> value is seen, the variable will be undefined. So Perl will treat it as zero for the purpose of the increment and either zero or <code>undef</code> for the Boolean. Zero and <code>undef</code> are falsey in Perl, so not zero/<code>undef</code> will be true the first time. Subsequent times, the value will be 1, 2, 3, etc. Those are all truthy, so the negated expression will be false.</p>\n<p>Perl uses short circuit Boolean operators. So if the line matches an empty line, the second part will never be reached.</p>\n<p>One of the major points of Perl one-liners is that they allow a very terse syntax, which is relatively difficult to read but easy to type. If you don't want that, upgrade it to a script with its much longer syntax. If you stuff it in the bin directory under your home directory in Linux, you can set the executable bit and use it like</p>\n<pre><code>~/bin/script_name.pl file_name\n</code></pre>\n<p>or</p>\n<pre><code>~/bin/script_name.pl &lt; file_name\n</code></pre>\n<p>or</p>\n<pre><code>some_other_command | ~/bin/script_name.pl\n</code></pre>\n<p>And if you want to know how it works later, you can simply view or edit the file. If you forget how something works and have to research it, add a comment for the next time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T08:10:22.097", "Id": "268324", "ParentId": "268320", "Score": "7" } } ]
{ "AcceptedAnswerId": "268324", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T05:08:30.477", "Id": "268320", "Score": "6", "Tags": [ "perl" ], "Title": "Remove duplicate lines without sorting or removing empty lines" }
268320
<p>I'm wondering if there is a nicer way to acomplish what I want:</p> <p>I do have an array with object like that:</p> <pre><code>let data = [ {val1: [1,2,3,4], val2:[6,7,8,9] } ] </code></pre> <p>What I want is an object like:</p> <pre><code>let limit = { minX: 1, maxX: 4, minY: 6, maxY: 9 }; </code></pre> <p>My Code works but once more I'm wondering if there is a nicer and shorter way to achieve it? Here is my solution:</p> <pre><code> determineMinxMax(data: any) { let limit = {minX: null, maxX: null, minY: null, maxY: null} limit.minX = Math.min(...data.map(item =&gt; Math.min(...item.val1))); limit.maxX = Math.max(...data.map(item =&gt; Math.max(...item.val1))); limit.minY = Math.min(...data.map(item =&gt; Math.min(...item.val2))); limit.maxY = Math.max(...data.map(item =&gt; Math.max(...item.val2))); return limit; } </code></pre>
[]
[ { "body": "<p>The original code looks more like traditional JS, it does not benefit from typing features provided by the <em>TypeScript</em> language.</p>\n<p>The solution I suggest below is not necessarily <em>shorter</em>, but its main goal is to put the things in order using the TS style.</p>\n<p>First of all, interfaces can be created to define the structures of the <code>data</code> and <code>limit</code> objects:</p>\n<pre class=\"lang-js prettyprint-override\"><code>interface MyDataItem {\n val1: Array&lt;number&gt;;\n val2: Array&lt;number&gt;;\n};\n\ninterface Limit {\n minX: number;\n maxX: number;\n minY: number;\n maxY: number;\n};\n</code></pre>\n<p>To access the <code>val1</code> and <code>val2</code> properties generically, a type and respective constants can be defined:</p>\n<pre class=\"lang-js prettyprint-override\"><code>type PropertyAccessor = (item: MyDataItem) =&gt; Array&lt;number&gt;;\n\nconst accessorX: PropertyAccessor = item =&gt; item.val1;\n\nconst accessorY: PropertyAccessor = item =&gt; item.val2;\n</code></pre>\n<p>Similarly, to access the <code>min</code> and <code>max</code> values, we can define dedicated mapping constants:</p>\n<pre class=\"lang-js prettyprint-override\"><code>type ValueExtractor = (values: Array&lt;number&gt;) =&gt; number;\n\nconst extractorMin: ValueExtractor = values =&gt; Math.min(...values);\n\nconst extractorMax: ValueExtractor = values =&gt; Math.max(...values);\n</code></pre>\n<p>Now, the implementation of the <code>determineMinMax</code> function becomes very concise and does not include repetitive stuff:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const determineMinMax = (data: Array&lt;MyDataItem&gt;): Limit =&gt; ({\n minX: extractMinMax(data, accessorX, extractorMin),\n maxX: extractMinMax(data, accessorX, extractorMax),\n minY: extractMinMax(data, accessorY, extractorMin),\n maxY: extractMinMax(data, accessorY, extractorMax)\n});\n</code></pre>\n<p>Finally, we need to implement the <code>extractMinMax</code> function, which contains the main calculation logic:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const extractMinMax = (data: Array&lt;MyDataItem&gt;, \n propertyAccessor: PropertyAccessor, \n minMaxExtractor: ValueExtractor): number =&gt;\n data.map(propertyAccessor) ​// extract the array with the current property from data\n ​.map(minMaxExtractor) // find the min value of each property\n ​.reduce((prev: number, next: number) =&gt; minMaxExtractor([prev, next])); // find the min value among all min values\n</code></pre>\n<p>...and a test case checking the calculated value:</p>\n<pre class=\"lang-js prettyprint-override\"><code>describe('Q268329', () =&gt; {\n\n ​it('should return expected value', () =&gt; {\n ​const data = [\n ​{val1: [1,2,3,4], val2:[6,7,8,9] }\n ​];\n ​const limit = determineMinMax(data);\n ​expect(limit).toEqual({\n ​minX: 1, maxX: 4, minY: 6, maxY: 9\n ​});\n ​});\n\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T12:02:28.707", "Id": "529298", "Score": "1", "body": "I noticed you are consistently using `Array<T>`. I only have limited experience with TypeScript, but in my limited experience, it seems that `T[]` is a more idiomatic way to write that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T14:15:09.017", "Id": "529304", "Score": "0", "body": "@\"Jörg W Mittag\" There is no \"idiomatic\" way between `Array` and `[]`, both are similar. It's simply a choice of coding style." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T08:29:15.820", "Id": "268399", "ParentId": "268329", "Score": "0" } } ]
{ "AcceptedAnswerId": "268399", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T10:13:17.537", "Id": "268329", "Score": "0", "Tags": [ "typescript" ], "Title": "Shorthand of compiling min and max values from an array with object into new object" }
268329
<p>This is a Python 3 script I have written over three days that transliterates (not translating) English orthography written in Latin alphabet to the Cyrillic alphabet, the Greek alphabet or a mixed of those two above.</p> <p>The script transliterates the text, meaning it doesn't translate the meaning of the text from one language to another language, it doesn't translate English into русский or Ελληνικά, rather, it attempts to analyze the pronunciation of the word to find the phonemes in it, and represent the phonemes by letters from another alphabet (either Greek or Cyrillic) or combinations thereof, phoneme for phoneme.</p> <p>I wrote this because this in my opinion is a truly cool thing to do, something that is rarely done and I highly doubt Python has a built-in function to do this; Cyrillic, Greek and Latin scripts are closely related, they are so similar yet also so fundamentally different, yet Cyrillic and Latin scripts both stem from (ancient) Greek script. English is always written in Latin alphabet, writing it in another script is really fascinating.</p> <p>I won't lie, I was inspired by 1337, however I found it too basic, contenting just at merely substitute letters with similar glyph, with some using letters from Greek and Cyrillic scripts, and these usages aren't phonetically correct at all. So I wrote this transliterating script, because if it merely translates the input, less knowledgeable people will just use Google Translate to get the original text, while in this case, you have to actually know how to read Cyrillic and Greek scripts to understand the transliterated output.</p> <p>I researched extensively on grapheme-to-phoneme conversion methods, ARPABET, modern Greek phonology and Russian phonology, and English phonology, and tried to stick to the spelling conventions and the pronunciations as close as possible;</p> <p>I tried to write a script to evaluate the pronunciation of written English, with a set of established rules to help determine pronunciation of each grapheme, having written 100+ lines of code with 30+ conditions, but ultimately gave up because there are simply too many variables at play here, instead I use <code>g2p</code> here, as <code>g2p</code> isn't in the standard library you will need to download it, <code>g2p</code> converts English into ARPABET, I have considered using <code>epitran</code>, however I am using Windows and I don't have <code>flite</code> installed, I tried the example from the official site and it just throws errors. <code>g2p</code> can convert words not found in dictionaries but may not be very accurate for such words.</p> <p>The output of the script, is, technically still English, however represented in scripts other than Latin, as the output is English and not the language the script and spelling suggest, Google Translate won't reliably &quot;translate&quot; the output back to the original input. The transliteration is a unidirectional process, transliterating the output back to the input is impossible without a dictionary and an artificial intelligence to evaluate the possibilities, there are three modes available: <code>'cyrillic'</code> (only using letters from Cyrillic script), <code>'greek'</code> (only using letters from Greek script) and <code>'random'</code> (randomly select letters from Greek and Cyrillic scripts), and I personally prefer the random mode as its outputs will confuse Google Translate making it unable to correctly pronounce the output, meaning you can't guess it by using Google Translate...</p> <p>Currently it is impossible to preserve cases because I am using <code>g2p</code>, but I have succeeded in preserving punctuations, and the loading time might be a bit too long, it is caused by <code>g2p</code> importing.</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code>import random import re import sys from g2p_en import G2p from string import punctuation g2p = G2p() ARPA2ALPHA = { '@': 'a', 'A': 'a', 'AA': 'a', 'AE': 'a', 'AH': 'a', 'AO': 'o', 'AW': 'au', 'AX': 'e', 'AXR': 'er', 'AY': 'ai', 'B': 'b', 'C': 'ch', 'CH': 'ch', 'D': 'd', 'DH': 'dh', 'DX': 't', 'E': 'e', 'EH': 'e', 'EL': 'l', 'EM': 'm', 'EN': 'n', 'ER': 'er', 'EY': 'ei', 'F': 'f', 'G': 'g', 'H': 'h', 'HH': 'h', 'I': 'i', 'IH': 'i', 'IX': 'i', 'IY': 'ii', 'J': 'j', 'JH': 'j', 'K': 'k', 'L': 'l', 'M': 'm', 'N': 'n', 'NG': 'ng', 'NX': 'nn', 'O': 'oi', 'OW': 'ou', 'OY': 'oi', 'P': 'p', 'Q': &quot;'&quot;, 'R': 'r', 'S': 's', 'SH': 'sh', 'T': 't', 'TH': 'th', 'U': 'u', 'UH': 'u', 'UW': 'u', 'UX': 'u', 'V': 'v', 'W': 'w', 'WH': 'w', 'X': 'i', 'Y': 'y', 'Z': 'z', 'ZH': 'zh', 'a': 'a', 'b': 'b', 'c': 'o', 'd': 'd', 'e': 'ei', 'f': 'f', 'g': 'g', 'h': 'h', 'i': 'ii', 'k': 'k', 'l': 'l', 'm': 'm', 'n': 'n', 'o': 'ou', 'p': 'p', 'r': 'r', 's': 's', 't': 't', 'u': 'u', 'v': 'v', 'w': 'w', 'x': 'e', 'y': 'y', 'z': 'z' } TRANSLITERATION = { 'a': {0: 'а', 1: 'α'}, 'b': {0: 'б', 1: 'μπ'}, 'd': {0: 'д', 1: 'ντ'}, 'e': {0: 'э', 1: 'ε'}, 'f': {0: 'ф', 1: 'φ'}, 'g': {0: 'г', 1: 'γκ'}, 'h': {0: 'х', 1: 'χ'}, 'i': {0: 'и', 1: 'ι'}, 'j': {0: 'дж', 1: 'τζ'}, 'k': {0: 'к', 1: 'κ'}, 'l': {0: 'л', 1: 'λ'}, 'm': {0: 'м', 1: 'μ'}, 'n': {0: 'н', 1: 'ν'}, 'o': {0: 'о', 1: 'ο'}, 'p': {0: 'п', 1: 'π'}, 'r': {0: 'р', 1: 'ρ'}, 's': {0: 'с', 1: 'σ'}, 't': {0: 'т', 1: 'τ'}, 'u': {0: 'у', 1: 'ου'}, 'v': {0: 'в', 1: 'β'}, 'y': {0: 'й', 1: 'γ'}, 'z': {0: 'з', 1: 'ζ'}, 'ai': {0: 'ай', 1: 'αϊ'}, 'au': {0: 'ао', 1: 'αου'}, 'ch': {0: 'ч', 1: 'τσ'}, 'dh': {0: 'з', 1: 'δ'}, 'dz': {0: 'дз', 1: 'τζ'}, 'ei': {0: 'эй', 1: 'εϋ'}, 'er': {0: 'эр', 1: 'ερ'}, 'ii': {0: 'ий', 1: 'ει'}, 'ks': {0: 'кс', 1: 'ξ'}, 'ng': {0: 'нг', 1: 'γγ'}, 'oi': {0: 'ой', 1: 'οϊ'}, 'ou': {0: 'оу', 1: 'ω'}, 'ps': {0: 'пс', 1: 'ψ'}, 'sh': {0: 'ш', 1: 'σ'}, 'th': {0: 'т', 1: 'θ'}, 'ts': {0: 'ц', 1: 'τσ'}, 'ui': {0: 'уй', 1: 'ουι'}, 'ya': {0: 'я', 1: 'γα'}, 'ye': {0: 'е', 1: 'γε'}, 'yo': {0: 'ё', 1: 'γο'}, 'yu': {0: 'ю', 1: 'γου'}, 'zh': {0: 'ж', 1: 'ζ'}, 'shch': {0: 'щ', 1: 'στσ'}, &quot;'&quot;: {0: 'ъ', 1: '΄'} } PHONEMES = list(TRANSLITERATION.keys()) + ['ia', 'ie', 'io', 'w'] PHONEME_REGEX = re.compile('(' + r'|'.join(sorted(PHONEMES, key=len, reverse=True)) + ')') def parser(s: str) -&gt; list: switch = {'ia': 'ya', 'ie': 'ye', 'io': 'yo', 'w': 'v'} reduct = lambda x: ''.join(i for i in x if i.isalpha()) if x[0].isalpha() else x phonemes = [reduct(p) for p in g2p(s)] parsed = ''.join([ARPA2ALPHA.get(p, p) for p in phonemes]) parsed = [i for i in PHONEME_REGEX.split(parsed) if i] phonemes = [switch.get(p, p) for p in parsed] return phonemes def transliterate(s: str, mode='random'): phonemes = parser(s) modes = {'cyrillic': 0, 'greek': 1} def convert(p, mode): if TRANSLITERATION.get(p, None): return TRANSLITERATION[p].get(modes.get(mode.lower(), random.randint(0, 1))) return p result = ''.join([convert(p, mode) for p in phonemes]) if result.endswith('σ'): result = result[:-1] + 'ς' for j in [' ' + i for i in punctuation]: result = result.replace(j, j[1]) return result if __name__ == '__main__': print(transliterate(*sys.argv[1:])) </code></pre> <p>Example outputs:</p> <pre><code>In [17]: transliterate('aphrodite', 'cyrillic') Out[17]: 'афрадайтий' In [18]: transliterate('ionization') Out[18]: 'αϊαναζэйσан' In [19]: transliterate('imagination') Out[19]: 'иματζαнэйшаν' In [20]: transliterate('esperanza') Out[20]: 'эσпэранζа' In [21]: transliterate('esperanza', 'Greek') Out[21]: 'εσπερανζα' In [22]: transliterate('esperanza', 'Cyrillic') Out[22]: 'эспэранза' In [23]: transliterate('liberty', 'Cyrillic') Out[23]: 'либэртий' In [24]: transliterate('liberty', 'Greek') Out[24]: 'λιμπερτει' In [25]: transliterate('fraternity', 'Greek') Out[25]: 'φρατερνατει' In [26]: transliterate('fraternity', 'Cyrillic') Out[26]: 'фратэрнатий' In [27]: transliterate('equality', 'Cyrillic') Out[27]: 'иквалатий' In [28]: transliterate('equality', 'greek') Out[28]: 'ικβαλατει' In [29]: transliterate('diversity', 'greek') Out[29]: 'ντιβερσατει' In [30]: transliterate('diversity', 'cyrillic') Out[30]: 'дивэрсатий' In [31]: transliterate('Hello, World!', 'cyrillic') Out[31]: 'халоу, вэрлд!' In [32]: transliterate('Hello, World!', 'greek') Out[32]: 'χαλω, βερλντ!' In [33]: transliterate('Hello, World!') Out[33]: 'χαлоу, вερлд!' In [34]: transliterate(&quot;To be, or not to be, that is the question&quot;) Out[34]: 'ту μπий, ορ νаτ ту бий, зат ιз δα квэσчан' In [35]: transliterate(&quot;He who fights with monsters should look to it that he himself does not become a monster. And when you gaze long into an abyss the abyss also gazes into you.&quot;) Out[35]: 'χει ху фαϊτσ βιδ μαнστερζ σуντ лук ту ιτ зαт χий хιμσэλф νταζ νατ бιкαм α маνστερ. αнντ βэν γου гεϋζ лοнг иντου αν аμπισ δа абισ ολсоу γκэйзαζ интου ю.' </code></pre> <p>How can my script be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:54:45.860", "Id": "529140", "Score": "0", "body": "\"ionization\" appears differently on my machine, as `'айаνаζεϋσаν'`. Is that intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:38:36.660", "Id": "529154", "Score": "0", "body": "oh, I see. Yes, it's intended, because one of your modes is explicitly non-deterministic." } ]
[ { "body": "<p>This is cool! I wonder how pronounce-able the results are by a native Greek speaker. Is that your language?</p>\n<p>Things that could be improved:</p>\n<ul>\n<li>It's not all that useful to represent the values of <code>TRANSLITERATION</code> as dicts. Given that they're all two items long, it's safe to just represent them as 2-tuples</li>\n<li>Whenever compiling a regex with dynamic substrings, ensure that those substrings go through <code>re.escape</code> for safety's sake</li>\n<li>Generally I find that there's a lot of reliance on comprehensions. This isn't the end of the world, but converting them to generator functions improves legibility, and the resulting bytecode will be very similar to a comprehension anyway</li>\n<li>Represent your mode values as enums rather than free strings.</li>\n<li><code>get(p, None)</code> is redundant and can just be <code>get(p)</code></li>\n<li>For the non-random examples you've shown, those are perfect cases for unit tests. For the random ones, you could expand coverage to run them and compare them against regexes with character classes whenever there's variation permitted.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport re\nimport sys\nfrom enum import Enum\nfrom typing import Iterator\n\nfrom g2p_en import G2p\nfrom string import punctuation\n\ng2p = G2p()\n\nARPA2ALPHA = {\n '@': 'a', 'A': 'a', 'AA': 'a', 'AE': 'a',\n 'AH': 'a', 'AO': 'o', 'AW': 'au', 'AX': 'e',\n 'AXR': 'er', 'AY': 'ai', 'B': 'b', 'C': 'ch',\n 'CH': 'ch', 'D': 'd', 'DH': 'dh', 'DX': 't',\n 'E': 'e', 'EH': 'e', 'EL': 'l', 'EM': 'm',\n 'EN': 'n', 'ER': 'er', 'EY': 'ei', 'F': 'f',\n 'G': 'g', 'H': 'h', 'HH': 'h', 'I': 'i',\n 'IH': 'i', 'IX': 'i', 'IY': 'ii', 'J': 'j',\n 'JH': 'j', 'K': 'k', 'L': 'l', 'M': 'm',\n 'N': 'n', 'NG': 'ng', 'NX': 'nn', 'O': 'oi',\n 'OW': 'ou', 'OY': 'oi', 'P': 'p', 'Q': &quot;'&quot;,\n 'R': 'r', 'S': 's', 'SH': 'sh', 'T': 't',\n 'TH': 'th', 'U': 'u', 'UH': 'u', 'UW': 'u',\n 'UX': 'u', 'V': 'v', 'W': 'w', 'WH': 'w',\n 'X': 'i', 'Y': 'y', 'Z': 'z', 'ZH': 'zh',\n 'a': 'a', 'b': 'b', 'c': 'o', 'd': 'd',\n 'e': 'ei', 'f': 'f', 'g': 'g', 'h': 'h',\n 'i': 'ii', 'k': 'k', 'l': 'l', 'm': 'm',\n 'n': 'n', 'o': 'ou', 'p': 'p', 'r': 'r',\n 's': 's', 't': 't', 'u': 'u', 'v': 'v',\n 'w': 'w', 'x': 'e', 'y': 'y', 'z': 'z'\n}\n\nTRANSLITERATION = {\n 'a': ('а', 'α'),\n 'b': ('б', 'μπ'),\n 'd': ('д', 'ντ'),\n 'e': ('э', 'ε'),\n 'f': ('ф', 'φ'),\n 'g': ('г', 'γκ'),\n 'h': ('х', 'χ'),\n 'i': ('и', 'ι'),\n 'j': ('дж', 'τζ'),\n 'k': ('к', 'κ'),\n 'l': ('л', 'λ'),\n 'm': ('м', 'μ'),\n 'n': ('н', 'ν'),\n 'o': ('о', 'ο'),\n 'p': ('п', 'π'),\n 'r': ('р', 'ρ'),\n 's': ('с', 'σ'),\n 't': ('т', 'τ'),\n 'u': ('у', 'ου'),\n 'v': ('в', 'β'),\n 'y': ('й', 'γ'),\n 'z': ('з', 'ζ'),\n 'ai': ('ай', 'αϊ'),\n 'au': ('ао', 'αου'),\n 'ch': ('ч', 'τσ'),\n 'dh': ('з', 'δ'),\n 'dz': ('дз', 'τζ'),\n 'ei': ('эй', 'εϋ'),\n 'er': ('эр', 'ερ'),\n 'ii': ('ий', 'ει'),\n 'ks': ('кс', 'ξ'),\n 'ng': ('нг', 'γγ'),\n 'oi': ('ой', 'οϊ'),\n 'ou': ('оу', 'ω'),\n 'ps': ('пс', 'ψ'),\n 'sh': ('ш', 'σ'),\n 'th': ('т', 'θ'),\n 'ts': ('ц', 'τσ'),\n 'ui': ('уй', 'ουι'),\n 'ya': ('я', 'γα'),\n 'ye': ('е', 'γε'),\n 'yo': ('ё', 'γο'),\n 'yu': ('ю', 'γου'),\n 'zh': ('ж', 'ζ'),\n 'shch': ('щ', 'στσ'),\n &quot;'&quot;: ('ъ', '΄'),\n}\n\nPHONEMES = sorted(\n (\n *TRANSLITERATION.keys(),\n 'ia', 'ie', 'io', 'w',\n ),\n key=len, reverse=True,\n)\n\nPHONEME_REGEX = re.compile(\n '('\n + '|'.join(\n re.escape(p) for p in PHONEMES\n )\n + ')'\n)\nPARSE_SWITCH = {'ia': 'ya', 'ie': 'ye', 'io': 'yo', 'w': 'v'}\n\n\ndef reduce(x: str) -&gt; str:\n if x[0].isalpha():\n return ''.join(i for i in x if i.isalpha())\n return x\n\n\ndef parse_phonemes(s: str) -&gt; Iterator[str]:\n for p in g2p(s):\n phoneme = reduce(p)\n yield ARPA2ALPHA.get(phoneme, phoneme)\n\n\ndef parser(s: str) -&gt; Iterator[str]:\n parsed = ''.join(parse_phonemes(s))\n for i in PHONEME_REGEX.split(parsed):\n if i:\n yield PARSE_SWITCH.get(i, i)\n\n\nclass Mode(Enum):\n CYRILLIC = 0\n GREEK = 1\n RANDOM = 2\n\n\ndef convert(p: str, mode: Mode) -&gt; str:\n trans = TRANSLITERATION.get(p)\n if trans:\n if mode == Mode.RANDOM:\n index = random.randrange(2)\n else:\n index = mode.value\n return trans[index]\n return p\n\n\ndef transliterate(s: str, mode: Mode = Mode.RANDOM) -&gt; str:\n phonemes = parser(s)\n result = ''.join(convert(p, mode) for p in phonemes)\n if result.endswith('σ'):\n result = result[:-1] + 'ς'\n for i in punctuation:\n j = ' ' + i\n result = result.replace(j, i)\n return result\n\n\ndef test() -&gt; None:\n assert transliterate('aphrodite', Mode.CYRILLIC) == 'афрадайтий'\n assert transliterate('esperanza', Mode.CYRILLIC) == 'эспэранза'\n assert transliterate('liberty', Mode.CYRILLIC) == 'либэртий'\n assert transliterate('fraternity', Mode.CYRILLIC) == 'фратэрнатий'\n assert transliterate('equality', Mode.CYRILLIC) == 'иквалатий'\n assert transliterate('diversity', Mode.CYRILLIC) == 'дивэрсатий'\n assert transliterate('Hello, World!', Mode.CYRILLIC) == 'халоу, вэрлд!'\n\n assert transliterate('esperanza', Mode.GREEK) == 'εσπερανζα'\n assert transliterate('liberty', Mode.GREEK) == 'λιμπερτει'\n assert transliterate('fraternity', Mode.GREEK) == 'φρατερνατει'\n assert transliterate('equality', Mode.GREEK) == 'ικβαλατει'\n assert transliterate('diversity', Mode.GREEK) == 'ντιβερσατει'\n assert transliterate('Hello, World!', Mode.GREEK) == 'χαλω, βερλντ!'\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:34:57.620", "Id": "529242", "Score": "0", "body": "One small nitpick — I think `typing.Iterator` is a slightly more precise return-value type hint for simple generators than `typing.Iterable`. (Other than that, great review, as usual!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:44:50.037", "Id": "529243", "Score": "0", "body": "@AlexWaygood Thank you <3 and you're right! `Iterator` is more specific; however, the [documentation](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator) indicates that that applies to classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T16:22:25.120", "Id": "529256", "Score": "0", "body": "Hrmm, it says the same thing about `Iterable` too, though, right? https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable Both are listed as valid ways of annotating the return types of simple generator functions in the documentation for the `typing` module https://docs.python.org/3/library/typing.html#typing.Generator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T01:02:14.667", "Id": "529487", "Score": "1", "body": "@AlexWaygood That's true. I'm in the habit of using `Iterable` for iterators but I think I should change to `Iterator`. I'd also confused `Iterator` with `Generator` which has a more complicated interface." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T22:46:12.690", "Id": "268361", "ParentId": "268331", "Score": "4" } } ]
{ "AcceptedAnswerId": "268361", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T10:27:23.840", "Id": "268331", "Score": "3", "Tags": [ "python", "python-3.x", "converting" ], "Title": "Python 3 script to phonetically transliterate written English to Cyrillic and/or Greek" }
268331
<p><strong>Shared below is a functionality test. I would love to get some review from the community. Thank you.</strong></p> <p>The idea of the system is a simple CLI application which can be used to download PDF from a given URL. For more information please visit <a href="https://github.com/PythonCheatsheet/downloadpdf" rel="nofollow noreferrer">https://github.com/PythonCheatsheet/downloadpdf</a>.</p> <p><em><strong>Test Code</strong></em></p> <pre><code>#!/usr/bin/env python3 import logging import unittest import os import shutil import tracemalloc from util.log import initilaizeLog from util.storage import storagePath from util.header import setHeaders from main.scrap import scrapHREF from main.download import downloadPDF class TestDownloadPDF(unittest.TestCase): os.environ[&quot;DEBUG&quot;] = &quot;TRUE&quot; url = '' folder = '' pdfFileExists = False def setUp(self): super(TestDownloadPDF, self).setUp() initilaizeLog() def test_shouldDownloadFromAthena(self): self.folder = 'athena.ecs.csus.edu' self.url = 'http://athena.ecs.csus.edu/~buckley/CSc191/' location = storagePath(self.url) setHeaders(self.url) pdfs = scrapHREF(self.url) self.assertIsNone(downloadPDF(self.url, location, pdfs)) self.fileAndFolderExists(self.folder) def test_shouldDownloadFromWTF(self): self.folder = 'wtf.tw' self.url = 'https://wtf.tw/ref/' location = storagePath(self.url) setHeaders(self.url) pdfs = scrapHREF(self.url) self.assertIsNone(downloadPDF(self.url, location, pdfs)) self.fileAndFolderExists(self.folder) def fileAndFolderExists(self, folder): self.assertTrue(os.path.exists('/tmp/' + folder)) for fname in os.listdir('/tmp/' + folder): if fname.endswith('.pdf'): self.pdfFileExists = True break self.assertTrue(self.pdfFileExists) def tearDown(self): super(TestDownloadPDF, self).tearDown() urlPart = self.url.split(&quot;//&quot;)[1] folderName = urlPart.split(&quot;/&quot;)[0] location = '/tmp/' + folderName if os.path.exists(location): shutil.rmtree(location) logging.shutdown() self.url = '' self.pdfFileExists = False self.folder = '' </code></pre> <p><strong>Core Logic</strong></p> <pre><code>#!/usr/bin/env python3 import logging import os from urllib import request from urllib.parse import unquote def downloadPDF(url, storage, pdfs): for link in pdfs: decodedFileName = link.get('href') unquoteFileName = unquote(decodedFileName) request.urlretrieve(url + '/' + decodedFileName, storage + '/' + unquoteFileName) if (os.environ.get('DEBUG')): break </code></pre> <p><strong>Web Scraper</strong></p> <pre><code>#!/usr/bin/env python3 import re from urllib import request from bs4 import BeautifulSoup def scrapHREF(url): html = request.urlopen(url).read() soup = BeautifulSoup(html, features=&quot;html.parser&quot;) pdfs = soup.findAll(&quot;a&quot;, href=re.compile(&quot;pdf&quot;)) if len(pdfs) == 0: raise Exception('No PDFs found at ' + url) return pdfs </code></pre>
[]
[ { "body": "<p>It's good to learn to write tests.</p>\n<p>That said, these tests are more complicated, error-prone, and breakable by far than your actual logic, so consider whether they would be worth it in a real project. They are also longer than the code, which is perfectly normal for tests.</p>\n<h3>General Style</h3>\n<p>You have repetition. Factor this out and call it from two places:</p>\n<pre><code>location = storagePath(self.url)\nsetHeaders(self.url)\npdfs = scrapHREF(self.url)\n\nself.assertIsNone(downloadPDF(self.url, location, pdfs))\nself.fileAndFolderExists(self.folder)\n</code></pre>\n<p>Replace your custom &quot;/tmp&quot; logic with python's <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">tempfile</a>, which among other things suports deleting the directory for you.</p>\n<p><code>initilaizeLog</code> is misspelled. american english <code>initialize</code> is most common (brits use <code>-ise</code> instead). <code>scrapHREF</code> should be <code>scrapeHREF</code> and <code>main.scap</code> should be <code>main.scrape</code>. You &quot;scape&quot; a web page in a process called web &quot;scaping&quot; (scrape-ing).</p>\n<h2>Test-specific Style</h2>\n<p>You have a lot of general logic and <code>if</code> branches and the like. In a test, it's better to assert that exactly what you think happens, happens. Unless it's to avoid repetition, hardcode everything instead of calculating it.</p>\n<p>The less logic you have, the better the chance that you can't mess the test up. For example, re-write</p>\n<pre><code>for fname in os.listdir('/tmp/' + folder):\n if fname.endswith('.pdf'):\n self.pdfFileExists = True\n break\nself.assertTrue(self.pdfFileExists)\n</code></pre>\n<p>As the more specific and straightforward:</p>\n<pre><code>files = os.listdir('/tmp/' + folder)\nself.assertEqual(files, [&quot;a.pdf&quot;, &quot;b.pdf&quot;])\n</code></pre>\n<p><code>scrapHREF</code> should not be done by the test and then not examined. In general, tests should not do any &quot;real&quot; work, they should only call functions and test the results. I would recommend breaking it into two tests:</p>\n<ul>\n<li>Test that <code>scapHREF</code> returns what you expect in a first test</li>\n<li>Use the <strong>expected</strong> result as the input to downloadPDF in a second test.</li>\n</ul>\n<p>Finally, these tests depend on an external website. If that website goes down or changes, your tests will fail. This is the downside to an integration test like this when testing web scraping.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T06:21:13.093", "Id": "530461", "Score": "0", "body": "Thank you for the review @zachary-vance. Typo-fixes recommendations are fine. \n\nA FYI, the `if fname.endswith('.pdf'):` condition is used as I think that on validating the functionality with at least one PDF file must have been downloaded and the test should exit without checking for all downloaded files. \n\nI am curious about your starting phrase about brittle tests and was wondering if you would share some insights on how to write, or how would you write production grade tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T00:28:06.460", "Id": "530792", "Score": "0", "body": "The word brittle doesn't appear in my answer. Could be more specific? A - The original test will fail/pass when it shouldn't if: (1) Cleanup doesn't happen between tests (2) Your downloader saves the PDF with the wrong name (3) Your downloader downloads only SOME of the PDFs (4) The external website goes down\n\nB - If you match against the exact PDFs, then it will fail if (4) The external website goes down or (5) The list of PDFs changes.\nC - If you test against your own website, for example by running a tiny server as part of the test, then there should be no failure modes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T00:18:22.903", "Id": "268868", "ParentId": "268333", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T11:56:40.963", "Id": "268333", "Score": "3", "Tags": [ "python", "python-3.x", "unit-testing" ], "Title": "Functional tests of downloadpdf, a python CLI app" }
268333
<p>I have written the following cli tool.</p> <pre><code>import sys import argparse parser = argparse.ArgumentParser(prog='remove-duplicate-lines-except-blank-lines', usage='%(prog)s [options] [files...]', description='Remove duplicate line except white space') args = parser.parse_known_args() command_line_arguments = sys.argv[1:] lines_seen = set() # holds lines already seen if sys.stdin.isatty() and (len(command_line_arguments) == 0): # has neither stdin nor file as input. Show help and exit. parser.print_help() sys.exit(&quot;Please give some input&quot;) if len(command_line_arguments) &gt; 1: # 2 or more arguments, so read from file, write to file try: infile = open(sys.argv[1], &quot;r&quot;) except FileNotFoundError: sys.exit(&quot;Input File Not Found&quot;) outfile = open(sys.argv[2], &quot;w&quot;) elif len(command_line_arguments) &gt; 0: # one argument if sys.stdin.isatty(): # one argument and stdin does not have value, so read from file and write to stdout try: infile = open(sys.argv[1], &quot;r&quot;) except FileNotFoundError: sys.exit(&quot;Input File Not Found&quot;) outfile = sys.stdout else: # one argument and stdin has value, so read from stdin and write to file infile = sys.stdin outfile = open(sys.argv[1], &quot;w&quot;) else: # no arguments, so read from stdin and write to stdout infile = sys.stdin outfile = sys.stdout for line in infile: if line not in lines_seen: outfile.write(line) if line != &quot;\n&quot;: lines_seen.add(line) if infile is not sys.stdin: infile.close() if outfile is not sys.stdin: outfile.close() </code></pre> <p>The purpose of this tool is to remove duplicate lines (except blank lines). It ignores blank lines.</p> <p>It has <code>--help</code> and <code>-h</code> to get help.</p> <p>The logic here is, it takes input from stdin or input-file. It gives output to <code>stdout</code> or output-file. So, total four combinations.</p> <ul> <li>input from stdin and output to stdout</li> <li>input from stdin and output to output-file</li> <li>input from input-file and output to stdout</li> <li>input from input-file and output to output-file</li> </ul> <p>There is a special case where there is no input (neither from stdin nor from input-file). Which is covered using:</p> <pre><code>if sys.stdin.isatty() and (len(command_line_arguments) == 0): # has neither stdin nor input file parser.print_help() sys.exit(&quot;Please give some input&quot;) </code></pre> <p>The problem with this code is, the logic seems over complicated. too many conditions giving me the sense that something is wrong here. However, because of these conditions, it has become very hard to test the code.</p> <p>Another problem with the code is the help, which looks like:</p> <pre><code>usage: remove-duplicate-lines-except-blank-lines [options] [files...] Remove duplicate line except white space optional arguments: -h, --help show this help message and exit </code></pre> <p>I am also looking for feedback on how to make the help option better. Given few things are not clear (mentioned bellow in bullet point) just by looking at <code>usage: remove-duplicate-lines-except-blank-lines [options] [files...]</code>. I am also not clear on how to write the usage properly.</p> <ul> <li>When there is stdin and one file as argument, the file is considered as output-file.</li> <li>When there is no stdin and one file as argument, the file is considered as input-file, and the output goes to the stdout.</li> </ul> <p>I want to keep this piece of code as a template for future cli apps written in python. So, your critique is very important for me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T11:17:08.093", "Id": "529440", "Score": "5", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>A few comments in no particular order:</p>\n<ul>\n<li>When reading, you are doing just fine, as you are processing one line at a time. However, you are storing the lines you read in memory. This could cause the program using lots of memory if reading long files.</li>\n</ul>\n<p>This has a simple solution as you don't really need to keep the lines in memory. All you really want is knowing whether a line has been seen before. To do that, simply hash the lines.</p>\n<ul>\n<li>As you have already stated in your concerns about how to write the help message, it is kind of hard to explain what your code does.That's simply because I find the core logic of argument parsing is kind of difficult.</li>\n</ul>\n<p>Just have a look at the <code>cat</code> <a href=\"https://man7.org/linux/man-pages/man1/cat.1.html\" rel=\"nofollow noreferrer\">manual</a>: it's really simple and intuitive, if any arguments are given, they are input files to be read. Otherwise, just read from stdin. Then, if you want to write to a file, use the already existent <code>&gt;</code> syntax to write stdout to a file.</p>\n<p>Maybe you could change your code logic to be like that.</p>\n<ul>\n<li><p>When writing a CLI, I'd recommend you to use an already existing library, like <a href=\"https://click.palletsprojects.com/en/8.0.x/\" rel=\"nofollow noreferrer\">click</a> or <a href=\"https://google.github.io/python-fire/guide/\" rel=\"nofollow noreferrer\">fire</a> (I personally like fire better, as there is less code to write). That hides all the complexity of parsing arguments under the library, and forces you to better organise your code by creating functions.</p>\n</li>\n<li><p>Your handling of files is not taking advantage of the <code>with</code> statement (due to not having extracted the core logic of your code of removing repeated lines into a function). This makes you have to manually close the input and output files, which isn't fail-safe: if you have any exception, the file closing will not be controlled. Also, you will close stdin or stdout in some cases, which seems a bit nasty (I'm not sure if the same applies to python, but <a href=\"https://stackoverflow.com/questions/288062/is-close-fclose-on-stdin-guaranteed-to-be-correct\">here</a> is a question about closing stdin in <code>C</code>).</p>\n</li>\n</ul>\n<h2>Edit</h2>\n<p>Here is a sample code of how you could update it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\nfrom typing import TextIO\nimport sys\n\nimport fire\n\ndef _remove_duplicates(input_file: TextIO, output_file: TextIO) -&gt; None:\n found_lines_hash = set()\n for line in input_file:\n line_hash = hash(line)\n if not line_hash in found_lines_hash:\n if line != &quot;\\n&quot;:\n found_lines_hash.add(line_hash)\n output_file.write(line)\n\ndef remove_duplicates(input_file_path: str) -&gt; None:\n input_file_path = Path(input_file_path)\n if not input_file_path.exists():\n print(f&quot;File does not exist '{input_file_path}'&quot;)\n return\n with input_file_path.open() as input_file:\n _remove_duplicates(input_file, sys.stdout)\n\nif __name__ == &quot;__main__&quot;:\n fire.Fire(remove_duplicates)\n</code></pre>\n<p>Then, you would run it like:</p>\n<pre><code>$ python remove_duplicates.py /path/to/my/input/file &gt; /path/to/output\n</code></pre>\n<p>To handle the stdin case you could add another function that also calls <code>_remove_duplicates</code>.</p>\n<p>I have to say I haven't been able to run the code, as I have written it from my phone. But you get the idea</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T04:18:39.510", "Id": "529330", "Score": "0", "body": "I am not using `with` statement because, `infile` can be `open(sys.argv[1], \"r\")` or `sys.stdin`, and `outfile` can be `open(sys.argv[1], \"w\")` or `open(sys.argv[2], \"w\")`, or `sys.stdout`. Can you please edit the code to extracted the core logic and use `with`. This will be very helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:58:01.463", "Id": "529355", "Score": "1", "body": "If I have some time later on I might try to write it. The idea would be: extract the actual logic of removing duplicates to a function that receives `infile` and `outfile` as parameters. In each of the if statements use a with statment to open the corresponding file (or just choose the corresponding std descriptor), and pass the file descriptor to the function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T20:06:15.970", "Id": "529475", "Score": "0", "body": "@blueray I have updated my answer to show how your code could be modified" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:41:28.700", "Id": "268350", "ParentId": "268336", "Score": "2" } }, { "body": "<p>The absence of declared functions is a clear indication of how you can better organize your code.<br />\nAlso, you're using <code>argparse</code>, which is good, but you're bypassing it in several ways, which isn't.</p>\n<p>Regarding <code>argparse</code>:</p>\n<ul>\n<li>Don't write your own <code>usage</code> if you can help it; let the parser write it based on it's own configuration. If you need to add additional notes, here's some copypasta from a tool of my own to &quot;have your cake and eat it&quot;:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def removeprefix(s, p): -- only needed for python versions &lt;3.9\n return s[len(p):] if s.startswith(p) else s\n\nparser.usage = (\n removeprefix(parser.format_usage(), 'usage: ')\n + &quot; (... my notes to users ...)&quot;\n)\n</code></pre>\n<ul>\n<li>Check out the examples in the <a href=\"https://docs.python.org/3.8/library/argparse.html#nargs\" rel=\"nofollow noreferrer\">docs for the <code>nargs</code> option</a>. Specifically I think you'll be able to use some combination of <code>'?'</code>, <code>'*'</code>, <code>'+'</code>, and <code>argparse.REMAINDER</code> to bind the input and output files.</li>\n<li>It's nice to give all your arguments optional names, so if a user wants to be explicit they can.</li>\n<li>Check out <a href=\"https://docs.python.org/3.8/library/argparse.html#filetype-objects\" rel=\"nofollow noreferrer\">FileType args</a>! I've never used them, but they look pretty cool! (It's unclear how/if you're supposed to close them though?)</li>\n</ul>\n<p>Other stuff:</p>\n<ul>\n<li><em>Do</em> have a core function that takes an open &quot;file&quot; to read from and an open file to write to.</li>\n<li>Why are you checking <code>sys.stdin.isatty()</code>? The comment suggests you think it's checking if <code>stdin</code> is available, but it's actually checking for an interactive shell. I see no reason you shouldn't be able to pipe streams into this program.</li>\n<li>What if I want to read from several files in sequence, removing duplicate lines from the whole batch? One could write <code>cat A.txt B.txt C.txt | rdlebl &gt; D.txt</code> (and relying on piping like this <em>is</em> a valid option!), but if your program is going to have built-in file management then it might as well be able to handle multiple files.</li>\n<li>Use <code>with</code> blocks to manage open files.</li>\n<li>What about non-newline whitespace? If a line is <code>&quot; \\n&quot;</code>, should it be treated as empty?</li>\n</ul>\n<h1>Edit</h1>\n<p>Since m-alorda added a code, I stopped resisting the urge to write my own. It was fun; I hope it's useful!</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser, FileType, REMAINDER\nfrom itertools import chain\nfrom sys import stdin\n\n# Not Implemented:\n# Whitespace options\n# Text-encoding options\n# [Don't] clobber options\n# Output as a positional argument\n\ndef main():\n args = get_args()\n deduper = Deduper()\n # I didn't see a way for argparse to have a default value\n # for args that merge, but maybe I missed something.\n sources = chain.from_iterable(args.source) if args.source else stdin\n for line in deduper.dedup(sources):\n args.out.write(line)\n\n# If you think inheriting from set is sketchy, wrap set in a dataclass.\nclass Deduper(set):\n def dedup(self, source):\n for line in source:\n # this behavior isn't exactly the same as yours.\n stripped = line.strip()\n if stripped:\n if stripped not in self:\n yield line\n self.add(stripped)\n else:\n yield '\\n'\n\ndef get_args():\n arg_parser = ArgumentParser(description=&quot;Remove duplicate lines.&quot;)\n arg_parser.add_argument('-o', '--out',\n default='-',\n type=FileType(mode='w'),\n metavar='FILE',\n help=&quot;The file to write to, defaults to stdout.&quot;)\n arg_parser.add_argument('-f', '--file',\n dest='source',\n action='append',\n type=FileType(mode='r'),\n metavar='FILE',\n help=&quot;A file to read from, or - for stdin.&quot;)\n arg_parser.add_argument('source',\n action='extend', # assumes python version &gt;=3.8\n nargs='*',\n type=FileType(mode='r'),\n metavar='FILE',\n help=&quot;The file(s) to read from, defaults to stdin.&quot;)\n return arg_parser.parse_args()\n\nif __name__ == '__main__':\n main()\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:59:36.353", "Id": "268481", "ParentId": "268336", "Score": "2" } }, { "body": "<p>OP here, the rewrite of the program looks like:</p>\n<pre><code>import sys\nimport argparse\n\nlines_seen = set() # holds lines already seen\n\nparser = argparse.ArgumentParser()\nparser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)\nargs = parser.parse_args()\n\n# taking input from stdin which is empty, so there is neither a stdin nor a file as argument\nif sys.stdin.isatty() and args.infile.name == &quot;&lt;stdin&gt;&quot;:\n sys.exit(&quot;Please give some input&quot;)\n\nfor line in args.infile:\n if line not in lines_seen:\n print(line)\n if line != &quot;\\n&quot;:\n lines_seen.add(line)\n</code></pre>\n<p>Here, you can see that I am not taking <code>output-file</code> as argument at all. This is because, by using <code>&gt;</code> we can redirect the program's output anyways. So, taking output as argument just increase the complexity of the program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:09:49.890", "Id": "529520", "Score": "0", "body": "Hi, if you want to submit this code to answer your question, it's fine. However, if you'd like the code to be reviewed, you should post another question and add a link to this original post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:39:44.610", "Id": "529528", "Score": "0", "body": "@m-alorda , I accepted one answer, gave bounty to another, and this is for me for future reference." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T04:46:05.943", "Id": "268492", "ParentId": "268336", "Score": "0" } } ]
{ "AcceptedAnswerId": "268350", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T13:00:21.333", "Id": "268336", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Template For a CLI Application" }
268336
<p>This was my solution to an interview question:</p> <p>Q: Implement an std::vector style container (does not have to be exactly compatible) with a fixed buffer and the following requirements and restrictions:</p> <ul> <li>The fixed buffer size should be provided by a template parameter.</li> <li>No dynamic memory allocations are allowed.</li> <li>Implement a “push_back” function that places an element to the end of the container if there is still room.</li> <li>Implement an “insert” function that inserts an element into a given position and moves other elements.</li> <li>Implement an “operator[]” function for the query of an element at a given index.</li> <li>Implement a “size” function, which returns the actual length of the vector</li> </ul> <p>My solution:</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;cstddef&gt; #include &lt;stdexcept&gt; #ifndef NDEBUG #include &lt;iostream&gt; #endif /* !defined NDEBUG*/ /** * @brief A vector with a fixed storage buffer implementing part of the std::vector interface */ template&lt;int BUFFER_SIZE, typename T&gt; class Stable_vector{ public: /** * @brief Syntax sugar to initialize the vector from { ,,, } * * @param[in] list The initializer list */ Stable_vector (std::initializer_list&lt;T&gt; list) { for (auto i = list.begin(); i != list.end(); i++)push_back(*i); } Stable_vector (void){ } /** * @brief Pushes an element into the array if there is capacity * * @param[in] data The data to be pushed back */ void push_back(T data){ if(BUFFER_SIZE &gt; used_elements){ internal_buffer[used_elements] = data; #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;push_back: Pushing value &quot; &lt;&lt; data &lt;&lt; &quot; to [&quot;&lt;&lt; used_elements &lt;&lt;&quot;]&quot;&lt;&lt; std::endl; #endif /* !defined NDEBUG*/ ++used_elements; }else throw std::runtime_error(&quot;Vector Out of capacity!&quot;); } /** * @brief Pops an element from the array if there is any * * @return The copy of the element removed from the vector. * It returns with a copy on purpose, as a reference would poit to a buffer * item which may be overwritten later. */ T pop_back(void){ if(0u &lt; used_elements){ #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;pop_back: Popping out internal buffer[&quot;&lt;&lt; (used_elements - 1u) &lt;&lt;&quot;] -&gt; &quot; &lt;&lt; internal_buffer[used_elements - 1u] &lt;&lt; std::endl; #endif /* !defined NDEBUG*/ --used_elements; return internal_buffer[used_elements]; /* as @used elements represents size and not index, it is at the correct position after the decrease */ }else throw std::runtime_error(&quot;Nothing to pop from the Vector!&quot;); } /** * @brief Pushes an element into the given index in case it is inside the used capacity * of the vector. The last previously stored item is lost when the vector is at * full capacity. * * @param[in] data The data to be inserted * @param[in] index The index to insert the data at */ void insert(T data, std::size_t index){ #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;insert: Trying to put value &quot;&lt;&lt; data &lt;&lt;&quot; into [&quot;&lt;&lt; index &lt;&lt;&quot;]&quot; &lt;&lt; std::endl; #endif /* !defined NDEBUG*/ if(used_elements &gt; index){ if(BUFFER_SIZE &gt; used_elements){ #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;insert: Pushing back the last item because (&quot;&lt;&lt; BUFFER_SIZE &lt;&lt;&quot;&gt;&quot;&lt;&lt; used_elements &lt;&lt;&quot;)&quot; &lt;&lt; std::endl; #endif /* !defined NDEBUG*/ this-&gt;push_back(this-&gt;back()); /*!Note: by now it is guaranteed that there is at least 1 element in the vector * because of the unsignedness of @index; In case (@used_elements &gt; @index) * @used_elements is at least 1 in this block. */ } /* Copy the items from the index until the end */ for(int copy_index = (used_elements - 1u); copy_index &gt;= index; --copy_index){ (*this)[copy_index] = (*this)[copy_index - 1u]; #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;insert: Copying [&quot;&lt;&lt; (copy_index - 1) &lt;&lt; &quot;]{&quot;&lt;&lt; (*this)[copy_index - 1] &lt;&lt; &quot;}&quot; &lt;&lt; &quot; to [&quot;&lt;&lt; copy_index &lt;&lt; &quot;]&quot; &lt;&lt; std::endl; #endif /* !defined NDEBUG*/ } #ifndef NDEBUG std::cout &lt;&lt; this &lt;&lt; &quot;-&gt;insert: Finally [&quot;&lt;&lt; index &lt;&lt; &quot;] = &quot;&lt;&lt; data &lt;&lt; std::endl; #endif /* !defined NDEBUG*/ (*this)[index] = data; }else throw std::runtime_error(&quot;Index Out of bounds&quot;); } /** * @brief Returns the number of elements stored in the vector * * @return The number of elements */ std::size_t size(void) const{ return used_elements; } /** * @brief Array indexer operator. * * @param[in] index The index * * @return Non-const reference to the stored element or a tasty std::runtime_error */ T&amp; operator[](std::size_t index){ if(used_elements &gt; index){ return internal_buffer[index]; }else throw std::runtime_error(&quot;Index Out of bounds&quot;); } /** * @brief Provides the last stored element in the vector if there is any * * @return Non-const reference to the stored element or a tasty std::runtime_error */ T&amp; back(void){ if(0u &lt; used_elements){ return internal_buffer[used_elements - 1u]; }else throw std::runtime_error(&quot;No elements to provide!&quot;); } private: T internal_buffer[BUFFER_SIZE]; std::size_t used_elements = 0u; }; </code></pre> <p>I already sent it, but I'd like to get better at what I do. What could be improved with this? Thank you in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:29:54.280", "Id": "529152", "Score": "3", "body": "Have a read of the 5 articles I wrote about creating your own vector class. https://lokiastari.com/series/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T22:40:00.193", "Id": "529194", "Score": "1", "body": "In real-world use, you would use `std::array`. In a code interview, you might as well mention that you know this, before demonstrating that you do know how to write one from scratch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T22:46:32.060", "Id": "529195", "Score": "3", "body": "I’m not a big fan of putting instrumentation with `cout <<` inside `#ifndef NDEBUG` blocks, because that leaves no way to disable them but enable assertions. Also, I prefer sending instrumentation to `cerr`/`stderr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:33:12.440", "Id": "529233", "Score": "0", "body": "Which version of C++ were you supposed to target?" } ]
[ { "body": "<p>This is not a bad attempt at making a vector-like container, except it is lacking support for <code>const</code> and makes unnecessary copies (see below for a more detailed explaination). The variable names are quite well chosen. It's also good to see Doxygen documentation.</p>\n<h1>Use <code>std::size_t</code> for the size of the storage</h1>\n<p>The template parameter <code>BUFFER_SIZE</code> should have type <code>std::size_t</code>. This will then also consistent with the type of <code>used_elements</code>. <code>std::size_t</code> is almost always the right type for sizes, counts and indices.</p>\n<h1>Omit <code>void</code> from empty parameter lists</h1>\n<p>Functions that don't take parameters should be declared as <code>foo()</code>, not <code>foo(void)</code>. The latter is necessary for C, but not for C++.</p>\n<h1>Use <code>= default</code> to generate a default constructor</h1>\n<p>If you want the compiler to create a default constructor that takes no arguments, use <code>= default</code> to declare it:</p>\n<pre><code>Stable_vector() = default;\n</code></pre>\n<p>The same would go for other constructors and for destructors. By explicitly defining a constructor with an empty body, the compiler will treat it as a user-defined constructor, which sometimes might have some subtle consequences, although it doesn't matter for your class.</p>\n<h1>Use a consistent code style</h1>\n<p>I see that sometimes your use of spaces is not consistent, which makes the code look a bit messy. You also sometimes have two statements on the same line; try to limit it to one statement per line. Use a consistent <a href=\"https://en.wikipedia.org/wiki/Programming_style\" rel=\"noreferrer\">code style</a> (which one you use exactly is of less importance). Instead of fixing everything yourself manually, either check if your code editor has a function to reformat the code, or use an external tool such as <a href=\"http://astyle.sourceforge.net/\" rel=\"noreferrer\">Artistic Style</a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"noreferrer\">ClangFormat</a>.</p>\n<h1>Remove debug statements from your code</h1>\n<p>Debug statements are helpful during initial development and for finding bugs, but it makes the code harder to read. I recommend you remove them, and only temporarily add them back as necessary.</p>\n<h1>Avoid unnecessary copies</h1>\n<p>Your <code>push_back()</code> function takes <code>data</code> by value, causing a copy to be made. It then makes another copy when storing it in the <code>internal_buffer</code>. Have a look at <a href=\"https://en.cppreference.com/w/cpp/container/vector/push_back\" rel=\"noreferrer\"><code>std::vector::push_back()</code></a>: you'll note it has two variants, one that takes a <code>const</code> reference, and the other which takes a forwarding reference. The first one just avoids the first copy, the second one also allows you to <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"noreferrer\"><code>std::move()</code></a> <code>data</code> into <code>internal_buffer</code>, which might avoid part of the second copy, if <code>T</code> has a <a href=\"https://en.cppreference.com/w/cpp/language/move_assignment\" rel=\"noreferrer\">move assignment operator</a>.</p>\n<p>The same goes for <code>insert()</code> of course.</p>\n<h1>Don't let <code>pop_back()</code> return an element</h1>\n<p>You'll notice that <a href=\"https://en.cppreference.com/w/cpp/container/vector/pop_back\" rel=\"noreferrer\"><code>std::vector::pop_back()</code></a> is a function that returns <code>void</code>. Instead, you're supposed to use <a href=\"https://en.cppreference.com/w/cpp/container/vector/back\" rel=\"noreferrer\"><code>back()</code></a> to get a <em>reference</em> to the back element, allowing you to read it without making a copy, and then you can remove it with <code>pop_back()</code> afterwards.</p>\n<h1>Add <code>const</code> versions of <code>operator[]</code> and <code>back()</code></h1>\n<p>Since your <code>operator[]</code> and <code>back()</code> are not <code>const</code> functions, they can't be used with a <code>const Stable_vector</code>. You have to add <code>const</code> versions of them (that return <code>const T&amp;</code> of course) to solve this issue.</p>\n<h1>Mark functions that don't throw exceptions <code>noexcept</code></h1>\n<p>If you mark functions that will never throw exceptions as <code>noexcept</code>, this will help the compiler generate more optimal code.</p>\n<h1>Copy the API of STL containers as much as possible</h1>\n<p>Have a look at the API of <code>std::vector</code> and follow it as closely as possible, not just the syntax but also the semantics. For example, <code>operator[]</code> does not do bounds checking and will not throw, but there is an <a href=\"https://en.cppreference.com/w/cpp/container/vector/at\" rel=\"noreferrer\"><code>at()</code></a> that does do this. While perhaps not mentioned in the requirements for your interview, it would also be nice to add <code>front()</code>, <code>begin()</code> and <code>end()</code>, <code>emplace_back()</code> and so on, so that your class will be a drop-in replacement for a regular <code>std::vector</code>.</p>\n<h1>Keep it professional</h1>\n<p>The code and comments look fine except for the &quot;tasty&quot; exceptions. Avoid making jokes in the code; it doesn't look professional, and it might actually be confusing for non-native speakers that might also need to work on the same code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:30:03.833", "Id": "529230", "Score": "2", "body": "I'd like to disagree with the `pop_back` advice. Having `back()` is good, but being able to pop is great. Do ensure it's a _move_, not a copy, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:31:56.967", "Id": "529232", "Score": "0", "body": "@MatthieuM. Sure, but then it would only work for types that are movable or copyable. By separating popping from accessing the element, the container will work for types that are neither." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:36:32.683", "Id": "529234", "Score": "3", "body": "You are technically correct -- and this is likely why `std::vector` does so -- however the curse of \"hyper-genericity\" that hampers the standard library is best not emulated. Non-moveable objects are _really_ rare. _Really_, _really_, rare. Constraining an interface to accommodate even the weirdest usecases at the cost of general ergonomics is a poor trade-off. Let the weirdest usecases call `auto x = v.back(); v.erase(v.end()-1);` and let the 99.9% of other use `auto x = v.pop_back();`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:49:51.033", "Id": "529235", "Score": "0", "body": "@MatthieuM. They are not *really really* rare, `std::mutex` is an obvious one, `std::atomic<>` is another one. It is exactly because the STL containers handle even the weirdest usecases that they are so useful. If you just want something that works for your own project, sure, only implement what you need. But if you want to make something genericly useful, you should make sure it handles these usecases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:28:44.027", "Id": "529241", "Score": "1", "body": "We'll have to agree to disagree on that one, then, I am afraid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:35:53.973", "Id": "529269", "Score": "2", "body": "Not being hyper-generic sounds appropriate for a custom container that nobody's proposing for a standard library. It's worth *noting* in a comment that this is something you'd need to change if you want to support that rare corner case, though. Can you have a template specialization for `<T>` that's copyable or movable to add a value-returning `pop` function? If you can find a name for it that isn't confusing, e.g. `pop_back` is used by `std::vector` to mean something else, so it's not a great choice. Maybe `pop_back_value`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:39:23.963", "Id": "529270", "Score": "0", "body": "I think @MatthieuM. meant rarity by fraction of actual containers in real code, not rarity by classes in real code. Yes, `std::atomic` is an example, but how many programs have a `std::vector< std::atomic<int> >`? There are definitely Stack Overflow Q&As about the error messages you get from trying to do that (anything that might reallocate won't compile), so some people may have gone ahead and used it in the limited ways that are possible. Or `std::array< std::atomic<int> >` is even more likely. But that's still a *very* small fraction of total uses of STL containers in C++ codebases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T20:01:21.600", "Id": "529278", "Score": "0", "body": "Since you mention the template param type, it might be interesting to specialize `used_elements` to just be an `unsigned int` with `std::conditional< BUFFER_SIZE<= ...limits<unsigned>::max , unsigned, std::size_t >`. That would save a bit of space on e.g. 64-bit systems for non-huge instances (only when alignof(T)<alignof(size_t) though, otherwise the class has padding). And reduces the alignment requirement of the container class in that case. (IDK if that's worth posting as a separate answer.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T20:35:21.320", "Id": "529279", "Score": "2", "body": "@PeterCordes It should indeed be possible to do a template specialization, or with C++17 you can just have an `auto` return type and do `if constexpr(can_move_or_copy<T>) return value; else return;`. I'll just say that the STL approach avoids the whole issue, and matching STL API and semantics is usually a good thing. I would create an out-of-class `pop_back_value()` convenience function that works for any container that has `pop_back()` and `back()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T10:06:03.493", "Id": "529295", "Score": "1", "body": "@PeterCordes: The dirty truth about `std::vector` is that it's nigh impossible to use on non-movable, non-copyable types, no matter how hard `pop_back` tries. Any function which adds an element requires the ability to grow the storage and move/copy the elements, any function which erases an element requires the ability to move/copy the other elements to fill the gap. The real reason for `pop_back` not returning a value is due to its _age_: it was standardized prior to move semantics, and not returning simplifies exception handling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T12:29:39.487", "Id": "529299", "Score": "0", "body": "@MatthieuM.: Yeah, following the [stdatomic] tag on SO, I've seen the evidence of how limited the things you can do with it are, without hacks like writing a wrapper or derived class to add copy constructors that you don't intend to ever get used (which would solve the `push_back` problem too). Interesting point about other reasons, that makes sense." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T13:55:21.690", "Id": "268338", "ParentId": "268337", "Score": "12" } }, { "body": "<blockquote>\n<pre><code> T internal_buffer[BUFFER_SIZE];\n</code></pre>\n</blockquote>\n<p>This isn't what you want for types that are expensive to construct, or can't be default-constructed.</p>\n<p>Your interviewer probably wants to see use of an uninitialized memory buffer, with placement-<code>new</code> and explicit destructor call to create and erase values.</p>\n<p>When you get to C++17 or later, then you should probably be using <code>std::uninitialized_value_construct()</code> and <code>std::destroy_at()</code> (from <code>&lt;memory&gt;</code>). TBH, I wouldn't accept a job in a shop still working with C++11 right now...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T11:59:34.143", "Id": "529361", "Score": "0", "body": "You are right, I guess this is where I'd make use of the `sizeof` function to allocate enough bytes statically. Would it be suggested to use `std::move` semantics in this case? \n If the iterator shows the number of \"valid\" bytes anyway.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:13:15.210", "Id": "529362", "Score": "0", "body": "`sizeof` is an _operator_, not a _function_, but otherwise yes, you should allocate sufficient uninitialized memory and create objects within that. For movable objects, you should be able to construct using the move constructor (which is what `std::uninitialized_value_construct()` will do if passed a `T&&`). There's also a helper function for moving multiple objects into uninitialized memory: `std::uninitialized_move()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:26:22.787", "Id": "268339", "ParentId": "268337", "Score": "8" } }, { "body": "<ol>\n<li><p>Debug-code</p>\n<ol>\n<li><p>The proper destination for debug-output is <code>std::clog</code> (which goes to <code>STDERR</code> by default, <code>std::cerr</code> has the same destination but no buffering), not <code>std::cout</code> (which goes to <code>STDOUT</code>). Doubly so for trace-output.</p>\n</li>\n<li><p>I guess you resort to <code>std::endl</code> because you use the wrong stream, though that's still a poor excuse. If you need an explicit flush, be explicit and use <code>std::flush</code>. Don't leave us wondering if you just wanted a newline.</p>\n</li>\n<li><p>Get rid of all the conditional compilation using the preprocessor.<br />\nWhile it might make sense to allow tracing your calls, code it similar to <code>assert()</code> or at least get rid of it at the end. Also, don't hang it on <code>NDEBUG</code>, tracing is far more intrusive.</p>\n</li>\n</ol>\n<pre><code>// trace.h\n#ifdef TRACE\n#undef trace\n#include &lt;iostream&gt;\ntemplate&lt;class...Ts&gt;\ninline void trace(Ts const&amp;... ts) noexcept {\n using T = int[];\n T{0, (std::cerr &lt;&lt; ts, void(), 0)};\n}\n#define trace(...) trace(__VA_ARGS__)\n#else\n#define trace(...) void()\n#endif\n\n</code></pre>\n</li>\n<li><p>Model your type on the standard library as good as you can. An interface should be as unsurprising as it can be without burdening the implementation unduly.</p>\n<ol>\n<li>Put the templates type-argument first. Everyone else does it.</li>\n<li>Use a <code>std::size_t</code> for the size like everyone else.<br />\nAlso, if you don't want to name it <code>N</code>, use something more descriptive like <code>CAPACITY</code>.</li>\n<li>Allow initialization from arbitrary iterator-pairs. That can be leveraged for <code>std::initializer_list</code>.</li>\n<li>Support move- and copy-insertion for <code>.push_back()</code>. The easiest way is by supporting <code>.emplace_back()</code>, as you don't need to special-case copying an element and re-allocation.</li>\n<li>For <code>.insert()</code>, create and delegate to <code>.emplace()</code>.</li>\n<li><code>.pop_back()</code> should not return anything, because copying the removed element can be a costly waste of time.</li>\n<li><code>operator[]</code> needs a constant overload, and should not catch errors. Adding an <code>assert()</code> would be appropriate though.<br />\n<code>.at()</code> is the member which should check bounds.</li>\n<li><code>.back()</code> also misses its constant overload, and should at most contain an <code>assert()</code> for checking errors.<br />\nWithout <code>.front()</code> it seems lonely.</li>\n<li>You are missing the whole iterator-interface, among others. At least add a note: <code>// TODO: iterators and more</code>.</li>\n</ol>\n</li>\n<li><p>Polishing the interface</p>\n<ol>\n<li><p>Just use <code>= default;</code> instead of <code>{}</code> for the default ctor. Some code checks for trivial ctors and provides an optimized path.</p>\n</li>\n<li><p>Use <code>noexcept</code> where expected. Doing so allows the compiler to remove exception-handling code, and there are often faster correct paths for code which cannot throw.</p>\n</li>\n</ol>\n</li>\n<li><p>Working with raw memory</p>\n<ol>\n<li><p>Don't initialize a bunch of objects you might never need. Use an unnamed union for the data-array to suppress the compiler calling special functions.</p>\n<pre><code>union { T internal_buffer[BUFFER_SIZE]; };\n</code></pre>\n</li>\n<li><p>Yes, the above point means that the default copy- and move- ctor/assignment as well as the default dtor do the wrong thing. Define them yourself to do the right thing.</p>\n</li>\n<li><p>Even if you do not want to use the <a href=\"//en.cppreference.com/w/cpp/memory\" rel=\"nofollow noreferrer\">Uninitialized memory algorithms</a>, you can use placement-new and manual destructor-invocation directly. Just include <a href=\"//en.cppreference.com/w/cpp/header/new\" rel=\"nofollow noreferrer\"><code>&lt;new&gt;</code></a>.</p>\n</li>\n</ol>\n</li>\n<li><p><code>(void)</code> is the proper parameter-list for a no argument function in C, due to back-compatibility. While C++ accepts it, <code>()</code> is preferred.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T21:08:54.947", "Id": "268357", "ParentId": "268337", "Score": "7" } }, { "body": "<pre><code>if(0u &lt; used_elements)\n</code></pre>\n<p>This is confusing to read and takes more time to understand than</p>\n<pre><code>if(used_elements &gt; 0u)\n</code></pre>\n<p>I can understand using the reversed equality comparison <code>0u == used_elements</code> to prevent accidentally writing <code>used_elements = 0u</code> (although I personally don't like that), but this is entirely unnecessary for inequalities.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:31:55.563", "Id": "529231", "Score": "4", "body": "Compilers warn about `if (x = 0)`, crank up the warnings, make warnings errors, and stop obfuscating code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T02:03:47.083", "Id": "268366", "ParentId": "268337", "Score": "4" } }, { "body": "<p>This isn't bad, but it's not stellar either.</p>\n<h3>Names matter.</h3>\n<p><code>Stable</code> is a very strange name here. It evokes pointer/iterator stability, a term used to indicate that pointers and iterators are stable in memory, for an construct in which they will NOT be.</p>\n<p>I would recommend using <code>Inline</code>, instead, to indicate that the memory used is right here (in line) rather than hidden behind an indirection.</p>\n<h3>Do no default construct items</h3>\n<p>Creating an empty vector should be a no-op, both for performance reasons and to allow using the vector with non-default constructible items.</p>\n<p>I recommend using a dedicated <code>Raw</code> class to represent potentially raw memory. You can use Rust's naming of <code>MaybeUninit</code> if you prefer. The advantage of clearly differentiating <code>Raw&lt;T&gt;&amp;</code> from <code>T&amp;</code> is, like all strong types, that it allows strictly differentiating between them.</p>\n<pre><code>template &lt;typename T&gt;\nclass Raw {\npublic:\n T const* pointer() const { return reinterpret_cast&lt;T const*&gt;(&amp;mMemory); }\n T* pointer() { return reinterpret_cast&lt;T const*&gt;(&amp;mMemory); }\n\n T const&amp; ref() const { return *this-&gt;pointer(); }\n T&amp; ref() { return *this-&gt;pointer(); }\n\nprivate:\n std::aligned_storage_t&lt;sizeof(T), alignof(T)&gt; mMemory;\n};\n</code></pre>\n<p>And from there you get:</p>\n<pre><code>template &lt;typename T, std::size_t N&gt;\nclass InlineVector {\npublic:\n /* Something */\nprivate:\n std::size_t mSize = 0;\n std::array&lt;Raw&lt;T&gt;, N&gt; mData;\n};\n</code></pre>\n<p>The downside is that you now need to implement all 5 special members yourself.</p>\n<h3>Use range-for syntax</h3>\n<p>Range-for syntax is easier, just use it.</p>\n<pre><code>InlineVector(std::initializer_list&lt;T&gt; list) {\n for (auto&amp; i : list) { ... }\n}\n</code></pre>\n<h3>Use braces, even for one-liners.</h3>\n<p>I recommend reading <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"noreferrer\"><code>goto fail</code></a> bug; it's the best justification for the practice.</p>\n<h3>Use batch operations, for performance.</h3>\n<p>While calling <code>push_back</code> repeatedly is correct, it unfortunately suffers from the issue of checking the capacity <em>every single time</em>. This is rather unfortunate.</p>\n<p>Instead, check <em>once</em>, and then perform the operation.</p>\n<p>As a bonus, this means that your function now has <em>transactional semantics</em>, also known as <strong>Strong Exception Guarantee</strong>.</p>\n<pre><code>InlineVector(std::initializer_list&lt;T&gt; list) {\n if (list.size() &gt; this-&gt;capacity()) {\n throw std::runtime_error(&quot;Insufficient memory&quot;);\n }\n\n for (auto&amp; i : list) {\n new (mData[mSize].pointer()) T(i);\n ++mSize;\n }\n}\n</code></pre>\n<h3>Factorize, to avoid mistakes.</h3>\n<p>Of course, since pushing will really happen quite a few times, it's best to factorize all that:</p>\n<pre><code>template &lt;typename... Args&gt;\nvoid emplace_back_impl(Args&amp;&amp;... args) {\n assert(this-&gt;size() &lt; this-&gt;capacity());\n\n new (mData[mSize].pointer()) T(std::forward&lt;Args&gt;(args)...);\n\n // Increment _after_ successfully construction, to avoid accessing\n // a partially constructed object in case of exception.\n ++mSize;\n}\n</code></pre>\n<p>Which allows us to rewrite the constructor as:</p>\n<pre><code>InlineVector(std::initializer_list&lt;T&gt; list) {\n if (list.size() &gt; this-&gt;capacity()) {\n throw std::runtime_error(&quot;Insufficient memory&quot;);\n }\n\n for (T const&amp; i : list) {\n this-&gt;emplace_back_impl(i);\n }\n}\n</code></pre>\n<p>Note: further improvements would be to consider trivially copyable types.</p>\n<h3>Use <code>= default</code> whenever possible</h3>\n<p>Default generated members have special consideration in the standard, unlocking special capabilities.</p>\n<pre><code>InlineVector() = default;\n</code></pre>\n<h3>Use guard style, instead of if/else</h3>\n<p>More of a stylistic rule, however the use of if/else tend to leave to convoluted highly-nested statements, which is hard for humans to follow.</p>\n<p>Simpler code being better, favor guard styles:</p>\n<pre><code>void push_back(T data) {\n if (this-&gt;size() == this-&gt;capacity()) {\n throw std::runtime_error(&quot;Insufficient memory&quot;);\n }\n\n this-&gt;push_back_impl(data);\n}\n</code></pre>\n<p>As a bonus, you'll note the check is very similar to that of the constructor, which means it should be factored away:</p>\n<pre><code>void ensure_space_for(std::size_t extra) {\n // Careful here, this-&gt;size() + extra could overflow std::size_t.\n if (extra &gt;= this-&gt;capacity() || this-&gt;size() &gt;= this-&gt;capacity() - extra) {\n throw std::runtime_error(&quot;Insufficient memory&quot;);\n }\n}\n</code></pre>\n<p>Allowing use to rewrite:</p>\n<pre><code>void push_back(T data) {\n this-&gt;ensure_space_for(1);\n\n this-&gt;push_back_impl(data);\n}\n</code></pre>\n<h3>Move, move!</h3>\n<p>Use moves whenever possible, they're more efficient than copies:</p>\n<pre><code>void push_back(T data) {\n this-&gt;ensure_space_for(1);\n\n this-&gt;push_back_impl(std::move(data));\n}\n</code></pre>\n<h3>Do not use primitive logging</h3>\n<p>You may need to use logging during debugging; that is fine.</p>\n<p>DO NOT activate such crude logging with a generic-purpose flag such as <code>NDEBUG</code>. Your users will hate you.</p>\n<p>And, really, consider removing such logging after you've tested and validated your code.</p>\n<h3>Do not use <code>void</code> for empty parameters list.</h3>\n<p>C++ is not C.</p>\n<pre><code>T pop_back() {\n // OP: feel free to use an exception if you wish to.\n assert(this-&gt;size() &gt; 0);\n\n --mSize;\n T&amp; slot = (mData[mSize].ref();\n\n T result = std::move(slot);\n slot.~T();\n\n return result;\n}\n</code></pre>\n<p>Note: I appreciate you deviating from <code>std::vector</code> and allowing users to pop-back a value in a single expression. Nice.</p>\n<h3>Consider Exception Safety</h3>\n<p>I won't lie, <code>insert</code> is <em>hard</em> in C++.</p>\n<p>The most efficiency way is to move elements, creating gaps of raw memory when inserting multiple elements. Fortunately, here, we have a single element, so we're good.</p>\n<pre><code>void insert(T data, std::size_t at) {\n this-&gt;ensure_space_for(1);\n this-&gt;ensure_within_bounds(at);\n\n if (at == mSize) {\n this-&gt;push_back_impl(std::move(data));\n return;\n }\n\n assert(mSize &gt; 0);\n\n // Move last element into raw memory\n new (mMemory[mSize].pointer()) T(std::move(mMemory[mSize-1].ref()));\n\n // Size cannot be incremented before the previous move, as in\n // case of exception, there is no fully constructed element in\n // the &quot;new&quot; slot.\n // It should be incremented immediately afterwards, however, to\n // ensure the element is destructed if anything goes wrong in\n // latter operations.\n ++mSize;\n\n // Move all elements from [at, mSize-1) to [at+1, mSize)\n for (std::size_t i = mSize - 1; i &gt; at; --i) {\n mMemory[i].ref() = std::move(mMemory[i - 1].ref());\n }\n\n // Overwrite element at index `at`.\n mMemory[at].ref() = std::move(data);\n}\n</code></pre>\n<p>Note: for performance reasons, it would be better to delegate the entire &quot;move sequence&quot; to a separate function, which could be specialized for trivially copyable types -- think <code>int</code>.</p>\n<h3>Provide const/non-const access pairs.</h3>\n<p>It's very frustrating not to be able to use an access method because it was forgotten.</p>\n<h3>Exceptions have a cost, asserts are free.</h3>\n<p>Exceptions have a cost, so it may be best to avoid introducing exceptions in functions for which <code>std::vector</code> doesn't throw, as it may introduce unacceptable overhead preventing the switch to your variant.</p>\n<p>Asserts are free (in Release), though, so pop them liberally.</p>\n<pre><code>T const&amp; back() const {\n assert(mSize &gt; 0);\n return mMemory[mSize - 1].ref();\n}\n\nT&amp; back() {\n assert(mSize &gt; 0);\n return mMemory[mSize - 1].ref();\n}\n\nT const&amp; operator[](std::size_t at) const {\n assert(at &lt; mSize);\n return mMemory[at].ref();\n}\n\nT&amp; operator[](std::size_t at) {\n assert(at &lt; mSize);\n return mMemory[at].ref();\n}\n</code></pre>\n<p>Note: it would be tempting to implement <code>back()</code> in terms of <code>(*this)[mSize - 1]</code>, and it would &quot;work&quot; even if <code>mSize</code> is 0, but it would be a bit confusing in the assert... sometimes a bit of duplication is clearer.</p>\n<h3>On testing.</h3>\n<p>I've written my fair share of containers in C++, and if I have one word of advice with regard to testing, it's that valgrind is your friend.</p>\n<p>I tend to use a very simple <code>HeapString</code> class for testing, written on top of <code>std::unique_ptr&lt;char[]&gt;</code>. This requires an independent memory allocation for every instance, which means that any issue in forgetting to construct, badly copying/moving, or forgetting to destruct, is immediately flagged by Valgrind.</p>\n<p>Combine with some &quot;exhaustive&quot; testing of each method, and I get very strong guarantees that I didn't mess things up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:46:08.070", "Id": "529274", "Score": "0", "body": "Naming: Perhaps something involving the word \"array\", to invoke similarity to `std::array`. It's an array with bookkeeping for in-use length. The allocation size never changes. I guess that's looking at it purely based on how it works, though, not what it can do for you / what it's for. And `vlength_array` is probably not helpful because that name is already taken by C99 VLAs, and that's not what this is trying to be." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:27:40.377", "Id": "268379", "ParentId": "268337", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T13:17:53.187", "Id": "268337", "Score": "4", "Tags": [ "c++", "c++11", "template", "vectors" ], "Title": "C++11 Custom Vector Implementation" }
268337
<p>I'm a mathematician who is new to programming and I'm currently reading the book &quot;Theory of Neural Networks&quot; by Rojas. To become better, I try to program every algorithm that is described in the book using javascript (to be precise: the p5js editor). Let <span class="math-container">\$X=\{x_{1},\ldots,x_{N}\}\subset\mathbb{R}^{n}\$</span> be a set of points viewed as vectors. Let's assume I want to find <span class="math-container">\$ k\$</span> clusters in the set <span class="math-container">\$X\$</span>. The algorithm goes as follows:</p> <p><strong>start</strong>: Initialize a set of <span class="math-container">\$k\$</span> normalized random vectors <span class="math-container">\$\{w_{1},\ldots,w_{k}\}\$</span>, called weight vectors.</p> <p><strong>test</strong>: Select <span class="math-container">\$x_{j}\in X\$</span> randomly and compute the dotproduct <span class="math-container">\$x_{j}\cdot w_{i}\,\forall\,i\in\{1,\ldots,k\}\$</span>. Find <span class="math-container">\$m\in\{1,\ldots,k\}\$</span> such that <span class="math-container">\$x_{j}\cdot w_{m}\geq x_{j}\cdot w_{i}\,\,\forall\,i\in\{1,\ldots,k\}\$</span>.</p> <p><strong>corrcet</strong>: Substitute <span class="math-container">\$w_{m}\$</span> by <span class="math-container">\$w_{m}+x_{j}\$</span> and normalize. Then go back to <strong>test</strong>.</p> <p>Here is my code:</p> <pre><code>let off = 20; // offset to not touch boundary class Point { constructor() { this.x = random(-width/2 + off , width / 2 - off); this.y = random(-height / 2 + off, height / 2 - off); } show() { stroke(239, 12, 12); strokeWeight(4); point(this.x, this.y); } } // function for initializing random weight vectors function setWeights(l) { let weights = []; let v; for (let i = 0; i &lt; l; i++) { v = createVector( random(-width / 2 , width / 2 ), random(-height / 2 , height / 2 ) ); weights.push(p5.Vector.mult(v, 1 / v.mag())); } return weights; } // k = # of weight vectors, N = # of learningsessions function computeClusters(inpts, k, N) { let w = setWeights(k); let erg, dotprods, ind, e, m, maxIndex; for (let j = 0; j &lt; N; j++) { dotprods = []; ind = floor(random(0, inpts.length)); e = inpts[ind]; for (let i = 0; i &lt; w.length; i++) { dotprods.push(e.dot(w[i])); } m = max(dotprods); maxIndex = 0; for (let i = 0; i &lt; dotprods.length; i++) { if (dotprods[i] == m) { maxIndex = i; } } erg = e.add(w[maxIndex]); w[maxIndex] = erg.mult(100/erg.mag()); } return w; } // function for displaying vector in an &quot;appropriate&quot; way function drawVector(vec, mycolor) { let arrowSize = vec.mag() / 10; push(); stroke(mycolor); strokeWeight(1.5); fill(mycolor); line(0, 0, vec.x, vec.y); rotate(vec.heading()); translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 4, 0, -arrowSize / 4, arrowSize, 0); pop(); } let points = []; let vectors = []; let w = []; function setup() { createCanvas(400, 400); for (let i = 0; i &lt; 10; i++) { let p = new Point(); points.push(p); vectors.push(createVector(p.x, p.y)); } w = computeClusters(vectors, 3, 10); } function draw() { background(165, 195, 239); translate(width / 2, height / 2); scale(1, -1); push(); strokeWeight(0.5); stroke(125); line(-width / 2, 0, width / 2, 0); line(0, -height / 2, 0, height / 2); pop(); for (var i = 0; i &lt; points.length; i++) { points[i].show(); } push(); for (let j = 0; j &lt; w.length; j++) { drawVector(w[j], color(50, 175, 150)); } pop(); } </code></pre> <p><a href="https://i.stack.imgur.com/6km9U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6km9U.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/fB7ef.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fB7ef.png" alt="enter image description here" /></a></p> <p>Now, the algorithm seems to performe quite well, see the attached pictures. The only problem I have is: why does my code sometimes produce two and sometimes produce three weight vecotrs, although I declared to create three: see <code>w = computeClusters(vectors, 3, 10);</code>?</p> <p>Thanks in advance for your help. If you have any general suggestions regarding my code, feel free to give me some input. :)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:47:09.723", "Id": "268340", "Score": "2", "Tags": [ "javascript", "algorithm", "machine-learning", "neural-network" ], "Title": "Unsupervised competitive learning algorithm from scratch in javascript" }
268340
<p>I have created a VBA macro to create a pivot table automatically. But taking 15 to 20 minutes of time to complete the macro.</p> <p>Especially at the point of below code taking half of the time. Review Code below</p> <pre><code>With .PivotFields(&quot;NTS USD ACT Previous Year&quot;) .Orientation = xlDataField .Position = 1 .Function = xlAverage .NumberFormat = &quot;$#,##;($#,##);-&quot; .Caption = &quot;FG NTS PY-Average&quot; End With </code></pre> <p>Requirements:</p> <p>Pivot Table should be in Tabular Format. Grand Total should be there and when I filter for single &quot;JNJ RM Code&quot; Grand should change. Row Sub totals should be turned off. Repeat all data labels. Adjust Pivot table Column width Seeking Advice: Can I have 200,000 data on excel sheet and to use pivot.</p> <p>Please do suggest how much data maximum excel can hold with better performance.</p> <p>Please review the entire module for your reference.</p> <pre><code>Option Explicit Dim wb As Workbook Dim wsData As Worksheet, wsPT As Worksheet Sub Create_Pivot_Table() Dim LR As Long, LC As Byte Dim DataRange As Range Dim PTCache As PivotCache Dim pt As PivotTable Dim st As String st = Now() Set wb = ThisWorkbook Set wsData = wb.Worksheets(&quot;Data&quot;) Call Delete_PT_Sheet With wsData LR = .Cells(Rows.Count, &quot;A&quot;).End(xlUp).Row LC = .Cells(1, Columns.Count).End(xlToLeft).Column Set DataRange = .Range(.Cells(1, 1), .Cells(LR, LC)) Set wsPT = wb.Worksheets.Add wsPT.Name = &quot;Pivot_Data&quot; Set PTCache = wb.PivotCaches.Create(xlDatabase, DataRange) Set pt = PTCache.CreatePivotTable(wsPT.Range(&quot;A2&quot;), &quot;Data&quot;) With pt .ColumnGrand = True .HasAutoFormat = True .DisplayErrorString = False .DisplayNullString = True .EnableDrilldown = True .ErrorString = &quot;&quot; .MergeLabels = False .NullString = &quot;&quot; .PageFieldOrder = 2 .PageFieldWrapCount = 0 .PreserveFormatting = True .RowGrand = True .PrintTitles = False .RepeatItemsOnEachPrintedPage = True .TotalsAnnotation = False .CompactRowIndent = 1 .VisualTotals = False .InGridDropZones = False .DisplayFieldCaptions = True .DisplayMemberPropertyTooltips = True .DisplayContextTooltips = True .ShowDrillIndicators = True .PrintDrillIndicators = False .AllowMultipleFilters = True .SortUsingCustomLists = True .DisplayImmediateItems = True .FieldListSortAscending = False .ShowValuesRow = False .RowAxisLayout xlTabularRow .RepeatAllLabels xlRepeatLabels '// Filter(s) With .PivotFields(&quot;Region&quot;) .Orientation = xlPageField .EnableMultiplePageItems = True .Subtotals(1) = True .Subtotals(1) = False End With '// Row Section (Layer 1) With .PivotFields(&quot;JNJ RM Code&quot;) .Orientation = xlRowField .Position = 1 .LayoutBlankLine = False .Subtotals(1) = True .Subtotals(1) = False .LayoutForm = xlTabular 'xlOutline .LayoutCompactRow = True End With '// Row Section (Layer 2) With .PivotFields(&quot;Component Description&quot;) .Orientation = xlRowField .Position = 2 .LayoutBlankLine = False .Subtotals(1) = True .Subtotals(1) = False End With '// Row Section (Layer 3) With .PivotFields(&quot;FG Material Code&quot;) .Orientation = xlRowField .Position = 3 .LayoutBlankLine = False .Subtotals(1) = True .Subtotals(1) = False End With '// Row Section (Layer 4) With .PivotFields(&quot;FG Material Description&quot;) .Orientation = xlRowField .Position = 4 .LayoutBlankLine = False .Subtotals(1) = True .Subtotals(1) = False End With '// Values Section Layer 2) With .PivotFields(&quot;NTS USD ACT Previous Year&quot;) .Orientation = xlDataField .Position = 1 .Function = xlAverage .NumberFormat = &quot;$#,##;($#,##);-&quot; .Caption = &quot;FG NTS PY-Average&quot; End With End With 'PT End With 'wsData '//Releasing Object Memories Set PTCache = Nothing Set wsPT = Nothing Set DataRange = Nothing Set wsData = Nothing Set wb = Nothing ThisWorkbook.Save 'MsgBox (&quot;Completed&quot;) End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:13:44.223", "Id": "529147", "Score": "0", "body": "The line(s) `With .PivotFields ... End With` are taking 7-10 minutes to execute? My guess is that it's in `.Function = xlAverage` and it will probably take this long if you were to create the pivot by hand. Since that's a built in Excel function, there isn't much you can do about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:44:15.100", "Id": "529158", "Score": "0", "body": "_Can_ you have 200,000 rows of data in Excel? Sure! You _can_ have 1 million rows (I believe that's the max for Excel 2010 and newer). It's just going to take longer to get things done. You may be at the point where it's time to migrate your data set into an actual database instead of using Excel as a database server (which it isn't very good at)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T16:29:06.323", "Id": "529164", "Score": "0", "body": "Did you remember to turn off the display of the work sheet while the pivot table is being created? If the display is being updated while processing the data the entire process is slowed down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T16:56:16.480", "Id": "529312", "Score": "0", "body": "@FreeMan Thank you for your reply. I noticed that when pivot did manually it is a bit faster than automation," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T17:00:40.997", "Id": "529313", "Score": "0", "body": "@FreeMan in that case can I use MS Access Automation to get this done? if yes is there any way to replicate data same as like pivot table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T17:02:05.887", "Id": "529314", "Score": "0", "body": "@pacmaninbw Yes, I turned events off." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T19:26:25.720", "Id": "529401", "Score": "0", "body": "@Mani233, yes, you can make a PivotTable in Access. You can also do nice reporting. You can also export the summary to Excel, without all that backing data. https://www.accessrepairnrecovery.com/blog/complete-information-about-ms-access-pivot-table" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T16:31:52.990", "Id": "529532", "Score": "0", "body": "@HackSlash Thank you" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:56:11.493", "Id": "268341", "Score": "0", "Tags": [ "vba", "excel", "macros" ], "Title": "Creating Pivot Table taking time at average vales" }
268341
<p>This very short piece of code is a migration in which a column name is changed to be more descriptive. It is part of a larger bioinformatics application written in RoR that parses the output of multiple bioinformatics tools, then summarizes and stores the results in PostgreSQL database. The goal is to analyze next generation sequencing data.</p> <p>I want to call attention to the comment style. <strong>Does this code follow common best practices in Ruby regarding block <em>vs</em> line comments?</strong> Block comments appear &quot;cleaner&quot; than line comments here, but I may be wrong. For example, Rubocop flags these. My main question is about the comment style, not about the executable code of the migration.</p> <pre><code>=begin Change column name to better reflect what is stored in that field. The name orig_num_reads or num_clusters will now refer to the number of reads or number of clusters that came off the sequencer. After that, the upstream code may optionally do a downsampling step, which results in delivered_num_reads. Those reads are used by Kraken for classification, and also to store in the delivered_num_reads column in the database. After that, there is usually another optional downsampling step, this time in Galaxy. The resulting number of reads is stored in num_reads column. So: [sequencer] -&gt; orig_num_reads [downsample in upstream code (optional)] -&gt; delivered_num_reads (used in Kraken) [donsample in Galaxy (optional)] -&gt; num_reads =end class RenameOrigNumReadsToDeliveredNumReads &lt; ActiveRecord::Migration[5.2] def change rename_column :read_groups, :orig_num_reads, :delivered_num_reads end end </code></pre> <p><strong>Note:</strong> I am already aware of these:<br /> <a href="https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/BlockComments" rel="nofollow noreferrer">Class: RuboCop::Cop::Style::BlockComments — Documentation for rubocop (1.21.0)</a><br /> <a href="https://futhark-lang.org/blog/2017-10-10-block-comments-are-a-bad-idea.html" rel="nofollow noreferrer">Block Comments are a Bad Idea, by Troels Henriksen</a><br /> <a href="https://news.ycombinator.com/item?id=15440166" rel="nofollow noreferrer">Hacker News: Block Comments Are a Bad Idea</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:30:38.360", "Id": "529153", "Score": "1", "body": "I don't know RoR but the class name is making my eyes water =)" } ]
[ { "body": "<blockquote>\n<p>Does this code follow common best practices in Ruby regarding block vs line comments?</p>\n</blockquote>\n<p>No, <a href=\"https://github.com/rubocop/ruby-style-guide#no-block-comments\" rel=\"nofollow noreferrer\">it doesn't</a>.<br />\nAnd with the fear of starting a flamewar here, it doesn't matter either as long as you understand what you're doing, but if other devs that follow these standards find that code, they could get mad with you :)<br />\nPersonally, I prefer line comments. For your case, where you're commenting the main class, is not a big issue, but when you start commenting in nested blocks, it gets troublesome with block comments.<br />\nTake the following code as example:</p>\n<pre><code>module SomeModule\n class YourClass\n def a_method\n if true\n =begin\n a\n very\n long\n multi\n lines\n comment\n =end\n puts &quot;Hello&quot;\n else\n puts &quot;Goodbye&quot;\n end\n end\n end\nend\n</code></pre>\n<p>this is not a valid ruby code and it won't execute</p>\n<pre><code>┗ ruby your_class.rb\nyour_class.rb:5: syntax error, unexpected '='\n =begin\nyour_class.rb:7: syntax error, unexpected '=', expecting end\n =end\nyour_class.rb:9: else without rescue is useless\n else\nyour_class.rb:14: syntax error, unexpected end-of-input, expecting end\n</code></pre>\n<p>as to make a block comment valid, it must be defined at the beggining of the line, like this:</p>\n<pre><code>module SomeModule\n class YourClass\n def a_method\n if true\n=begin\n a\n very\n long\n multi\n lines\n comment\n=end\n puts &quot;Hello&quot;\n else\n puts &quot;Goodbye&quot;\n end\n end\n end\nend\n</code></pre>\n<p>and yeah, is the ugliest thing you'll ever see because you're not respecting the code indentation, so the option to this is commenting every line:</p>\n<pre><code>module SomeModule\n class YourClass\n def a_method\n if true\n # a\n # very\n # long\n # multi\n # lines\n # comment\n puts &quot;Hello&quot;\n else\n puts &quot;Goodbye&quot;\n end\n end\n end\nend\n</code></pre>\n<p>Now you could think this will be a pain to comment every line, but most of IDEs have the option to select the text to be commented. With VSCode I just press <code>cmd</code> + <code>/</code> and it works, but with other IDEs probably will work with the same or similar key combination.<br />\nIf you don't really care about these type of warnings, there's always the option to disable this rule creating a <code>.rubocop.yml</code> file in your project's root folder like this:</p>\n<pre><code>Style/BlockComments:\n # You can disable the cop completely\n Enabled: false\n # Or exclude some specific folders/files from being inspected\n Exclude:\n - 'db/**/*' \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T15:13:12.267", "Id": "529948", "Score": "1", "body": "Thank you very much for a thoughtful and detailed answer! +50." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T23:26:22.953", "Id": "268412", "ParentId": "268342", "Score": "1" } } ]
{ "AcceptedAnswerId": "268412", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:59:34.700", "Id": "268342", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Migration in a bioinformatics application that changes a column name and explains the rationale" }
268342
<p>My first language is Python and I learned considerably a good amount of it. So now I started learning C++. I know the basics of C++ and about classes and inheritance.</p> <p>This is my first serious project with classes. (I am thinking of adding an ai)</p> <p>I wanted to know where I could -</p> <ul> <li>Optimize the performance.</li> <li>Improve my class.</li> <li>Improve my win and draw detection functions. (Sadly, I cant use <code>... == ... ==... ==</code> in C++)</li> </ul> <p>Here is my code -</p> <pre><code>#include &lt;iostream&gt; class TicTacToe { private: char board[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; char current_turn = 'X'; bool playing = true; int state = 0; int input; public: void print_board(); int play_move(int index, char move); int check_win(char move); void start(); }; int main() { TicTacToe game; game.start(); return 0; } void TicTacToe :: start() { while (playing == true) { print_board(); std::cout &lt;&lt; &quot;Play your move &quot; &lt;&lt; current_turn &lt;&lt; std::endl; std::cin &gt;&gt; input; if (play_move(input, current_turn) == 0) { std::cout &lt;&lt; &quot;Box already occupied&quot; &lt;&lt; std::endl; continue; }; state = check_win(current_turn); if (state == 1) { print_board(); std::cout &lt;&lt; current_turn &lt;&lt; &quot; wins the game!&quot; &lt;&lt; std::endl; break; } else if (state == 2) { std::cout &lt;&lt; &quot;Draw!&quot; &lt;&lt; std::endl; break; }; current_turn = (current_turn == 'X') ? 'O' : 'X'; }; }; void TicTacToe :: print_board() { for (int i = 0; i &lt; 9; i++) { if (i == 1 || i == 2 || i == 4 || i == 5 || i == 7 || i == 8) { std::cout &lt;&lt; &quot; | &quot;; } std::cout &lt;&lt; board[i]; if (i == 2 || i == 5) { std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot;---------&quot; &lt;&lt; std::endl; } } std::cout &lt;&lt; std::endl; }; int TicTacToe :: play_move(int index, char move) { if (index &gt;= 0 &amp;&amp; index &lt; 9) { if (board[index] == ' ') { board[index] = move; return 1; } } return 0; }; /* 0 1 2 3 4 5 6 7 8 */ int TicTacToe ::check_win(char move) { if ( // Horizontal checks (board[0] == move &amp;&amp; board[1] == move &amp;&amp; board[2] == move) || (board[3] == move &amp;&amp; board[4] == move &amp;&amp; board[5] == move) || (board[6] == move &amp;&amp; board[7] == move &amp;&amp; board[8] == move) || // Vertical Checks (board[0] == move &amp;&amp; board[3] == move &amp;&amp; board[6] == move) || (board[1] == move &amp;&amp; board[4] == move &amp;&amp; board[7] == move) || (board[2] == move &amp;&amp; board[5] == move &amp;&amp; board[8] == move) || // Diagonal Checks (board[0] == move &amp;&amp; board[4] == move &amp;&amp; board[8] == move) || (board[2] == move &amp;&amp; board[4] == move &amp;&amp; board[6] == move)) { return 1; } else { bool draw = true; for (int i = 0; i &lt; 9; i++) { if (board[i] == ' ') { draw = false; break; } } if (draw == true) { return 2; } } return 0; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T10:23:02.923", "Id": "529229", "Score": "1", "body": "Since you mention knowing Python, would you use a class to implement this in Python? I'm asking because, just like in Python, you would usually *not* use a class here in C++, as it's completely unnecessary and only makes your code more complex. If this confuses you, go watch [*Stop writing classes* by Jack Diederich](https://youtu.be/o9pEzgHorH0)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T16:58:39.467", "Id": "529280", "Score": "0", "body": "what means std::something, i thought using namespace std its enough to not declare that part" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T17:54:46.467", "Id": "529281", "Score": "1", "body": "Using `using namespace std;` is considered to be a bad practice. Refer this [StackOverflow answer](https://stackoverflow.com/a/1452738/16246688)." } ]
[ { "body": "<p>in <code>print_board</code>:</p>\n<ul>\n<li>instead of checking against all <code>i</code>s I would try to find a formula (probably containing a modulo) to check against once</li>\n<li>if you want to <code>cout</code>, don't put an <code>endl</code> at every line (it flushes the buffer to screen), use a simple <code>'\\n'</code> and an <code>endl</code> or <code>flush</code> at the end.</li>\n</ul>\n<p>in <code>check_win</code>:\ninstead of again doing all these separate comparisons, I might add up the contents of the possible winning lines and compare each with <code>3*move</code></p>\n<p>The last one of course is only viable if you can ensure that\n<code>3*token1</code> is neither once nor twice the value of <code>token2</code> (which I haven't checked for 'X' and 'O' ...)</p>\n<p>Draw detection:</p>\n<pre><code>bool draw = std::find(board, board+9, ' ') == board+9;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:44:30.653", "Id": "529175", "Score": "0", "body": "`if (i % 3)` =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T18:13:35.137", "Id": "529180", "Score": "0", "body": "Could you elaborate what you mean by \"it flushes the buffer to the screen\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:27:09.470", "Id": "529216", "Score": "0", "body": "@Random_Pythoneer59 `cout` is a \"stream\" object (it lives in the `iostream` header). It collects everything you stream into it (with the `<<` operator) in a buffer and does not immediately print it to screen. You need to `flush` the buffer to do so. `endl` does this implicitly every time you use it. So for better performance, avoid `endl` as a simple line-break if you don't need to actually print every single line separately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T08:56:34.393", "Id": "529292", "Score": "1", "body": "Considering your other answer was not well received and on the verge of getting deleted by the community, I've merged your answers. It's quite possible the quality of your answer can be further improved by polishing it up a bit based on the comments you received. The comments can be found [here](https://chat.stackexchange.com/rooms/129998/discussion-on-answer-by-tino-michael-tic-tac-toe-in-c-with-classes)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:41:47.250", "Id": "268351", "ParentId": "268345", "Score": "3" } }, { "body": "<h2>Be smart!!</h2>\n<p>Imagine it's Friday afternoon. You are feeling impressed with yourself for completing the assignment right on time and just when you are about close your little MacBook, your boss walks in and asks if you can modify your program to work on a 5 x 5 grid? Tears run down your face as you realize that your weekend is ruined.\nYou should always code for reusability.</p>\n<pre><code>enum Diagonal\n{\n Principle,\n Secondary\n};\n\ntemplate &lt;class T&gt; class TicTacTo\n{\nprivate:\n std::size_t _rows;\n std::size_t _cols;\n T _emptySpace;\n std::vector&lt;T&gt; _cells = {};\n\npublic:\n TicTacTo(std::size_t rows, std::size_t cols, T _emptySpace)\n : _rows{rows},\n _cols{cols},\n _emptySpace{_emptySpace}\n {\n _cells.resize(rows * cols, _emptySpace);\n }\n\npublic:\n T&amp; cell(std::size_t row, std::size_t col) {\n return _cells[col + row * _cols];\n }\n\n const std::vector&lt;T&gt; getCol(std::size_t col) {\n std::vector&lt;T&gt; v(_rows);\n for (std::size_t row = 0; row &lt; _rows; row++)\n v[row] = cell(row, col);\n return v;\n }\n\n const std::vector&lt;T&gt; getRow(std::size_t row) {\n std::vector&lt;T&gt; v(_cols);\n for (std::size_t col = 0; col &lt; _cols; col++)\n v[col] = cell(row, col);\n return v;\n }\n\n const std::vector&lt;T&gt; getDiagonal(Diagonal d) {\n std::vector&lt;T&gt; v;\n for (std::size_t col = 0; col &lt; _cols; col++) {\n if (col &lt; _rows) {\n v.push_back(cell(col, d == Diagonal::Principle ? col : _rows - col - 1));\n }\n }\n return v;\n }\n\n bool check_done() {\n return std::count(_cells.begin(), _cells.end(), _emptySpace) == 0;\n }\n\n bool check_equal(std::vector&lt;T&gt; v, T move) {\n return v[0] == move &amp;&amp; std::equal(v.begin() + 1, v.end(), v.begin());\n }\n\n bool check_win(T move) {\n // check rows\n for (std::size_t r = 0; r &lt; _rows; r++) {\n if (check_equal(getRow(r), move))\n return true;\n }\n // check columns\n for (std::size_t c = 0; c &lt; _cols; c++) {\n if (check_equal(getCol(c), move))\n return true;\n }\n // check diagonals\n for (int d = 0; d &lt; 2; d++) {\n if (check_equal(getDiagonal(d == 0 ? Diagonal::Principle : Diagonal::Secondary), move))\n return true;\n }\n return false;\n }\n\n void print() {\n for (std::size_t row = 0; row &lt; _rows; row++) {\n for (std::size_t col = 0; col &lt; _cols; col++) {\n std::cout &lt;&lt; &quot; &quot; &lt;&lt; cell(row, col);\n if (col &lt; _cols - 1)\n std::cout &lt;&lt; &quot; |&quot;;\n }\n if (row &lt; _rows - 1) {\n std::cout &lt;&lt; std::endl;\n for (std::size_t col = 0; col &lt; _cols; col++) {\n std::cout &lt;&lt; (col &lt; _cols - 1 ? &quot;----&quot; : &quot;---&quot;);\n }\n std::cout &lt;&lt; std::endl;\n }\n }\n std::cout &lt;&lt; std::endl;\n };\n};\n\nint main() {\n TicTacTo&lt;char&gt; ttt(5, 5, ' ');\n ttt.cell(0, 4) = 'x';\n ttt.cell(1, 3) = 'x';\n ttt.cell(2, 2) = 'x';\n ttt.cell(3, 1) = 'x';\n ttt.cell(4, 0) = 'x';\n ttt.print();\n\n std::cout &lt;&lt; &quot;win = &quot; &lt;&lt; ttt.check_win('x') &lt;&lt; std::endl;\n}\n</code></pre>\n<p>The next edit will replace <code>vector</code> with <code>valarray</code> and use <code>stride</code> etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:48:37.800", "Id": "268352", "ParentId": "268345", "Score": "1" } }, { "body": "<ul>\n<li><p>Only the <code>start()</code> member function needs to be <code>public</code>. The other member functions can be <code>private</code>.</p>\n</li>\n<li><p>Member functions that don't change any member variables in the class should be marked <code>const</code>, e.g. <code>void print_board() const;</code></p>\n</li>\n<li><p><code>play_move</code> returns success or failure, so it should return a <code>bool</code> and not an <code>int</code>.</p>\n</li>\n<li><p>It would be better to use an <code>enum</code> for <code>state</code>, instead of an <code>int</code>. That way we can use meaningful names, e.g.: <code>enum class State { undecided, tie, winner };</code></p>\n</li>\n<li><p><code>state</code> doesn't need to be a member variable. It can be a local variable in <code>start()</code>.</p>\n</li>\n<li><p><code>playing</code> could also be a local variable, but since it's never set to <code>false</code> we don't actually need it! The loop in <code>start()</code> could just be <code>while (true) { ... }</code>.</p>\n</li>\n<li><p>Note that when testing a <code>bool</code>ean variable like <code>playing</code> in a <code>while</code> or <code>if</code> condition, we should do <code>if (playing)</code>, not <code>if (playing == true)</code>. (It's already a boolean so we don't need the equality comparison!)</p>\n</li>\n<li><p><code>input</code> can also be a local variable... in fact the <code>current_turn</code> can also be a local variable, since we pass it everywhere we need it.</p>\n</li>\n</ul>\n<hr />\n<p>Rather than checking lots of magic numbers in <code>print_board</code>, we could iterate over rows and columns and calculate the relevant board index, e.g.:</p>\n<pre><code> const int board_size = 3; // could be a static constant member variable in the class\n\n for (int y = 0; y != board_size; ++y)\n {\n for (int x = 0; x != board_size; ++x)\n {\n if (x != 0)\n {\n std::cout &lt;&lt; &quot; | &quot;;\n }\n\n std::cout &lt;&lt; board[y * board_size + x];\n }\n\n std::cout &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;---------&quot; &lt;&lt; std::endl;\n }\n\n std::cout &lt;&lt; std::endl;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T20:53:52.567", "Id": "268356", "ParentId": "268345", "Score": "3" } }, { "body": "<p>Let's look at the class first:</p>\n<blockquote>\n<pre><code>class TicTacToe\n{\nprivate:\n char board[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};\n char current_turn = 'X';\n bool playing = true;\n int state = 0;\n int input;\n\npublic:\n void print_board();\n int play_move(int index, char move);\n int check_win(char move);\n void start();\n};\n</code></pre>\n</blockquote>\n<p>All the state is private and the functions are all public - that seems sensible. We can omit the <code>private:</code> label since that's the default for <code>class</code>, but it does no harm to have it, and it is more explicit.</p>\n<p>The print and check functions shouldn't need to modify the state of the object, so they probably ought to be declared <code>const</code>:</p>\n<pre><code> void print_board() const;\n int check_win(char move) const;\n</code></pre>\n<p>The function we've called <code>print_board()</code> is usually spelt <code>&lt;&lt;</code>, with the signature</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const TicTacToe&amp;)\n</code></pre>\n<p>We need it to be a non-member function (and probably <code>friend</code> so it can read the innards of <code>TicTacToe</code> objects).</p>\n<p><code>start()</code> isn't a great name - it seems it plays a whole game. I'd call it <code>play()</code> or <code>play_game()</code>.</p>\n<p>It's not clear that <code>input</code> needs to be a member - usually inputs are transient values that only later translate into state changes. The integer <code>state</code> is a very vague name; when I went to see where it's used, it seems it doesn't need to be a member either.</p>\n<p>I would consider changing <code>current_turn</code> into something like <code>bool player_is_x</code> - that's easier to toggle (<code>player_is_x = !player_is_x</code>) and still quite simple to convert to the appropriate letter (<code>player_is_x ? 'X' : 'O'</code> - or more obscurely, <code>player_is_x[&quot;OX&quot;]</code>, but really don't do that).</p>\n<p>You might want to consider having a class to represent a board, and one that knows how to play the game (managing whose turn it is, etc.).</p>\n<hr />\n<p>In a couple of places, we have redundant comparisons:</p>\n<blockquote>\n<pre><code> while (playing == true)\n\n if (draw == true)\n</code></pre>\n</blockquote>\n<p><code>while</code> and <code>if</code> accept booleans, so they can be simply:</p>\n<blockquote>\n<pre><code> while (playing)\n\n if (draw)\n</code></pre>\n</blockquote>\n<p>We never write <code>if ((x == y) == true)</code>, do we?</p>\n<hr />\n<p>The structure of <code>check_win()</code> is</p>\n<blockquote>\n<pre><code>if (⋯)\n{\n return 1;\n}\nelse\n{\n bool draw = true;\n for (⋯)\n {\n if (⋯)\n {\n draw = false;\n break;\n }\n }\n if (draw == true)\n {\n return 2;\n }\n}\nreturn 0;\n</code></pre>\n</blockquote>\n<p>Whenever we have <code>if (⋯) { return; }</code> any following <code>else</code> can just go directly after without the <code>else</code> keyword:</p>\n<pre><code>if (⋯)\n{\n return 1;\n}\nbool draw = true;\nfor (⋯)\n{\n if (⋯)\n {\n draw = false;\n break;\n }\n}\nif (draw == true)\n{\n return 2;\n}\nreturn 0;\n</code></pre>\n<p>Now, the <code>draw</code> variable is only ever set to determine what to return. But we can simply return immediately instead of setting it:</p>\n<pre><code>if (⋯)\n{\n return 1;\n}\nfor (⋯)\n{\n if (⋯)\n {\n return 0;\n }\n}\nreturn 2;\n</code></pre>\n<p>That's much simpler. Simpler still (for the caller, too) is to have separate member functions to check for a win and for a draw.</p>\n<p>When we're checking for a win, do you see any pattern in the cell indexes here?</p>\n<blockquote>\n<pre><code> // Horizontal checks\n (board[0] == move &amp;&amp; board[1] == move &amp;&amp; board[2] == move) ||\n (board[3] == move &amp;&amp; board[4] == move &amp;&amp; board[5] == move) ||\n (board[6] == move &amp;&amp; board[7] == move &amp;&amp; board[8] == move) ||\n // Vertical Checks\n (board[0] == move &amp;&amp; board[3] == move &amp;&amp; board[6] == move) ||\n (board[1] == move &amp;&amp; board[4] == move &amp;&amp; board[7] == move) ||\n (board[2] == move &amp;&amp; board[5] == move &amp;&amp; board[8] == move) ||\n // Diagonal Checks\n (board[0] == move &amp;&amp; board[4] == move &amp;&amp; board[8] == move) ||\n (board[2] == move &amp;&amp; board[4] == move &amp;&amp; board[6] == move)\n</code></pre>\n</blockquote>\n<p>Each straight-line check is an arithmetic progression, with a step of 1 for horizontal, 3 for vertical, 4 for major diagonal and 2 for minor diagonal. So we could write a small (private) helper rather than writing out all cases like that:</p>\n<pre><code>bool TicTacToe::check_line(int pos, int step) const\n{\n char val = board[pos];\n pos += step;\n if (board[pos] != val) { return false; }\n pos += step;\n if (board[pos] != val) { return false; }\n return true;\n}\n\nbool TicTacToe::check_win() const\n{\n for (int i = 0; i &lt; 3; ++i) {\n // horizontal line?\n if (check_line(i*3, 1)) { return true; }\n // vertical line?\n if (check_line(i, 3)) { return true; }\n }\n // diagonals\n return check_line(0, 4) || check_line(2, 2);\n}\n\nbool TicTacToe::check_draw() const\n{\n for (char c: board) {\n if (c == ' ') {\n return false;\n }\n }\n return true;\n};\n</code></pre>\n<p>(Note that I didn't need to pass the current player here - if there's any line, it can only have been made in the most recent turn, or there would have been a win earlier).</p>\n<p>And the call is just:</p>\n<pre><code> if (check_win()) {\n print_board();\n std::cout &lt;&lt; current_turn &lt;&lt; &quot; wins the game!\\n&quot;;\n break;\n }\n if (check_draw()) {\n std::cout &lt;&lt; &quot;Draw!\\n&quot;;\n break;\n };\n</code></pre>\n<hr />\n<p>When reading input, always check the stream state afterwards. If the user enters something unexpected, the variable won't have a useful value:</p>\n<pre><code> int input;\n std::cin &gt;&gt; input;\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Input error\\n&quot;;\n return;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:10:36.573", "Id": "529213", "Score": "0", "body": "`std::ostream& operator<<(std::ostream&, const TicTacToe&)` I am new to this syntax, could you explain a bit more?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:51:35.007", "Id": "529222", "Score": "0", "body": "If you have ever written `std::cout << \"Hello World!\"`, that's what you're using. It's how you implement a _stream insertion operator_ in C++. See this [reference guide](https://en.cppreference.com/w/cpp/language/operators#Stream_extraction_and_insertion) and [a tutorial](https://www.tutorialspoint.com/overloading-stream-insertion-and-extraction-operators-in-cplusplus)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T21:26:41.757", "Id": "268358", "ParentId": "268345", "Score": "3" } } ]
{ "AcceptedAnswerId": "268358", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T16:47:23.890", "Id": "268345", "Score": "4", "Tags": [ "c++", "performance", "tic-tac-toe", "classes" ], "Title": "Tic Tac Toe in C++ with classes" }
268345
<p>On my page I have a <code>mouseup eventlistener</code> on <code>document</code>. I want to be able <em>catch</em> if the <em>clicked</em> elements has a specific <code>id</code> in any of their parents.</p> <p>What I'm doing now is to <code>loop</code> over the <code>e.path</code> and only <code>push</code> the ids to an <code>array</code> and from there check if the <code>array</code> <code>includes</code> that id <em>(the id is: <code>getme</code>)</em>. <em>You can see the code below.</em></p> <p>I feel this is not optimal or <em>the right way</em> of doing this. How can I make it so I don't need to each time loop over all the <code>e.path</code> and push to the <code>array</code> and than do the <code>include</code>.</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>document.addEventListener("mouseup", function(e){ console.log('Document was clicked - Document click fucntion comes here'); console.log(e.path); idsArr = []; const allPaths = e.path; allPaths.forEach((path)=&gt;{ if (path.id){ idsArr.push(path.id); } }); console.log(idsArr); if (idsArr.includes('getme')){ console.log('Array Includes the ID - Specific ID click fucntion comes here'); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.getme{background:blue;width:300px;height:400px;}.dontneed{width:200px;height:300;float:left;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div class="getme" id="getme"&gt; &lt;div class="parent1"&gt; &lt;div class="parent2"&gt; &lt;p&gt;Im pragraf&lt;/p&gt; &lt;div class="parent3"&gt; &lt;button&gt;Im button&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;img src="https://picsum.photos/200/300"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="dontneed"&gt; &lt;img src="https://picsum.photos/200/300"&gt; &lt;/div&gt; &lt;p&gt;Dont need&lt;/p&gt;</code></pre> </div> </div> </p> <p>Any suggestion or feedback is appreciated!</p>
[]
[ { "body": "<blockquote>\n<p>I feel this is not optimal or the right way of doing this. How can I make it so I don't need to each time loop over all the e.path and push to the array and than do the include.</p>\n</blockquote>\n<p>Another approach would be to use the element method <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/matches\" rel=\"nofollow noreferrer\"><code>matches</code></a> to check if the target of the event is the element with the specific <em>id</em> or a child element.</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>document.addEventListener(\"mouseup\", function(e){\n console.log('Document was clicked - Document click fucntion comes here');\n\n if (e.target.matches('#getme, #getme *')) {\n console.log('Array Includes the ID - Specific ID click fucntion comes here');\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.getme{background:blue;width:300px;height:400px;}.dontneed{width:200px;height:300;float:left;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"getme\" id=\"getme\"&gt;\n &lt;div class=\"parent1\"&gt;\n &lt;div class=\"parent2\"&gt;\n &lt;p&gt;Im pragraf&lt;/p&gt;\n &lt;div class=\"parent3\"&gt;\n &lt;button&gt;Im button&lt;/button&gt; \n &lt;/div&gt;\n &lt;/div&gt;\n &lt;img src=\"https://picsum.photos/200/300\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n\n&lt;div class=\"dontneed\"&gt;\n &lt;img src=\"https://picsum.photos/200/300\"&gt;\n&lt;/div&gt;\n&lt;p&gt;Dont need&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>The array <code>idsArr</code> is not declared with any scope keyword (e.g. <code>var</code>, <code>let</code>, <code>const</code>) and thus it is considered a global variable. It is recommended to <a href=\"https://softwareengineering.stackexchange.com/questions/277279/why-are-globals-bad-in-javascript\">avoid global variables</a>.</p>\n<p>As the snippet below demonstrates the <code>idsArr</code> could be derived using the array methods <code>map</code> and <code>filter</code></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>document.addEventListener(\"mouseup\", function(e){\n console.log('Document was clicked - Document click fucntion comes here');\n \n const allPaths = e.path;\n const idsArr = e.path.map((path) =&gt; path.id).filter(id =&gt; id)\n \n console.log('idsArr: ', idsArr);\n\n if (idsArr.includes('getme')){\n console.log('Array Includes the ID - Specific ID click fucntion comes here');\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.getme{background:blue;width:300px;height:400px;}.dontneed{width:200px;height:300;float:left;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"getme\" id=\"getme\"&gt;\n &lt;div class=\"parent1\"&gt;\n &lt;div class=\"parent2\"&gt;\n &lt;p&gt;Im pragraf&lt;/p&gt;\n &lt;div class=\"parent3\"&gt;\n &lt;button&gt;Im button&lt;/button&gt; \n &lt;/div&gt;\n &lt;/div&gt;\n &lt;img src=\"https://picsum.photos/200/300\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n\n&lt;div class=\"dontneed\"&gt;\n &lt;img src=\"https://picsum.photos/200/300\"&gt;\n&lt;/div&gt;\n&lt;p&gt;Dont need&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:50:51.857", "Id": "529176", "Score": "0", "body": "Appreciate it Sam :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:52:05.053", "Id": "529177", "Score": "0", "body": "which of the solutions are the \"best\" to use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T18:10:42.250", "Id": "529179", "Score": "0", "body": "The answer may depend on requirements... for example, I would say using the `.matches()` method might be best unless a team-mate is opposed to that approach or there are many target ids to look for. I also considered asking if you are familiar with event bubbling, and checking if the event handler could be added to the element with id `getme` instead of the document..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T18:28:04.503", "Id": "529181", "Score": "0", "body": "Thanks a lot mate. Yes at first I tested with to adding the eventlistener to `getme` but because of some requirements I need it to be on on `document`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:38:05.613", "Id": "268349", "ParentId": "268346", "Score": "2" } }, { "body": "<h2>Review</h2>\n<p>The code is very inflexible, too complex, and has very poor naming.</p>\n<h2>Inflexible</h2>\n<p>The code will force you write a new function for each <code>id</code> you want action on. It is not at all reusable without modification, which means it will need to be tested each time you use it.</p>\n<h2>Overly complex</h2>\n<p>Creating a copy of part of the path then to search that copy for a match is inefficient as the match can be found in one expression.</p>\n<pre><code>const getMeClicked = e.path.some(el =&gt; el === &quot;get me&quot;); // bool\n</code></pre>\n<h2>Poor naming.</h2>\n<p>You are confusing paths, elements, and ids. You are also naming an array that will never contain more than one item.</p>\n<ul>\n<li><p><code>idsArr</code> is not an array of ids, it is an array of elements with an id. There can only ever be one copy of an id (if page is not in quirks mode). Thus this should not be an array.</p>\n</li>\n<li><p><code>allPaths</code> There is only one path. There is no need to hold a second reference to <code>event.path</code></p>\n</li>\n<li><p><code>path</code> (in <code>forEach</code> callback) The for each is iterating elements not paths, the name should be <code>element</code>, or common abbreviation <code>el</code></p>\n</li>\n</ul>\n<h2>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a></h2>\n<p>As pointed out in the other answer you have used an undeclared variable. This is very dangerous.</p>\n<p>To avoid this mistake always write your JS in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a></p>\n<p><strong>Note</strong> that if using modules you don't need to use the directive as they can only run in strict mode.</p>\n<h2>Rewrite</h2>\n<p>Rewrite to provide identical functionality (ignoring and modifying some logs)</p>\n<p>It uses Array.some so that it can stop iterating when the id is found</p>\n<pre><code>&quot;use strict&quot;; // Must be at top of JS tag or file.\ndocument.addEventListener(&quot;click&quot;, e =&gt; {\n console.log(&quot;Document was clicked&quot;);\n e.path.some(el =&gt; {\n if (el.id === &quot;getMe&quot;) {\n console.log(&quot;Includes the ID&quot;);\n return true;\n }\n });\n});\n</code></pre>\n<p>However this is rather clunky and un-reusable so below is an re-design</p>\n<h2>Example redesign</h2>\n<p>Uses a function factory to return an event callback that will branch calls depending on the ids found in the path.</p>\n<pre><code>/* Function factory onMatchId \n id String Id to Match in event.path\n onId Callback to call if path contains id [optional]\n onNotId Callback to call if path does not contain id [optional]\n onAny Callback to call on any event [optional]\n\n Callback signature \n callback(e, id) \n e is event object. \n id is id string to match;\n*/\nconst onMatchId = (id, onId, onNotId, onAny) =&gt; e =&gt; \n (onAny?.(e, id), (e.path.some(el =&gt; el.id === id) ? onId : onNotId)?.(e, id));\n</code></pre>\n<h3>Simple example</h3>\n<p>A callback to match one id in path and a callback for all clicks</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(()=&gt; {\n\"use strict\";\nconst onMatchId = (id, onId, notId, any) =&gt; e =&gt; \n (any?.(e, id), (e.path.some(el =&gt; el.id === id) ? onId : notId)?.(e, id));\n \n \n/* callbacks */\nvar clickNum = 0;\nconst anyClk = () =&gt; console.log(\"Document was clicked\");\nconst clk = () =&gt; console.log(\"ID: getme clicked\");\n\n\n\n/* simple usage example */\ndocument.addEventListener(\"mouseup\", onMatchId(\"getme\", clk, undefined, anyClk));\n})();\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Text not of getme &lt;button&gt;Button not of getme&lt;/button&gt;\n&lt;div id=\"getme\"&gt;\n &lt;div id=\"a2\"&gt;\n &lt;div id=\"a1\"&gt;\n I'm text child of a1 a2 getme\n &lt;button&gt;Child of a1 a2 getme&lt;/button&gt;\n &lt;/div&gt;\n &lt;button&gt;Child of a2 getme&lt;/button&gt;\n &lt;/div&gt;\n &lt;button&gt;Child of getme button&lt;/button&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Complex example</h3>\n<p>Includes many callbacks, one for all clicks, then for <code>&quot;getme&quot;</code> clicked and not clicked, id <code>&quot;a2&quot;</code> clicked and not clicked, and for id <code>&quot;a1&quot;</code> only when clicked</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(()=&gt; {\n\"use strict\";\nconst onMatchId = (id, onId, notId, any) =&gt; e =&gt; \n (any?.(e, id), (e.path.some(el =&gt; el.id === id) ? onId : notId)?.(e, id));\n \n \n/* callbacks */\nvar clickNum = 0;\nconst anyClk = (e, id) =&gt; (console.clear(), console.log(\"Click num: \" + clickNum++));\nconst clk = (e, id) =&gt; console.log(\"ID: \" + id + \" clicked\");\nconst notClk = (e, id) =&gt; console.log(\"Not ID: \" + id + \" clicked\");\n\ndocument.addEventListener(\"click\", onMatchId(\"getme\", clk, notClk, anyClk));\ndocument.addEventListener(\"click\", onMatchId(\"a2\", clk, notClk));\ndocument.addEventListener(\"click\", onMatchId(\"a1\", clk));\n})();\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"getme\"&gt;\n &lt;div id=\"a2\"&gt;\n &lt;div id=\"a1\"&gt;\n I'm text child of a1 a2 getme\n &lt;button&gt;Child of a1 a2 getme&lt;/button&gt;\n &lt;/div&gt;\n &lt;button&gt;Child of a2 getme&lt;/button&gt;\n &lt;/div&gt;\n &lt;button&gt;Child of getme button&lt;/button&gt;\n&lt;/div&gt;\nText not of getme &lt;button&gt;Button not of getme&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T03:00:04.957", "Id": "268395", "ParentId": "268346", "Score": "3" } } ]
{ "AcceptedAnswerId": "268395", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T17:05:07.027", "Id": "268346", "Score": "1", "Tags": [ "javascript", "ecmascript-6", "event-handling" ], "Title": "Javascript - On mouseup check if any of the parents has/includes specific id" }
268346
<p><strong>The problem</strong></p> <p>I am working towards improving my Python coding. I am checking that I am doing the best in terms of the Python code, not necessarily the algorithms. Having looked at one of my previous attempts in C++, I learned about Sieves for prime numbers.</p> <p>I want to know that I am following the proper Python coding &quot;standards&quot; (i.e. PEP8), and there aren't any weird issues I'm overlooking. The run times in comment blocks show the function's run time with my computer, and your results may vary.</p> <p><strong>The code</strong></p> <pre><code>&quot;&quot;&quot;Prime number generator&quot;&quot;&quot; import math import argparse import datetime def is_odd(number: int): &quot;&quot;&quot;Returns true if the integer passed is an odd number&quot;&quot;&quot; return number % 2 == 1 def is_prime(number: int): &quot;&quot;&quot;Returns true if the integer passed is a prime number&quot;&quot;&quot; for _ in range(2, int(math.sqrt(number)) + 1): if number % _ == 0: return False return True # Run time: 11.808096 # Params: minimum=40, maximum=999999 def is_sieved(minimum: int, maximum: int, count: bool): &quot;&quot;&quot;Return list of numbers that are prime&quot;&quot;&quot; initial_list = range(minimum, maximum) list_of_primes = set(initial_list) for x in range(2, int(math.sqrt(maximum)) + 1): first_loop_of_numbers = True for y in range(x, maximum + 1, x): if not first_loop_of_numbers: list_of_primes.discard(y) first_loop_of_numbers = False print(f&quot;{list_of_primes=}&quot;) if count: print(f&quot;Primes found: {len(list_of_primes)}&quot;) # Run time: 02.103035 (min 2 | max 999999) # Run time: 25.752799 (min 2 | max 9999999) def main(minimum: int, maximum: int, count: bool): &quot;&quot;&quot;Main function&quot;&quot;&quot; if minimum &lt;= 1: print(&quot;Warning: Minimum set to less than 2. Setting to 2...&quot;) minimum = 2 if is_odd(maximum): maximum = maximum + 1 # Maximum must be even for range() to include it if minimum &gt;= maximum: print(&quot;Error! Maximum must be an integer higher than Minimum! Current&quot; + f&quot;values: {minimum=} | {maximum=}&quot;) return 2 # for number in range(minimum, maximum, 2): # if is_prime(number): # print(f&quot;{number}&quot;, end=&quot;, &quot;, flush=True) is_sieved(minimum, maximum, count) print() return 0 if __name__ == &quot;__main__&quot;: parser = argparse.ArgumentParser(description=&quot;Prime number generator&quot;) parser.add_argument('--minimum', dest='minimum', type=int, default=2, help='Minimum number to check (default: 2)') parser.add_argument('--maximum', dest='maximum', type=int, default=100, help='Minimum number to check (default: 100)') parser.add_argument('--count', dest='count', action='store_true', help=&quot;Count the number of primes found&quot;) args = parser.parse_args() begin_time = datetime.datetime.now() main(args.minimum, args.maximum, args.count) end_time = datetime.datetime.now() print(f&quot;Execution time: {end_time - begin_time}&quot;) </code></pre>
[]
[ { "body": "<p>Your code is readable, consistant and adheres to all the PEP8 standards I have to follow. I wouldn't worry about any further nit picks.</p>\n<p>One preference I have - If I am defining the parameter type, I would also define the return type:</p>\n<pre><code>def is_odd(number: int) -&gt; bool:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:16:56.923", "Id": "268378", "ParentId": "268354", "Score": "2" } }, { "body": "<h1>Throw-away variable</h1>\n<p>The <code>_</code> variable is used when you need a variable for syntactic correctness, but don’t actually need to ever use the variable. In <code>is_prime</code>, this is not the case; you loop over a range of trial divisors, and then check if the value is divisible by each of those divisors. The variable needs a name!</p>\n<pre class=\"lang-py prettyprint-override\"><code> for divisor in range(2, int(math.sqrt(number)) + 1):\n if number % divisor == 0:\n return False\n</code></pre>\n<h1>Integer square-root</h1>\n<p>The <code>int(math.sqrt(number))</code> expression may cause you grief. The calculation is done using floating-point arithmetic. If <code>number</code> is large (over 9,007,199,254,740,992), the conversion to floating-point is not exact and will result in loss of one or more of the least-significant bits. When the square-root is computed on this modified value, it is <em>possible</em> for the square-root to fall on the wrong side of an exact integer, and when converted to an <code>int</code>, the value may end up larger or smaller than the exact mathematical result should be.</p>\n<p>This can be trivially avoided by using <code>math.isqrt(number)</code>, which by avoiding the floating-point conversion, always computes the correct value. It is also clearer, being four characters shorter to type and eliminating a pair of parenthesis. It should also be faster.</p>\n<h1>0 and 1 are not prime</h1>\n<p>The <code>is_prime()</code> function returns <code>True</code> for the numbers <code>0</code> and <code>1</code>, neither of which are considered to be prime numbers.</p>\n<p>It is true that your <code>main</code> function enforces a lower limit of 2 on the prime number search range, so it should never be called with values less than <code>2</code>, but it is valid to write <code>from … import is_prime</code> in other modules where this restriction may not be present. The function should be flagged “not for external use” by prefixing the name with an underscore (<code>_is_prime</code>), or it should behave correctly for all values.</p>\n<h1>Misleading help</h1>\n<pre class=\"lang-py prettyprint-override\"><code> parser.add_argument('--maximum', dest='maximum', type=int, default=100,\n help='Minimum number to check (default: 100)')\n</code></pre>\n<p>Is <code>--maximum</code> really setting the <strong>minimum</strong> number to check?</p>\n<h1>Efficiency</h1>\n<p>Setting <code>first_loop_of_numbers</code> to <code>True</code> outside of the <code>for</code> loop, and inside the loop testing it and clearing it, just to do something different on the first iteration of a loop, results in a lot of unnecessary work being done by the processor. It is simpler to “unroll the loop”, doing the “first iteration” explicitly before the loop, and the “remaining iterations” inside the loop with no unnecessary tests required.</p>\n<p>In this particular case, your “doing something different on the first iteration” is actually ensuring nothing is done on the first iteration. So really you could just start the loop at the second iteration, by adding the increment to the starting value:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for x in range(2, int(math.sqrt(maximum)) + 1):\n for y in range(x + x, maximum + 1, x):\n list_of_primes.discard(y)\n</code></pre>\n<h1>Timing</h1>\n<p>Using <code>datetime.datetime.now()</code> for profiling is not the best idea. A lot of additional unnecessary work is being performed to handle timezones. A better choice would be <a href=\"https://docs.python.org/3/library/time.html?highlight=perf_counter#time.perf_counter\" rel=\"nofollow noreferrer\"><code>time.perf_counter()</code></a>.</p>\n<h1>Separate computation and printing</h1>\n<p>The name of the function <code>is_sieved</code> suggests it returns a <code>True</code> or <code>False</code> result. The <code>&quot;&quot;&quot;docstring&quot;&quot;&quot;</code> describes it as returning a list of numbers. In actuality, neither is correct; it returns <code>None</code>, and prints the prime numbers it found.</p>\n<p>The function would be better called <code>sieve_and_print_primes(…)</code>. Best would be to perform the sieve in one function, and print the results in a different function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sieve(minimum: int, maximum: int) -&gt; set[int]:\n …\n return list_of_primes\n\ndef report(list_of_primes: set[int], count: bool) -&gt; None:\n print(f&quot;{list_of_primes=}&quot;)\n if count:\n print(f&quot;Primes found: {len(list_of_primes)}&quot;)\n\ndef main(…):\n …\n primes = sieve(minimum, maximum)\n report(primes, count)\n …\n</code></pre>\n<p>This also gives you the ability to time just the sieve without the I/O (which may involve scrolling output in your shell window) slowing down the program.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main(…):\n …\n begin_time = time.perf_counter()\n primes = sieve(minimum, maximum)\n end_time = time.perf_counter()\n report(primes, count)\n print(f&quot;Calculation time: {end_time - begin_time}&quot;)\n …\n</code></pre>\n<h1>Types</h1>\n<p><code>list_of_primes</code> is actually a <code>set</code>, not a <code>list</code>. This also means the prime numbers are not returned in ascending order as one may expect.</p>\n<h1>Range</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if is_odd(maximum):\n maximum = maximum + 1\n # Maximum must be even for range() to include it\n</code></pre>\n<p>I understand what you mean, but this is the wrong. If there was some large even number that was prime, your algorithm wouldn’t find it if it was given as the <code>maximum</code>, because <code>is_odd(maximum)</code> wasn’t true.</p>\n<p>Don’t adjust the range based on a condition. Always adjust the range. The clearest way is by adjusting it where it is used:</p>\n<pre class=\"lang-py prettyprint-override\"><code> initial_list = range(minimum, maximum + 1)\n</code></pre>\n<p>Every Python programmer understands this to mean to include the end point.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:36:06.273", "Id": "268433", "ParentId": "268354", "Score": "4" } } ]
{ "AcceptedAnswerId": "268433", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T20:18:05.733", "Id": "268354", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Prime number finder in Python3" }
268354
<p>I'm scraping posts from various discussion forums and storing those posts, along with some metadata, into a relational database (SQL). My actual use case is a bit more complex, but I think I can give you the idea by using just two fictitious forums, one focusing on fishing (&quot;Fish Forum&quot;) and another focusing on golf (&quot;Golf Forum&quot;). In reality, I would also be storing threads, user info and other things you can imagine, but let me only focus on the actual posts, i.e., messages written by the users.</p> <p>I have a bunch of tables per forum, differing slightly from each other depending on the forum structure. On the fishing forum, each post has an id, timestamp, reply count, information on which post a particular post is replying to and a scrape time. The golfing forum is similar, but the metadata differs a bit. The main point is that both forums have some internal post numbering scheme assigning unique identifiers to each post.</p> <p>Now, my spider is working well and storing data, but I'm also interested in passing those messages through a natural language processing (NLP) model which is predicting a category for each post. For this, I've set up a third table called PREPROCESSED_POSTS. Here, we store the post id, the source forum (in this case, &quot;fish&quot; or &quot;golf&quot;), the predicted category (e.g., &quot;talks about the weather&quot;), confidence (e.g., &quot;0.952&quot;) and the identifier of the NLP model (e.g., &quot;my_latest_nlp_model&quot;).</p> <pre><code>CREATE TABLE FISH_FORUM_POSTS ( id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, post_id INT NOT NULL, created_at DATETIME2 NOT NULL, msg NVARCHAR(MAX) NOT NULL, reply_count INT NOT NULL, reply_to_post_number INT, scrape_time DATETIME2 NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT UNIQ_FISH_POST UNIQUE(post_id) ); CREATE TABLE GOLF_FORUM_POSTS ( id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, post_id INT NOT NULL, profile_id INT NOT NULL, msg NVARCHAR(MAX) NOT NULL, created_at DATETIME2 NOT NULL, like_count INT NOT NULL, scrape_time DATETIME2 NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT UNIQ_GOLF_POST UNIQUE(post_id) ); CREATE TABLE PREPROCESSED_POSTS ( id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, post_id INT NOT NULL, source_forum NVARCHAR(256) NOT NULL, prediction NVARCHAR(256), confidence DECIMAL(12, 4), model_name NVARCHAR(256) -- Each post on a forum has at most one prediction by any given model CONSTRAINT UNIQ_PREPROCESSED_POST UNIQUE(post_id, source_forum, model_name) ); </code></pre> <p>What annoys me here is that PREPROCESSED_POSTS just stores post identifier and the forum, so it's possible that by mistake we enter a post id and/or a forum that doesn't exist (e.g., &quot;cars&quot;). So I would want there to be an actual reference or a foreign key to something that exists. The problem is that I can't seem to do that because the posts are in two different tables.</p> <p>This is probably a well-known problem. What design should I apply here to circumvent this problem?</p> <p>I guess if I build a view that would distill the essence (= <code>post_id</code> plus <code>forum_name</code>) would be OK, but I probably can't make a foreign key into a view. It also seems difficult to use just one table that could then be referenced in PREPROCESSED_POSTS, because in reality all forums I'm scraping are very different with different kind of metadata. Also, I could add a check to enforce source_forum is either &quot;fish&quot; or &quot;golf&quot;, but that only solves the problem partially as it doesn't address the post_id being valid.</p>
[]
[ { "body": "<p>If the <code>post_id</code> is unique, why not make it a primary key? Sometimes it is justified to have an internally-controlled primary key like <code>id</code> but here the justification is unclear. One catch is that if the two forums are from different websites, their ID sequences will be different and you don't have a choice but to maintain your own primary keys.</p>\n<p>Transact-SQL supports <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">column-level unique constraints</a>, which means - so long as you don't care to name your constraint - you can delete your table-level constraint syntax and move your <code>unique</code> to the column.</p>\n<p><code>reply_to_post_number</code> looks like it should be a foreign key, if you are able to assume that all linked posts are present in the database. Note that Transact SQL doesn't support <code>restrict</code> for whatever reason, and you're limited to disabling relational integrity for this foreign key to prevent cascade cycles.</p>\n<p><code>reply_count</code> should have a check constraint to be non-negative. Depending on what <code>confidence</code> is, you may be able to write a check constraint to ensure that it's between 0 and 1 for instance.</p>\n<p><code>preprocessed_posts.post_id</code> should certainly be a foreign key, but I'm going to propose that that column be deleted altogether and <code>id</code> made to be both a primary and foreign key.</p>\n<p>A way to cut out a large amount of redundancy between your fish and golf tables is to make a third table, <code>FORUM_POSTS</code>, containing only the common columns; have <code>FISH_FORUM_POSTS</code> and <code>GOLF_FORUM_POSTS</code> only contain varying columns; and have the latter two include an ID column that is both a primary key and a foreign key to <code>FORUM_POSTS</code>. Conceptually this is analogous to class inheritance in the OOP world. This would allow you to have a foreign key from <code>PREPROCESSED_POSTS</code> straight to <code>FORUM_POSTS</code>.</p>\n<blockquote>\n<p>it's possible that by mistake we enter a post id and/or a forum that doesn't exist (e.g., &quot;cars&quot;)</p>\n</blockquote>\n<p>This is what foreign keys and relational integrity are for. However, to prevent redundancy, I don't think that the source forum column should exist at all. The source forum would be implied by the presence of a matching row in either of the fish or golf tables.</p>\n<blockquote>\n<p>if I build a view that would distill the essence (= post_id plus forum_name) would be OK</p>\n</blockquote>\n<p>This does not sound like the right way to go. Nothing I've seen here calls for a view; just a plain-old normalized relational schema.</p>\n<h2>Proposed</h2>\n<p>Runs fine on <a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2019&amp;fiddle=cd2c927bfa1767680e41532661d51351\" rel=\"nofollow noreferrer\">dbfiddle</a>:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>create table forum_posts(\n id int identity primary key,\n created_at datetime2 not null,\n msg nvarchar(max) not null,\n scrape_time datetime2 not null default current_timestamp\n);\n\ncreate table fish_forum_posts(\n id int primary key references forum_posts(id)\n on update cascade on delete cascade,\n \n -- Delete this if it's in the same sequence as the other fora\n post_id int unique not null,\n \n reply_count int not null check(reply_count &gt;= 0),\n \n reply_to_post_number int references fish_forum_posts(post_id)\n -- Needed to avoid cascade cycles\n on update no action on delete no action\n);\n\ncreate table golf_forum_posts(\n id int primary key references forum_posts(id)\n on update cascade on delete cascade,\n \n -- Delete this if it's in the same sequence as the other fora\n post_id int unique not null,\n \n profile_id int not null,\n \n like_count int not null check(like_count &gt;= 0)\n);\n\ncreate table models(\n id int identity primary key,\n name nvarchar(256) unique not null\n);\n\ncreate table preprocessed_posts(\n id int not null references forum_posts(id)\n on update cascade on delete cascade,\n \n prediction nvarchar(256) not null,\n confidence decimal(12, 4) not null check (confidence between 0 and 1),\n model int not null references models(id)\n on update cascade on delete cascade,\n \n primary key(id, model)\n);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T16:34:36.293", "Id": "530029", "Score": "0", "body": "I wonder how the subtypes of the posts should be detected? So if I want all golf posts, I can select * and inner join them with forum posts. But in my end application, the user is exposed to all posts and I want her to be able to filter on a source forum (golf, fishing). How is this best supported? One option is to give a view to the application that makes selects over golf, fish etc. posts and adds one constant source column. Or should the subtypes know their type (e.g., a source column)? Ofc, I'd do this in a normalized manner by using a separate table they link to which acts like an enum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T16:45:06.727", "Id": "530030", "Score": "0", "body": "Let's discuss in https://chat.stackexchange.com/rooms/130294/database-schema-for-discussing-forum-scraping" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T23:10:24.767", "Id": "268362", "ParentId": "268355", "Score": "1" } } ]
{ "AcceptedAnswerId": "268362", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T20:30:52.817", "Id": "268355", "Score": "1", "Tags": [ "sql", "sql-server", "database" ], "Title": "Database schema for discussion forum scraping" }
268355
<p>I'm a Kotlin engineer looking to get into web dev. I thought it'd be fun to make a Todo app w/o help from the internet. Just looking for some critiques and feedback, as I'm new-ish to the language.</p> <p>Here's the JS, HTML, CSS. Looking for criticism on all of it. No mobile support btw.</p> <p>JS:</p> <pre><code>class Column { constructor(elementId, countId) { this.items = new Map(); this.count = this.items.size; this.elementId = elementId; this.countId = countId; this.node = document.getElementById(this.elementId); this.countNode = document.getElementById(this.countId); } updateCount() { this.count = this.items.size; this.countNode.innerHTML = &quot;|(&quot; + this.count.toString() + &quot;)&quot;; } } class Todo extends Column { constructor() { super(&quot;todo&quot;, &quot;todoCount&quot;); } add(item) { item.toolbar.appendChild(item.close); if (item.complete) { item.checkbox.addEventListener(&quot;click&quot;, () =&gt; { closeItem(item); }); item.complete = false; } this.items.set(item, item.node); this.node.appendChild(item.node); this.updateCount() } remove(item) { this.items.delete(item); item.node.remove(); item.complete = true; this.updateCount(); } } class Done extends Column { constructor() { super(&quot;done&quot;, &quot;doneCount&quot;); } add(item) { item.checkbox.addEventListener(&quot;click&quot;, () =&gt; { openItem(item); }); this.items.set(item, item.node); this.node.appendChild(item.node); this.updateCount(); } remove(item) { this.items.delete(item); item.node.remove(); this.updateCount(); } } class TodoItem { constructor() { this.node = null; this.toolbar = null; this.checkbox = null; this.close = null; this.complete = false; } generateName() { return Math.floor(Math.random() * 1000).toString(); } create() { // Create the parent of the todo item let item = document.createElement(&quot;article&quot;); item.id = this.generateName(); // Create a checkbox, and its parent let todoToolbar = document.createElement(&quot;span&quot;); todoToolbar.className = &quot;todoToolbar&quot;; let checkbox = document.createElement(&quot;input&quot;); checkbox.className = &quot;checkbox&quot;; checkbox.type = &quot;checkbox&quot;; let close = document.createElement(&quot;span&quot;); close.className = &quot;close&quot; close.textContent = &quot;✖&quot;; // Create the Todo input area let input = document.createElement(&quot;textarea&quot;); input.className = &quot;todoInput&quot;; checkbox.addEventListener(&quot;click&quot;, () =&gt; { closeItem(this); }); close.addEventListener(&quot;click&quot;, () =&gt; { deleteItem(this); }); // Assign children and set the node todoToolbar.appendChild(checkbox); todoToolbar.appendChild(close); item.appendChild(todoToolbar); item.appendChild(input); this.node = item; this.toolbar = todoToolbar; this.checkbox = checkbox; this.close = close; } } let todo = new Todo(); let done = new Done(); function closeItem(item) { todo.remove(item); done.add(item); } function openItem(item) { done.remove(item); todo.add(item); } function deleteItem(item) { if (done.items.has(item)) { done.items.delete(item); done.updateCount(); } if (todo.items.has(item)) { todo.items.delete(item); todo.updateCount(); } item.node.remove(); } function createItem() { let item = new TodoItem(); item.create(); todo.add(item); } function main() { document.getElementById(&quot;addTodo&quot;).onclick = createItem; todo.updateCount(); done.updateCount(); } main(); </code></pre> <p>HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;index.css&quot;&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;main id=&quot;todoParent&quot;&gt; &lt;article id=&quot;functionality&quot;&gt; &lt;section id=&quot;toolbar&quot;&gt; &lt;button id=&quot;addTodo&quot;&gt;Add Todo&lt;/button&gt; &lt;/section&gt; &lt;section id=&quot;columns&quot;&gt; &lt;section id=&quot;todo&quot;&gt; &lt;div class=&quot;columnToolbar&quot;&gt; &lt;h1&gt;Todo&lt;/h1&gt; &lt;h1 id=&quot;todoCount&quot;&gt;&lt;/h1&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id=&quot;done&quot;&gt; &lt;div class=&quot;columnToolbar&quot;&gt; &lt;h1&gt;Done&lt;/h1&gt; &lt;h1 id=&quot;doneCount&quot;&gt;&lt;/h1&gt; &lt;/div&gt; &lt;/section&gt; &lt;/section&gt; &lt;/article&gt; &lt;/main&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre><code>html { min-height: 100%; position: relative; } body { height: 100%; } button { z-index: 10; } #todoParent { display: flex; justify-content: center; height: 100%; top:0; bottom:0; left:0; right:0; overflow:hidden; background-color: darkslategray; position:absolute; } #functionality { width: 40%; background-color: white; } #columns { display: flex; flex-direction: row; justify-content: center; } #columns h1 { text-align: center; } #columns section { background-color: #e0e0e0; border: black solid 1px; width: 250px; height: 90vh; margin: 5%; overflow-y: scroll; } #columns article { display: flex; flex-direction: column; justify-content: flex-start; background-color: white; width: 200px; height: 200px; margin: 5%; padding: 5%; } #toolbar { display: flex; justify-content: center; flex-direction: row; background-color: #e0e0e0; } #toolbar button { margin: 5px; } #todoCount { margin-left: 1%; } .todoToolbar { display: flex; flex-direction: row; justify-content: space-between; } .todoCheckbox { margin: 5%; } .todoInput { height: 100%; box-sizing: border-box; resize: vertical; } .columnToolbar { display: flex; flex-direction: row; justify-content: center; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Too complex</h2>\n<p>You have over engineered the objects.</p>\n<p><code>Column</code> should not care what it contains. All it should do is add and remove items.</p>\n<p>Inheriting from <code>Column</code> to create <code>Done</code> and <code>Todo</code> columns has just made more work for the coder.</p>\n<p>Only the <code>Todo</code> item cares about where it is. It adds it's self to the Todo column if not complete, moves it's self from the todo to done when UI clicked. and removes it's self when deleted.</p>\n<p>There should be no calls to outside function to provide this functionality.</p>\n<h2>Rewrite</h2>\n<p>Not addressing various other items the rewrite is an example of a more role driven design. This example does not include any state encapsulation as the focus is on defining clear object roles rather than state safty.</p>\n<h3>Object <code>Column</code></h3>\n<ul>\n<li><code>new Column(node, countNode); </code> Accepts nodes rather than ID's</li>\n<li><code>Column.add(item)</code> adds an item if it has a node to add. It also calls the items added function if item has that function,</li>\n<li><code>Column.remove(item)</code> Removes the item if it has it.</li>\n</ul>\n<h3>Object <code>Todo</code></h3>\n<ul>\n<li><code>new Todo()</code> Creates nodes and adds listeners and adds its self to the <code>todoColumn</code></li>\n<li><code>Todo.added(column)</code> Called by instance of <code>Column</code> to provide a reference to the column</li>\n<li><code>Todo.toggleComplete()</code> Event. Toggles the <code>complete</code> semaphore. It removes and adds it's self to the correct column as required.</li>\n<li><code>Todo.delete()</code> Event. Removes it's self from current column,</li>\n</ul>\n<p><strong>Note</strong> that the functions <code>tag</code>, <code>append</code>, <code>listener</code> are just helper functions to reduce the verbosity of DOM API calls.</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>;(()=&gt;{\n\"use strict\";\n\nconst tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst append = (par, ...sibs) =&gt; sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), par);\nconst listener = (el, name, call, opt = {}) =&gt; (el.addEventListener(name, call, opt), el);\n\nvar uid = 0;\nclass Column {\n constructor(node, countNode) {\n this.items = new Map();\n this.node = node;\n this.countNode = countNode;\n }\n updateCount() { this.countNode.textContent = \" | (\" + this.items.size + \")\" }\n add(item) {\n if (item.node) {\n item?.added(this);\n this.items.set(item, item.node);\n this.node.appendChild(item.node);\n this.updateCount();\n }\n }\n remove(item) {\n if (this.items.has(item)) {\n this.items.delete(item);\n item.node.remove();\n this.updateCount();\n }\n } \n}\n\nclass Todo {\n constructor() {\n this.complete = false;\n this.node = tag(\"article\", {id: uid++});\n const toolbar = tag(\"span\", {className: \"todoToolbar\"});\n const checkbox = listener(\n tag(\"input\", {className: \"checkbox\", type: \"checkbox\"}),\n \"click\", this.toggleComplete.bind(this)\n );\n const close = listener(\n tag(\"span\", {className: \"close\", textContent: \"✖\"}),\n \"click\", this.delete.bind(this)\n );\n \n append (\n this.node,\n append(toolbar, checkbox, close),\n tag(\"textarea\", {className: \"todoInput\"})\n );\n todoColumn.add(this);\n }\n delete() { this.column.remove(this) } \n added(column) { this.column = column }\n toggleComplete() {\n this.column.remove(this);\n this.complete = !this.complete;\n (this.complete ? doneColumn : todoColumn).add(this); \n }\n}\n\nconst todoColumn = new Column(todo, todoCount);\nconst doneColumn = new Column(done, doneCount);\nlistener(addTodo, \"click\", () =&gt; new Todo());\n\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#todoParent {\n display: flex;\n justify-content: center;\n height: 100%;\n top:0;\n bottom:0;\n left:0;\n right:0;\n overflow:hidden;\n background-color: darkslategray;\n position:absolute;\n}\n\n#functionality {\n width: 84%;\n background-color: white;\n}\n\n#columns {\n display: flex;\n flex-direction: row;\n justify-content: center;\n}\n\n#columns h1 {\n text-align: center;\n}\n\n#columns section {\n background-color: #e0e0e0;\n border: black solid 1px;\n width: 250px;\n height: 90vh;\n margin: 5%;\n overflow-y: scroll;\n}\n\n#columns article {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n background-color: white;\n width: 82%;\n margin: 5%;\n padding: 5%;\n}\n\n#toolbar {\n display: flex;\n justify-content: center;\n flex-direction: row;\n background-color: #e0e0e0;\n}\n\n#toolbar button { margin: 5px; }\n\n#todoCount { margin-left: 1%; }\n\n.todoToolbar {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n.columnToolbar {\n display: flex;\n flex-direction: row;\n justify-content: center;\n}\n.close { cursor: pointer; }\n.close:hover { color: red; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;main id=\"todoParent\"&gt;\n &lt;article id=\"functionality\"&gt;\n &lt;section id=\"toolbar\"&gt;\n &lt;button id=\"addTodo\"&gt;Add Todo&lt;/button&gt;\n &lt;/section&gt;\n &lt;section id=\"columns\"&gt;\n &lt;section id=\"todo\"&gt;\n &lt;div class=\"columnToolbar\"&gt;\n &lt;h1&gt;Todo&lt;/h1&gt;\n &lt;h1 id=\"todoCount\"&gt;&lt;/h1&gt;\n &lt;/div&gt;\n &lt;/section&gt;\n &lt;section id=\"done\"&gt;\n &lt;div class=\"columnToolbar\"&gt;\n &lt;h1&gt;Done&lt;/h1&gt;\n &lt;h1 id=\"doneCount\"&gt;&lt;/h1&gt;\n &lt;/div&gt;\n &lt;/section&gt;\n &lt;/section&gt;\n &lt;/article&gt;\n&lt;/main&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:23:17.160", "Id": "268441", "ParentId": "268363", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T00:16:45.663", "Id": "268363", "Score": "3", "Tags": [ "javascript", "html", "css", "to-do-list" ], "Title": "Simple Vanilla JS Todo app" }
268363
<p>I tried to write the program so that it runs without error but I want to improve the program so that it follows the Single Responsibility Principle. What changes can I make to improve this program? I am a beginner in programming and not good at pseudocode or commenting so if there is anything I can do to also improve there.</p> <pre><code> &quot;&quot;&quot; Pseudocode: def main(): set plants list day = 0 food = 0 display welcome() display plants() report_day() display_menu() get choice.lower() while choice != quit: if wait: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:29:11.917", "Id": "529207", "Score": "0", "body": "I'm not sure why you removed the Python part of your program, since it makes your question off-topic. If the Python code works, you can put it back. If it doesn't work, the question wasn't ready for review. Please take a look at the [help/on-topic]." } ]
[ { "body": "<h2>Pseudocode</h2>\n<p>First, your block-quoted pseudo-code is too much like code, and not enough pseudo. The purpose of pseudo-code is understanding. If it doesn't help you to understand, or if it doesn't help someone else (like a professor) to understand, then you're doing it wrong. In general, I'd suggest writing your pseudo-code in successive waves of refinement. Something like this:</p>\n<pre><code>while not done:\n get user choice()\n if choice is 'wait':\n get rainfall()\n if rainfall amount &lt; threshold:\n kill one plant()\n produce food from plants remaining()\n if choice is 'add plant':\n add new plant()\n if choice is 'display plants':\n display plants()\n if choice is 'quit':\n quit()\n \n print daily report()\n</code></pre>\n<p>That's probably enough to get yourself started writing code, and it might be enough to make a teacher happy. The details should be in the code itself, unless you are forced to change your logic.</p>\n<h2>Naming</h2>\n<p>You need to read and apply the <a href=\"https://www.pep8.org\" rel=\"nofollow noreferrer\">Python style guide.</a></p>\n<p>In particular: documentation for functions goes in the function's docstring. Constants should be ALL_CAPS.</p>\n<h2>Functions</h2>\n<p>You have some good functions. But I submit to you that each time you have a comment in your code, that's probably a good place for a function. Sometimes, you can combine several comments into a single function, but in general, if you're explaining what happens, you can explain better using a function and its accompanying docstring:</p>\n<pre><code> if rainfall &lt; high_threshold: \n plant_die = random.choice(plants) # pick random a plant for too little rain\n print(f&quot;Sadly, your {plant_die} plant has died&quot;) \n plants.remove(plant_die) # remove plant from list\n</code></pre>\n<p>Could be rewritten as:</p>\n<pre><code>if rainfall &lt; high_threshold:\n one_plant_dies(plants)\n</code></pre>\n<h2>Wrapping</h2>\n<p>Your text output functions are relying on the <code>print()</code> statement to emit each line. This means that wrapping of text is occurring at the line level.</p>\n<p>In many cases, you would do better to use the <a href=\"https://docs.python.org/3/library/textwrap.html\" rel=\"nofollow noreferrer\"><code>textwrap</code> </a> module to perform wrapping for you, and put entire paragraphs in <em>&quot;&quot;&quot;triple quotes.&quot;&quot;&quot;</em></p>\n<h2>Results</h2>\n<p>You have written all your functions as procedures -- subroutines that do not return a value. If you haven't encountered the <code>return</code> statement, I encourage you to read about it. You will find it very hard to use the SRP if you cannot return values.</p>\n<p>Much of your code looks like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>print some information\nget some input\n</code></pre>\n<p>That sort of thing is a good candidate for encapsulation in a function that returns <em>well validated</em> result. Thus, your code might be something like:</p>\n<pre><code>def get_user_preference(params):\n while True:\n print some information\n get some input\n if input is valid:\n return result(input)\n</code></pre>\n<h2>main()</h2>\n<p>There's a standard way to handle calling the main entry point of your program or module:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>The purpose and value of this is that it will call <code>main()</code> when you just run <code>python mycode.py</code> but it will <em>not</em> call anything if you <code>import mycode</code>. This is valuable if you are writing a program that is also a library, or if you are using a unit test driver that will import your code into its test engine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T02:20:46.223", "Id": "529203", "Score": "0", "body": "thank you so much. I was able to fix my code and create the 3 functions for wait option. I still don't understand how I can come up with psuedo code prior to programming, but I will be working on that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T01:46:30.813", "Id": "268365", "ParentId": "268364", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T00:22:30.063", "Id": "268364", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "functional-programming" ], "Title": "Garden simulator" }
268364
<p>The problem states that you have to rob the maximum money stashed in the houses but you cannot rob two adjacent houses. array[i] denotes the money in the (i)th house. I got the following code submitted but Is there a more optimised aprroach. I saw a very small solution on the YouTube Channel 'NeetCode' but couldn't understand the solution.(<a href="https://youtu.be/73r3KWiEvyk" rel="nofollow noreferrer">https://youtu.be/73r3KWiEvyk</a>). Below two test scenarios:</p> <p><strong>Example 1:</strong></p> <p>Input: nums = [1,2,3,1]</p> <p>Output: 4</p> <p>Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.</p> <p><strong>Example 2:</strong></p> <p>Input: nums = [2,7,9,3,1]</p> <p>Output: 12</p> <p>Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.</p> <pre><code>package com.company; import java.util.Arrays; public class RobTheMax { static int Rob(int[] nums,int[] dp) { Arrays.fill(dp,-1); int max = 0; for (int i = 0; i &lt; nums.length; i++) { int val = rob(i,nums,dp); if (val &gt; max) { max= val; } } return max; } static int rob(int indexToBegin,int[] nums,int[] storage) { int big_val = 0; int nums_val = nums[indexToBegin]; int storage_value = storage[indexToBegin]; if (storage_value != -1) { return storage_value; } if (indexToBegin + 2 &gt;= nums.length) { return nums_val; } else { for (int i = indexToBegin + 2; i &lt; nums.length; i++) { int val = rob(i,nums,storage); if (val &gt; big_val) { big_val = val; } } storage[indexToBegin] = big_val + nums_val; return big_val + nums_val; } } public static void main(String[] args) { int[] nums = {2,1,1,2}; int[] dp = new int[nums.length]; System.out.println(&quot;max robbery is &quot; + Rob(nums,dp)); } } </code></pre> <p>Link to the original problem is <a href="https://leetcode.com/problems/house-robber/" rel="nofollow noreferrer">https://leetcode.com/problems/house-robber/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:45:58.323", "Id": "529208", "Score": "0", "body": "Hello, I added the two test scenarios included in the link to the description of the problem for a better understanding of the task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T17:51:04.307", "Id": "529261", "Score": "0", "body": "Copying your code to the leetcode site ends with a compilation error. Have you run it just locally and not on the site?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T20:47:26.447", "Id": "530605", "Score": "0", "body": "I confirm that this code works, just not as copy-pasted verbatim on leetcode. With cosmetic adaptation the solution passes on leetcode." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:02:48.327", "Id": "268367", "Score": "0", "Tags": [ "java", "performance", "programming-challenge", "dynamic-programming" ], "Title": "Better Approach for the House Robbery Problem (LeetCode 198)?" }
268367
<p>So, I just finished Problem 10 on Project Euler, but it took about 3 to 4 minutes for my output to come out, due to bad coding, I guess, any suggestions on how could I optimize my code?</p> <p><strong>Question</strong></p> <p><strong>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</strong></p> <p><strong>Find the sum of all the primes below two million.</strong></p> <p>Here is my code:</p> <pre><code>public static void main(String[] args) { // var int i, k = 3; long sum = 2; // processing for(i = 2; i &lt;= 2000000;){ if (i % 2 == 0){ i++; k = 3; }else{ if (i % k == 0 &amp;&amp; i != k){ i++; k = 3; }else { if (i == k) { sum = (sum + i); i++; k = 3; }else { k = (k + 2); } } } } // out System.out.print(&quot;The result is: &quot; + sum); } </code></pre>
[]
[ { "body": "<p>The main problem I see is, that you don't use the number one rule in software development, which is: <em><strong>split the problem</strong></em>.</p>\n<p>When you want to know the sum of primes up to <em>n</em>, you basically have two distinct parts to solve:</p>\n<ol>\n<li>know the primes up to <em>n</em></li>\n<li>sum these primes up</li>\n</ol>\n<p>For part 1, use a commonly known algorithm like the sieve of Erasthostenes, for part 2 do a loop.</p>\n<p>(I hacked away such a solution while drinking my first cup of coffee today, and it completes in about 20 ms.)</p>\n<p>Regarding your code: I don't have the slightest idea what it does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:52:35.390", "Id": "268369", "ParentId": "268368", "Score": "1" } }, { "body": "<blockquote>\n<pre><code> int i, k = 3;\n</code></pre>\n</blockquote>\n<p>I'm simply going to delete this line. In general, it is better to declare variables as close to first use as possible. In this case, inside the loop is possible.</p>\n<blockquote>\n<pre><code> for(i = 2; i &lt;= 2000000;){\n</code></pre>\n</blockquote>\n<p>For every candidate number from 2 to 2,000,000. But I can tell you immediately that about half of those won't be prime. Consider</p>\n<pre><code> outer:\n for (int i = 3; i &lt;= 2000000; i += 2) {\n</code></pre>\n<p>Now you won't waste your time checking even numbers for primality. There's only one, so you can just skip along once you include it in the <code>sum</code> (which you already did, good work). I'll explain more about the <code>outer:</code> label later.</p>\n<blockquote>\n<pre><code> if (i % 2 == 0){\n i++;\n k = 3;\n }else{\n</code></pre>\n</blockquote>\n<p>If we're only checking odd numbers, we don't have to check if they are even. We can just delete this (and don't forget the <code>}</code> at the end).</p>\n<blockquote>\n<pre><code> if (i % k == 0 &amp;&amp; i != k){\n i++;\n k = 3;\n }else {\n if (i == k) {\n sum = (sum + i);\n i++;\n k = 3;\n }else {\n k = (k + 2);\n }\n }\n</code></pre>\n</blockquote>\n<p>Well, looking at it one way, this is rather clever. You increment different variables based on certain conditions. So one <code>for</code> loop effectively loops over two different variables. But from another perspective, it's wasted cleverness. You're making things more complicated for no real gain. It would be better to simply nest another <code>for</code> loop here. Why? Well, let's look at it:</p>\n<pre><code> for (int k = 3; k &lt;= i / k; k += 2) {\n if (i % k == 0) {\n continue outer;\n }\n }\n\n sum += i;\n</code></pre>\n<p>So from your twelve lines of code, we drop to seven (eight if we count the blank line, but we usually wouldn't).</p>\n<p>One of the seven lines is the <code>outer:</code> label. Basically that allows us to say that we are done with the inner loop and want to skip the rest of the current iteration of the outer loop. We will resume (or <code>continue</code>) immediately before the increment step or immediately after the body of the loop (same thing; different descriptions). Note that we could make it more readable by moving the logic to check if an odd prime into a separate method. But this is more like your existing solution.</p>\n<p>This moves all the management of <code>k</code> into the <code>for</code> loop. Now our check if <code>i</code> is not prime is much simpler. And we don't have to consider whether or not we want to increment <code>i</code>. We do that every iteration of the outer loop. Nor do we have to think about whether we increment <code>k</code>. We do that every iteration of the inner loop. Your code wasted cleverness on determining whether you wanted to do those things. But nesting the loops does the same thing without cleverness. As such, it is a simpler, more elegant solution.</p>\n<p>We also check fewer values here. Note that your loop checked from 2 to <code>i</code>. But we don't need to check to <code>i</code>. If something is a factor, then there must be a factor that is less than or equal to the square root of <code>i</code>. And <code>k &lt;= i / k</code> is the same as <code>k * k &lt;= i</code> or <code>k &lt;= Math.sqrt(i)</code>. It's the preferred check here for a few reasons.</p>\n<ol>\n<li><code>k * k</code> may overflow the <code>int</code> size. <code>i / k</code> won't.</li>\n<li>In many systems, both <code>i % k</code> and <code>i / k</code> will be calculated at the same time. So since you would next check <code>i % k</code>, the <code>i / k</code> is almost free (not quite since if it fails, you don't check <code>i % k</code>).</li>\n<li>It is usually cheaper (in time) to compute <code>i % k</code> than <code>Math.sqrt(k)</code>.</li>\n</ol>\n<p>The counter-argument would be that you can calculate <code>Math.sqrt(k)</code> once, prior to the loop and save it in a variable. But as I said, in many systems, you only have to calculate <code>i / k</code> separately once and it will almost always be cheaper than calculating the square root.</p>\n<h3>Time complexity analysis</h3>\n<p>Only checking odd numbers won't affect the complexity analysis. But it may still make things faster.</p>\n<p>The larger change is likely to be stopping at the square root. The square root of a million is a thousand. Would you prefer to do something a million times or a thousand? Hopefully obvious that the square root is better.</p>\n<h3>Separation of concerns</h3>\n<p>As noted <a href=\"https://codereview.stackexchange.com/a/268369/71574\">elsewhere</a>, it is often better to separate different concerns. In this case, one concern is generating the primes and another is summing them (and it would be reasonable to think of checking primality as a third). This is true, but I ignored it to concentrate on improvements to the way that you are doing things now. However, please do not take this as an endorsement of mixing concerns like this. That is not usually recommended except in specific cases where optimization demands it. This probably isn't one of those cases.</p>\n<p>For similar reasons, I stuck with testing by trial division rather than using a sieving algorithm. But that doesn't mean that a sieve wouldn't solve this problem more quickly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T04:49:00.000", "Id": "529287", "Score": "0", "body": "Thank you so much for your answer, it really teached me A LOT, thank you very very much" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T06:52:34.233", "Id": "268371", "ParentId": "268368", "Score": "2" } } ]
{ "AcceptedAnswerId": "268371", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:11:52.377", "Id": "268368", "Score": "1", "Tags": [ "java", "performance", "beginner", "programming-challenge", "primes" ], "Title": "Improving Project Euler code problem #10" }
268368
<p>I don't know why there's no such function in std (at least I didn't find one). I need a conditional template function to return a reference to an object of <code>T</code>. <code>T</code> might be passed as a pointer or a smart pointer or by reference:</p> <pre><code>template &lt;typename T&gt; void do_foo(T &amp;t) { auto &amp;&amp;res = dereference(t).foo(); } </code></pre> <p>So I wrote this:</p> <pre><code>#include &lt;memory&gt; #include &lt;type_traits&gt; namespace eld::traits { template&lt;typename T&gt; struct is_pointer_like : std::is_pointer&lt;T&gt; { using value_type = T; }; template&lt;typename T, typename DeleterT&gt; struct is_pointer_like&lt;std::unique_ptr&lt;T, DeleterT&gt;&gt; : std::true_type { using value_type = T; }; template&lt;typename T&gt; struct is_pointer_like&lt;std::shared_ptr&lt;T&gt;&gt; : std::true_type { using value_type = T; }; namespace detail { template&lt;typename T, bool /*false*/ = is_pointer_like&lt;T&gt;::value&gt; struct dereference { constexpr explicit dereference(T &amp;t) // : value(t) { } T &amp;value; }; template&lt;typename PtrT&gt; struct dereference&lt;PtrT, true&gt; { constexpr explicit dereference(PtrT &amp;ptrT) : value(*ptrT) {} typename is_pointer_like&lt;PtrT&gt;::value_type &amp;value; }; } // namespace detail template &lt;typename T&gt; constexpr auto&amp; dereference(T &amp;t) { return detail::dereference&lt;std::decay_t&lt;T&gt;&gt;(t).value; } template &lt;typename T&gt; constexpr const auto&amp; dereference(const T &amp;t) { return detail::dereference&lt;const std::decay_t&lt;T&gt;&gt;(t).value; } } // namespace eld::traits </code></pre> <hr /> <p>This code does not support the concept of shared pointer though. <code>dereference</code> does not increment a counter, so using an obtained reference is dangerous. Because when <code>std::shared_ptr</code> is used the user is expected to hold a copy of it (like with <code>std::weak_ptr</code>).<br /> Taking it into an account I suppose using <code>dereference</code> as a function is a wrong approach. I think that <code>dereference</code> should be a persistent object if I expect it to support a concept of sharable ownership.</p> <pre><code>template &lt;typename T&gt; void so_stuff(T &amp;t) { dereference derefT{t}; auto &amp;refT = derefT.value(); auto &amp;&amp;res = refT.foo(); } </code></pre> <p>However, this becomes convoluted in use.</p> <hr /> <p>Also, I feel like using <code>is_pointer_like</code> is redundant. Maybe I am better of just implementing <code>dereference</code> with SFINAE customizations for raw and smart pointers.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:28:12.030", "Id": "529217", "Score": "0", "body": "Can you explain the motivation for this a bit more? I'm guessing that it's a helper for other templates which you want to use with pointer-like types, but at some point there has to be some invocation, so is this just a matter of saving someone a `*` somewhere in the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:49:03.463", "Id": "529221", "Score": "0", "body": "@TobySpeight you are correct, it is a utility to be used within a tempate function. As you can see from an example `void do_stuff`, I need to invoke a member function of T. But I don't want to limit T to be either a reference or a pointer. Because member invokation for the latter requires dereferencing. So template for a pointer would not compile for a reference. Hence I want an adapter that will access the member and compile in both cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:55:21.873", "Id": "529223", "Score": "0", "body": "Why not call `do_stuff(*foo)` when using with a pointer? (I'm assuming that's a function similar to `so_stuff()` in the question) Is it because `foo` has come from dereferencing an iterator or something, where the caller can't know whether it needs to dereference for itself? I'm asking because that might make a difference to the object-lifetime concerns you mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T08:58:45.313", "Id": "529224", "Score": "0", "body": "@TobySpeight `the caller can't know whether it needs to dereference for itself` exactly. In case you have a complex template logic and you assume that at *some* point you get an object which might be a pointer, or not. It will facilitate, for example, modification of containers. You would be able to change value type to be a pointer, without changing the logic (adding or removing dereferencing)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T19:04:21.350", "Id": "529318", "Score": "0", "body": "I think that what you want is somewhere buried in here: https://github.com/CarloWood/ai-utils/blob/master/print_using.h .. but no time to extract it for you." } ]
[ { "body": "<h1>It is probably a bad idea</h1>\n<p>Your <code>dereference()</code> will even work if you don't give it a pointer-like type:</p>\n<pre><code>int foo = 42;\nstd::cout &lt;&lt; eld::traits::dereference(foo) &lt;&lt; '\\n';\n</code></pre>\n<p>That prints out 42. Maybe it's still simple when we deal with (a pointer to) an <code>int</code>, but what if we have a pointer to a pointer? Do you want the first pointer or the second pointer? Or dereference all the way until we get a non-pointer value? It's not even that far-fetched: what if we have a function that that operates on an iterator, and the iterator may or may not be passed via a pointer, but the iterator itself could be just a plain pointer (like <code>std::begin()</code> on a C-style array)?</p>\n<p>It would really be much better if you put the burden of dereferencing on the caller, as the caller knows best what to do.</p>\n<p>Perhaps as a compromise, assuming we want a <code>T</code> but it might be passed as <code>T&amp;</code>, <code>T*</code> or <code>std::smart_ptr&lt;T&gt;</code>, you could change <code>dereference()</code> so that you have to provide the expected <em>value</em> type <code>T</code> as a template parameter.</p>\n<h1>About supporting <code>std::shared_ptr</code></h1>\n<blockquote>\n<p>This code does not support the concept of shared pointer though. <code>dereference</code> does not increment a counter, so using an obtained reference is dangerous.</p>\n</blockquote>\n<p>If you want to do call <code>derefence()</code> on a <code>std::shared_ptr</code>, I would not worry about it. Your <code>derefence()</code> returns a reference, so it's already required that you should keep the original object alive for the duration you are using the reference you got. This is no different from dereferencing or calling <code>get()</code> on a <code>std::shared_ptr</code> itself.</p>\n<h1>It does not work on raw pointers</h1>\n<p>Surprisingly, while your code works fine with smart pointers, it doesn't work with raw pointers. The problem is that the first <code>is_pointer_like</code> version doesn't actually remove the pointer from <code>T</code>. That's easy to fix:</p>\n<pre><code>template&lt;typename T&gt;\nstruct is_pointer_like : std::is_pointer&lt;T&gt;\n{\n using value_type = std::remove_pointer_t&lt;T&gt;;\n};\n</code></pre>\n<h1>It doesn't work with temporary <code>std::unique_ptr</code> and <code>std::shared_ptr</code>s</h1>\n<p>The following doesn't work either:</p>\n<pre><code>std::cout &lt;&lt; eld::traits::dereference(std::make_unique&lt;int&gt;(42)) &lt;&lt; '\\n';\n</code></pre>\n<p>Even though it works if you pass in a named <code>std::unique_ptr</code> variable. The reason is that while you correctly handle <code>const</code> in the function <code>dereference()</code>, you are missing specializations of <code>is_pointer_type</code> that handle <code>const std::unique_ptr</code> and <code>const std::shared_ptr</code>. You have to add:</p>\n<pre><code>template&lt;typename T, typename DeleterT&gt;\nstruct is_pointer_like&lt;const std::unique_ptr&lt;T, DeleterT&gt;&gt; : std::true_type\n{\n using value_type = const T;\n};\n\ntemplate&lt;typename T&gt;\nstruct is_pointer_like&lt;const std::shared_ptr&lt;T&gt;&gt; : std::true_type\n{\n using value_type = const T;\n};\n</code></pre>\n<p>Adding a test suite would be helpful in finding these kinds of problems.</p>\n<h1>Simplifying the code</h1>\n<p>One issue at the moment is that you have to explicitly handle both <code>std::shared_ptr</code> and <code>std::unique_ptr</code>, and <code>const</code> and non-<code>const</code> versions of both, duplicating a lot of code. With SFINAE or C++20 concepts, it might be possible to make an <code>is_pointer_like</code> that handles both smart pointers in the same way, and might even support other smart point types that have the same interface. In particular, both <code>std::shared_ptr</code> and <code>std::unique_ptr</code> have a member type <code>element_type</code>, and a member function <code>get()</code>. It would then also work with the deprecated <code>std::auto_ptr</code>. Ideally it looks like:</p>\n<pre><code>template&lt;typename T&gt;\nrequires is_smart_pointer_like&lt;T&gt;\nstruct is_pointer_like&lt;T&gt; : std::true_type\n{\n // Deduce the value type such that const is propagated\n using value_type = std::remove_reference_t&lt;decltype(*std::declval&lt;T&amp;&gt;())&gt;;\n};\n</code></pre>\n<p>Then the trick is just to implement the concept <code>is_smart_pointer_like</code>.\nBut note that there is nothing in the body that uses <code>element_type</code> or <code>get()</code>, it only needs <code>T</code> to be dereferencable. So perhaps you could even just check for that, as it will then also work for regular pointers, but on the other hand this might match more types than you like. For example, it would then match iterators.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T10:42:16.527", "Id": "268374", "ParentId": "268370", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T06:42:50.563", "Id": "268370", "Score": "1", "Tags": [ "c++", "template-meta-programming" ], "Title": "template function for conditional dereference" }
268370
<p>Dabbling a bit more with arm assembly, I wrote a few functions to handle string splitting. The goal was to write a few reusable functions that could be combined to emulate (roughly) what C <code>strtok()</code> does. The approach was essentially to write <code>strspn()</code> and <code>strcspn()</code> approximations and then combine them in the function that tokenizes the string.</p> <p>All works as intended, but I'm concerned about the efficiency of the data-handling. The loads, moves, adds, and register use seem like it should be able to be improved on. Currently it is written so it was easy to read, but each function is making use of up to five registers (<code>r4</code> - <code>r8</code>) as well as grabbing an extra few bytes of stack space when needed. Is there a trade-off in pushing and popping that number of registers with every function call compared with just using additional stack space in each function for temporary storage?</p> <p>The primary feedback I'm looking for is whether the data-handling between and within the functions is reasonable and makes sense, or if there are glaring areas where that can be optimized.</p> <p>The main program prompts for and takes the string to tokenize along with the delimiter string as user inputs. It then loops calling <code>strtoka</code> keeping track of the number of tokens found and the number of characters consumed in the string each iteration. The token number along with the token are output. The program is limited to processing 10 tokens just due to the output using a single digit token-number for testing. Otherwise it will handle any number of tokens up to a 32-bit limit.</p> <p>(all the string function names just have an <code>a</code> tacked onto the end of the C function names, e.g. <code>strtoka</code>, <code>strspna</code>, <code>strcspna</code>, <code>strlena</code>, ...)</p> <p>The example code is:</p> <pre><code>/* Split string on delimiters * Reads string and delimiters as user input and splits string on * occurrence or sequence of deliters entered. Roughly modeling * C strtok() implemented with alternating strspn() and strcspn(). * * Compile/Link: * as -mcpu=cortex-a53 -o obj/split_string.o split_string.s * ld -o bin/split_string obj/split_string.o * * Example Use: * * enter string : -.one,two.three-four+five?six * delimiters : ?+-., * token 0 : one * token 1 : two * token 2 : three * token 3 : four * token 4 : five * token 5 : six * */ /* Define Raspberry Pi 3 B/B+ */ .cpu cortex-a53 .fpu neon-fp-armv8 .syntax unified /* modern syntax */ /* constants uninitialized variables */ .bss .align 2 .lcomm delim, 32 .lcomm buffer, 128 /* constannts for functions */ .data .align 2 .equ STDIN, 0 .equ STDOUT, 1 .equ STDERR, 2 .equ MAXD, 32 .equ MAXC, 128 .equ nul, 0 prompt: .asciz &quot;enter string : &quot; .equ promptlen,.-prompt spliton: .asciz &quot;delimiters : &quot; .equ splitonlen,.-spliton result: .asciz &quot;token &quot; .equ resultlen,.-result resend: .asciz &quot; : &quot; .equ resendlen,.-resend .text .align 2 .global _start .type _start, %function _start: stmdb sp!, {r4, r5, r6, r7, r8, fp, lr} /* prologue */ mov fp, sp /* set stack frame */ sub sp, sp, 8 /* 4-bytes extra storage */ eor r4, r4, r4 /* zero token counter */ eor r7, r7, r7 /* zero offset in string */ /* prompt, read and validate string to be split */ mov r0, STDOUT /* stdout file no. to r0 */ ldr r1, promptadr /* prompt address in r1 */ mov r2, promptlen /* length in r2 */ bl writenchar /* display prompt */ mov r0, STDIN /* stdin file no. in r0 */ ldr r1, bufferadr /* char array address in r1 */ mov r2, MAXC /* length in r2 */ bl readstr /* read user-input */ cmp r0, 0 /* VALIDATE no. of chars read */ moveq r1, 1 /* return EXIT_FAILURE */ beq returnerr /* branch to error */ /* prompt, read and validate delimiters to split string */ mov r0, STDOUT /* stdout file no. to r0 */ ldr r1, splitonadr /* result address in r1 */ mov r2, splitonlen /* length in r2 */ bl writenchar /* display result prefix */ mov r0, STDIN /* stdin file no. in r0 */ ldr r1, delimadr /* char array address in r1 */ mov r2, MAXD /* length in r2 */ bl readstr /* read user-input */ cmp r0, 0 /* VALIDATE no. of chars read */ beq returnerr /* branch to error */ tokenize: /* call strcspna to obtain length of first token */ ldr r0, bufferadr /* load buffer addr in r0 */ add r0, r0, r7 ldr r1, delimadr /* load delimiter addr in r1 */ bl strtoka /* strtok() */ cmp r2, 0 /* check token length */ beq tokend /* done if zero */ sub r3, r1, r0 /* get delimiters consumed */ add r3, r3, r2 /* get total offset for tok */ add r7, r7, r3 /* add to offset from str start */ mov r6, r1 /* save token start addr */ mov r8, r2 /* save no. chars in token */ /* output prefix for token */ mov r0, STDOUT /* stdout file no. to r0 */ ldr r1, resultadr /* result address in r1 */ mov r2, resultlen /* length in r2 */ bl writenchar /* display result prefix */ add r5, r4, '0' /* add ASCII '0' to token count */ strb r5, [sp, -1]! /* token no. at sp, pre-increment */ add r4, r4, 1 /* increment token count */ mov r0, STDOUT /* stdout file no. to r0 */ mov r1, sp /* char address in r2 */ mov r2, 1 /* length in r2 */ bl writenchar mov r0, STDOUT /* stdout file no. to r0 */ ldr r1, resendadr /* result address in r1 */ mov r2, resendlen /* length in r2 */ bl writenchar /* display result ending */ mov r0, STDOUT /* display token */ mov r1, r6 mov r2, r8 bl writenchar bl newln /* tidy up with newline */ mov r0, 10 /* check count &lt; 10 */ cmp r4, r0 /* (single digit output limit) */ beq tokend b tokenize tokend: mov r0, 0 /* return EXIT_SUCCESS */ b alldone returnerr: mov r0, 1 alldone: add sp, sp, 8 ldmia sp!, {r4, r5, r6, r7, r8, fp, lr} /* epilogue */ mov r7, 1 /* __NR_exit syscall */ svc 0 bufferadr: .word buffer delimadr: .word delim promptadr: .word prompt splitonadr: .word spliton resultadr: .word result resendadr: .word resend /* implements strspn from C. finds the initial number of * characters in str (r0) that are contained in delim. * * parameters: * r0 - address of string * r1 - address of delimiter string * return: * r0 - number of initial characters matching chars in delimiter */ .text .align 2 .global strspna .type strspna, %function strspna: stmda sp!, {r4, r5, r6, r8, fp, lr} /* prologue */ sub fp, sp, 4 /* set stack frame */ eor r4, r4, r4 /* zero r4 for counter */ strspstr: ldrb r5, [r0, r4] /* load str char in r5 w/offset r4 */ cmp r5, nul /* check for nul-char end of str */ beq strspnex mov r6, r1 /* load delim str address in r6 */ strspdelim: ldrb r8, [r6], 1 /* load delim char in r8 post inc r6 */ cmp r8, nul /* check end of delim */ beq strspnex /* delim not found, done */ cmp r8, r5 /* cmp delim char &amp; str char */ addeq r4, 1 /* inc no. offset in str */ beq strspstr /* if chars eq, get next str char */ b strspdelim /* get next char in delim */ strspnex: mov r0, r4 /* return initial no. chars in r0 */ ldmib sp!, {r4, r5, r6, r8, fp, lr} /* epilogue */ bx lr /* return */ /* implements strcspn from C. finds the initial number of * characters in str (r0) that are not contained in delim. * * parameters: * r0 - address of string * r1 - address of delimiter string * return: * r0 - number of initial characters not in delimiter */ .text .align 2 .global strcspna .type strcspna, %function strcspna: stmda sp!, {r4, r5, r6, r8, fp, lr} /* prologue */ sub fp, sp, 4 /* set stack frame */ eor r4, r4, r4 /* zero r4 for counter */ strcstr: ldrb r5, [r0, r4] /* load str char in r5 w/offset r4 */ cmp r5, nul /* check for nul-char end of str */ beq strcspnex mov r6, r1 /* load delim str address in r6 */ strcdelim: ldrb r8, [r6], 1 /* load delim char in r8 post inc r6 */ cmp r8, nul /* check end of delim */ addeq r4, 1 /* inc no. offset in str */ beq strcstr /* get next char in str */ cmp r8, r5 /* cmp delim char &amp; str char */ beq strcspnex /* if chars eq, done */ b strcdelim /* get next char in delim */ strcspnex: mov r0, r4 /* return initial no. chars in r0 */ ldmib sp!, {r4, r5, r6, r8, fp, lr} /* epilogue */ bx lr /* return */ /* implements strtok from C. locates start of token in string * delimiter string returing address of token in r1 and length * in r2. * * parameters: * r0 - address of string (updated in caller after each token) * r1 - address of delimiter string * return: * r0 - address (unchanged) * r1 - address of start of token * r2 - number of characers in token */ .text .align 2 .global strtoka .type strtoka, %function strtoka: stmda sp!, {r4, r5, r6, r8, fp, lr} /* prologue */ sub fp, sp, 4 /* set stack frame */ mov r5, r0 /* save string address in r5 */ mov r8, r1 /* save delimiter address in r8 */ bl strspna /* handle leading delimiters */ mov r4, r0 /* save offset to first token in r4 */ ldrb r6, [r5, r4] /* load char at r5 + r4 in r6 */ cmp r6, nul /* check at end/empty-string */ eoreq r2, r2, r2 /* return 0 chars in token in r2 */ beq strtokex /* branch to end */ add r6, r5, r4 /* add string addr and offset */ mov r0, r6 /* addr for token start in r0 */ mov r1, r8 /* set delimiter in r1 */ bl strcspna /* get token length */ mov r2, r0 /* return no. chars in token in r2 */ strtokex: mov r0, r5 /* return addr of string in r0 */ mov r1, r6 /* return start of token in r1 */ ldmib sp!, {r4, r5, r6, r8, fp, lr} /* epilogue */ bx lr /* return */ /* read string from file descriptor upto max chars, * '\n' character is read but not included in string * parameters: * r0 - file descriptor to read * r1 - address of string to fill * r2 - maximum number of bytes including null * return: * r1 - address (unchanged) * r0, r2 - number of characters read */ .text .align 2 .global readstr .type readstr, %function readstr: stmdb sp!, {r4, r5, r6, r7, r8, fp, lr} mov fp, sp sub sp, sp, 4 mov r4, r0 /* file descriptor in r4 */ mov r5, r1 /* string address in r5 */ mov r6, r2 /* max count in r6 */ sub r6, r6, 1 /* subtract one for nul char */ eor r8, r8, r8 /* zero r8 for character count */ rdcharcnt: mov r0, r4 add r1, r5, r8 /* load address + r8 into r1 */ mov r2, 1 /* read one byte */ mov r7, 3 /* __NR_read syscall */ svc 0 cmp r0, 1 /* validate 1-char read */ blt terminate /* on EOF or error, terminate */ @ mov r2, 10 ldrb r3, [r1] /* load character written in r3 */ cmp r3, 10 /* compare if \n character */ beq terminate /* terminate overwriting \n with \0 */ cmp r8, r6 /* max chars reached? */ beq rdcharcnt /* loop discarding additional chars */ add r8, 1 /* increment count in r2 */ b rdcharcnt /* loop, read next char */ terminate: mov r0, 0 /* 0 for \0 in r0 */ @ strb r0, [r1] strb r0, [r5, r8] /* stored \0 index in r8 */ mov r2, r8 /* set length return in r2 and r0 */ mov r0, r8 mov r1, r5 /* restore address of string in r1 */ readstrex: /* epilogue */ add sp, sp, 4 ldmia sp!, {r4, r5, r6, r7, r8, fp, lr} bx lr /* return */ /* length of c-string strlen() * r1 - address of string to write * return: * r2 - number of characters */ .text .align 2 .global strlena .type strlena, %function strlena: stmdb sp!, {r4, fp, lr} /* save r4, fp, lr */ mov fp, sp /* set stack frame */ sub sp, sp, 4 /* 8-byte align stack */ mov r4, r1 /* string address in r4 */ eor r2, r2 /* zero r2 for character count */ charcnt: ldrb r3, [r4], 1 /* load char into r3, post-increment in r4 */ cmp r3, nul /* nul-terminating character? */ beq strlenex /* branch to write to file */ add r2, 1 /* increment count in r2 */ b charcnt /* loop */ strlenex: add sp, sp, 4 ldmia sp!, {r4, fp, lr} /* epilogue */ bx lr /* return */ /* print c-string to file descriptor (stdout default) * r0 - file descriptor * r1 - address of string to write * return: * r0 - number of characters written */ .text .align 2 .global writestr .type writestr, %function writestr: stmdb sp!, {r7, fp, lr} /* save r7, fp, lr */ mov fp, sp /* set stack frame */ sub sp, sp, 4 /* 8-byte align stack */ bl strlena /* strlen of r1, length returned in r2 */ cmp r2, 0 beq wstrexit mov r7, 4 /* __NR_write in r7 */ svc 0 wstrexit: add sp, sp, 4 ldmia sp!, {r7, fp, lr} /* epilogue */ bx lr /* return */ /* print n-chars to file descriptor (stdout default) * r0 - file descriptor * r1 - address of string to write * r2 - number of characters to write * return: * r0 - number of characters written */ .text .align 2 .global writenchar .type writenchar, %function writenchar: stmdb sp!, {r7, fp, lr} /* save r7, fp, lr */ mov fp, sp /* set stack frame */ sub sp, sp, 4 /* 8-byte align stack */ ldrb r7, [r1] /* load 1st char for comparison */ cmp r7, 0 /* check for empty-string */ beq wnchrexit mov r7, 4 /* __NR_write in r7 */ svc 0 wnchrexit: add sp, sp, 4 ldmia sp!, {r7, fp, lr} /* epilogue */ bx lr /* return */ /* write a newline to stdout * no parameters, all registers preserved * return: * none */ .text .align 2 .global newln .type newln, %function newln: stmdb sp!, {r7, fp, lr} /* save r7, fp, lr */ mov fp, sp /* set stack frame */ sub sp, sp, 4 /* 8-byte align stack */ mov r0, 1 /* mov #1 to r0 (stdout fd) */ @ add r1, r1, sp /* sp address in r1 */ add r1, sp, 0 /* sp address in r1 */ mov r3, 0xa /* move '\n' to r3 */ mov r2, r0 /* move length of write to r2 */ strb r3, [r1, -1]! /* store '\n' at sp, pre-increment to write */ @ strb r3, [r1] /* store '\n' at sp, pre-increment to write */ mov r7, 4 /* __NR_write in r0 */ svc 0 add sp, sp, 4 ldmia sp!, {r7, fp, lr} /* epilogue */ bx lr /* return */ </code></pre> <p>Also of interest is whether it is poor form just to use what seems like a large number of registers in each function instead of simply moving the stack pointer and using the stack space for storage instead. Situations like using two registers to temporarily save the token start address and number of characters in the token, e.g.</p> <pre><code> mov r6, r1 /* save token start addr */ mov r8, r2 /* save no. chars in token */ </code></pre> <p>My thoughts were simply to use the registers available to avoid load or store later, but I end up saving and restoring 4-5 registers worth of data in each prologue and epilogue. That seems fine, but there may be considerations of efficiency I'm missing in the trade-off between pushing and popping the number of registers versus just using stack space within the function to minimize that.</p> <p>Those are the primary areas of critique I'm interested in.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T06:59:38.400", "Id": "268372", "Score": "4", "Tags": [ "assembly", "arm" ], "Title": "Arm Assembly Tokenize String (strtok()), Load Move, Add Efficiency" }
268372
<p>I was watching <a href="https://www.youtube.com/watch?v=MacVqujSXWE" rel="nofollow noreferrer">Computerphile's video on using genetic algorithms</a> to solve <a href="https://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow noreferrer">the Knapsack problem</a>, and I decided to give it a whack.</p> <p>For anyone running the code, the <code>result_data</code> pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">Data Frame</a> contains the most recent iteration's breakdown of the genomes that are &quot;still alive&quot;.</p> <pre><code>&gt;&gt;&gt; result_data solution count fitness reproduction_probability population_size 0 11010000 36 11 0.462117 47 1 10000001 1 11 0.462117 1 2 00001100 31 10 0.420788 39 3 01011000 1 10 0.420788 1 4 01000001 1 10 0.420788 1 .. ... ... ... ... ... 90 00100111 1 0 -0.064774 1 91 00011110 1 0 -0.064774 1 92 00010011 1 0 -0.064774 1 93 00001111 1 0 -0.064774 1 94 00001110 1 0 -0.064774 1 </code></pre> <p>The <code>fitness</code> parameter is a particular solution's utility as calculated by the fitness function, which is itself simply the sum of the values of all the items in the solution. When the sum of the weights exceed the specified limit, however, the fitness of that particular solution is set to zero.</p> <p>I decided the model the probability of successfully reproducing using the hyperbolic tangent function. After each iteration, I calculate the z-score of each solution and I pass that in to the <span class="math-container">\$\tanh x\$</span> function, yielding what seemed to me like pretty decent results. Again, I know nothing about this field, though.</p> <p>I keep track of the extant number of each genome over each iteration, and I use Matplotlib to plot a graph at the end of the genomes which scored higher than an eight on the fitness function (this is pretty arbitrary, but the vast majority of the genomes were massively outdone pretty quickly and became afterthoughts right away, so it helps to not clutter the graph).</p> <p><img src="https://i.imgur.com/MrnmKrY.png" alt="Sample Simulation Output" /></p> <p>I wrote the entire thing as a one-file script, which I know is not ideal, but I was having a blast writing the actual logic. The one change I would make is incorporating <code>configparser</code> and <code>argparse</code> to be able to handle both configuration files and command-line parameters.</p> <p>The simulation can already handle custom configuration parameters, albeit only like four of them, but the mechanism is really clunky.</p> <p>I'm excited to hear about any and all potential improvements, even the aforementioned structural refactoring. If I may request one specific area of focus: you might notice that there are what seem like semi-half-hearted attempts at using generators that look like I just gave up and used lists. I haven't really gotten the opportunity to sit down and internalize generators (not to mention coroutines and their async counterparts), so any feedback on that particular subject is particularly appreciated. This project seems like the perfect place for generator expressions to really shine.</p> <p>Of course, any feedback is always appreciated regardless. Thanks for reading!</p> <pre><code>&quot;&quot;&quot; Knapsack Problem Genetic Algorithm Solver &quot;&quot;&quot; from collections import Counter from dataclasses import dataclass from itertools import chain, combinations, filterfalse, product, repeat from operator import attrgetter from typing import Any, List, Text, TypeVar, Union import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.ticker import MultipleLocator from more_itertools import unique_everseen from numpy.random import default_rng from pandas import DataFrame, Series def z_scores(data: Series) -&gt; Series: return (data - data.mean()) / data.std() @dataclass class Item: weight: float = 0.0 value: float = 0.0 class Solution: def __init__(self, items: List[Item], limit: float, solution: str = None) -&gt; None: self.items = items self.limit = limit self._solution = \ self._generate_random_solution() \ if solution is None else int(solution, base=2) def __str__(self) -&gt; Text: return f&quot;{self._solution:08b}&quot; def __repr__(self) -&gt; Text: return f&quot;Solution({Text(self)})&quot; def _generate_random_solution(self) -&gt; int: global rng solution = 0 for i, _ in enumerate(self.items): if rng.binomial(1, 0.5): solution += (1 &lt;&lt; i) return solution def fitness(self) -&gt; int: return solution_fitness(self._solution, self.limit) def solution_fitness(solution: Text, limit: float) -&gt; float: # The fitness of a particular population group is equal # to the total item value that solution would have # yielded. # # Note that that if a particular solution results in # a weight above the specified limit, the fitness score # for that solution is automatically graded at zero. # fitness = sum( items[i].value if c == &quot;1&quot; else 0 for i, c in enumerate(f&quot;{solution}&quot;)) # Cap the fitness score of a population group based on # whether they were able to make it under the allowable # weight limit. If they weren't, the solution is useless # and the fitness score for that solution is zero. return fitness if fitness &lt;= limit else 0.0 @dataclass class Result: solution: str count: int fitness: float # This is the maximum weight limit that we are able to carry # in this scenario. This is the primary constraint against # all possible solutions will be judged. Any solution which # goes over this limit (by any amount), will be judged an # instant failure. limit = 11.4 # This is the collection from which the solutions will be # picking. The goal is to come up with the maximum value # while still coming in under the maximum weight limit, # is defined above. items = [ Item(weight=7.0, value=5.0), Item(weight=2.0, value=4.0), Item(weight=1.0, value=7.0), Item(weight=9.0, value=2.0), Item(weight=6.0, value=4.0), Item(weight=3.0, value=6.0), Item(weight=4.0, value=5.0), Item(weight=5.0, value=6.0) ] # Define the verbose logging command-line and configuration # variable. verbose_logging = False # Define the number of genetic evolution iterations to # simulate. evolution_iterations = 12 # Define the population size. population_size = 125 # Define the probability of a crossover event occurring. crossover_probability = 0.57 # Define the probability of random genetic mutations. genetic_mutation_probability = 0.018 # Define the natural death rate. This is the rate at which # elements probabilistically die, allowing for weaker # genetic elements to actually die out. natural_death_factor = 0.17 # Initialize the random number generator. rng = default_rng() # Generate the initial simulated population. # # The initial population needs to be randomly generated, but # every successive iteration thereafter should be created # based on the genetic evolution of the previous generation. # population = ( Solution(items, limit) for _ in range(population_size)) # Initialize the population variable. population = list(population) # Setup pandas series array in which the counts over each # iteration will be logged for each of the genomes. series = { str(solution): Series(str(solution)) for solution in population } # Initialize the sentinel value we will use to ensure the # initial counts get logged only once. initial_counts_logged = False # Simulate each successive iteration of population dynamics. for iteration in range(evolution_iterations): if verbose_logging: # Output verbose debugging log indicating that the # simulation is currently entering iteration n. print(f&quot;Iteration {iteration:3d}...\n&quot;) # Create a Counter element to determine the relative # frequency of each possible population element. counter = Counter(str(element) for element in population) # Check whether the first counts have been written to # the pandas series array. If they haven't, go ahead and # do it. if initial_counts_logged == False: # Add the initial iteration's counts to the pandas # series array. for key, val in counter.items(): series[key] = series[key].append(Series(val)) # Make sure not to re-log the counts here again, # since we take care of this at the end of each # iteration, after performing the genetic mutations # and cross-over events. initial_counts_logged = True # Create a list of the results using the counts mapping # in the Counter dictionary. results = [ Result(solution, count, solution_fitness(solution, limit)) for solution, count in counter.items() ] # Sort the results of the current iteration in reverse # order, decreasing from highest fitness to lowest # fitness, then highest count to lowest count, and then # finally using the solution itself for lexicographic # sort order. results = sorted(results, key=attrgetter( &quot;fitness&quot;, &quot;count&quot;, &quot;solution&quot; ), reverse=True) # Create a pandas DataFrame out of the results to make # statistical analysis way easier. result_data = DataFrame(results, copy=False) # Set the probability of successful reproduction for # each solution by normalizing the fitness of all of the # solutions in the result data. # # At the moment, the standard z-score of the fitness # for each solution is calculated (the fitness is # assumed to be Gaussian, although this is absolutely # not the case), and the result is passed to the # hyperbolic tangent function. fitness_z_scores = z_scores(result_data[&quot;fitness&quot;]) # In order to transform the z-scores into reproduction # probabilities, we first add by the absolute value of # all of the z-scores to ensure we have a range from 0.0 # to max z-score times two. Then, we divide all of the # z-scores by two times the maximum z-score, in order to # normalize the values to between 0.0 and 1.0. # # Once this has been completed, we finally conclude by # passing in the normalized values to the hyperbolic # tangent function, which finally gives us the # reproduction probabilities for each group. reproduction_probabilities = \ np.tanh(fitness_z_scores / \ np.max(2.0 * fitness_z_scores)) # Augment the result dataset by adding the reproduction # probabilities that we just calculated to the data # frame. result_data = result_data.assign( reproduction_probability=reproduction_probabilities) # I'm just renaming the reproduction probabilities # series that we calculated above to give it a shorter # name, in order to comply with Python programming # standards. survival_probability = \ result_data[&quot;reproduction_probability&quot;] # Filter out the solutions which have already died out. # # This actually causes Python to crash, although I # haven't taken the time to figure out why, I simply # disabled this step in the meantime. # # result_data = result_data[result_data[&quot;reproduction_probability&quot;] &gt; 0.00] # Calculate the number of extant solution samples per # category as a function of the reproduction probability # and overall population size. population_sizes = \ np.around( (1.0 + survival_probability - natural_death_factor) * result_data[&quot;count&quot;]) # Ensure that no population size drops below zero. population_sizes = \ np.maximum(0.0, population_sizes) # Augment the data frame so we can continue to keep # track of the current population until we are done with # this iteration for sure. result_data = result_data.assign( population_size=population_sizes) # Convert the data types in the data frame to their most # appropriate form. result_data = result_data.convert_dtypes() # Generate population for the next iteration. # # All I'm doing here in these two lines is just creating # variables with shorter names. I'm not too familiar # with pandas yet, so this conversion to a regular list # could probably be done a lot less... badly. solutions = result_data[&quot;solution&quot;].array.to_numpy().tolist() population_sizes = result_data[&quot;population_size&quot;].array.to_numpy().tolist() # Initialize the population variable. population = [ ] # Iterate over the solution and population size to be # able to create the appropriate number of child # elements for the next generation. for solution, size in zip(solutions, population_sizes): # Convert the population size of the given solution # to an actual integer. size = int(size) # Generate the next generation's population. # # TODO: Figure out how to save population as a # generator expression so we don't need to create # the entire list in memory right away. population += [ Solution(items, limit, solution) for _ in range(size) ] # Create pairs of matched up population elements which # will potentially undergo a crossover event. pairings = combinations(population, 2) # Initialize the pairings object from the generator. pairings = list(pairings) for A, B in pairings: # Python strings are immutable, so we represent the # temporary genome sequences as arrays, which later # we'll &quot;&quot;.join(a) and &quot;&quot;.join(b) to come up with # the actual strings. a = [c for c in str(A)] b = [d for d in str(B)] # Simulate genetic mutations within population # element A's genome. for index, mutation in enumerate(rng.binomial(1, genetic_mutation_probability, len(items))): if mutation: a[index] = &quot;0&quot; if a[index] == &quot;1&quot; else &quot;1&quot; # Simulate genetic mutations within population # element B's genome. for index, mutation in enumerate(rng.binomial(1, genetic_mutation_probability, len(items))): if mutation: b[index] = &quot;0&quot; if b[index] == &quot;1&quot; else &quot;1&quot; # Make sure that a and b are not the same, since # otherwise there is literally no point in doing a # crossover event simulation. if &quot;&quot;.join(a) == &quot;&quot;.join(b): # Since both elements are made up of the same # exact genetic components, we might as well # skip this pair. After all, a crossover event # between two identical elements would by # definition be completely unnoticeable. Simply # move on. continue # Now that we know that the two genetic elements are # not identical, we can go ahead and check whether a # cross-over even needs to be carried out. If it # does, we go ahead and do that. for c, d in zip(str(A), str(B)): # We model the chance that a cross-over event # will occur as a Bernoulli random variable with # a probability of 0.57. # # Note, however, that this is the probability of # a single cross-over event occuring. Multiple # cross-over events could occur between two # members of a population, albeit with # significantly lower probability. In this model # we consider cross-over events independent, and # thus the probability of multiple cross-over # events is equal to (0.57)^n, where n is equal # to the number of cross-over events. # # Whether the assumption that cross-over events # can actually be reasonably assumed to be # independent is completely unbeknownst to me. for index, crossover in enumerate(rng.binomial(1, crossover_probability, len(items))): # Perform cross-over event on the current # monomer, which we are metaphorically # representing as a single character that # could either be a zero or a one. if crossover: temp = a[index] a[index] = b[index] b[index] = temp # Replace the solution values with the modified # genome sequences. A = Solution(items, limit, &quot;&quot;.join(a)) B = Solution(items, limit, &quot;&quot;.join(b)) # Add the current counts to the pandas series array. for key, val in counter.items(): series[key] = series[key].append(Series(val)) # Initialize configuration variables. maximum_x_value = None minimum_x_value = 0 maximum_y_value = 1 minimum_y_value = 0 # Initialize the figure. figure, axis = plt.subplots() figure.set_dpi(300.0) figure.set_size_inches(w=8.0, h=6.2) # Configure the axis. axis.axhline(y=0, linewidth=1.5, color=&quot;black&quot;) axis.axvline(x=0, linewidth=1.5, color=&quot;black&quot;) axis.grid(True, which=&quot;major&quot;) # Plot all of the simulation series for which we have data. for key in series.keys(): # Configure the plot data for this series. data = series.get(key).to_list()[1:] # The maximum x value should be the number of iterations # performed. if maximum_x_value is None or maximum_x_value &lt; len(data): maximum_x_value = len(data) # The maximum y value should be set dynamically based # on the values in the plot data. if np.max(data) &gt; maximum_y_value: maximum_y_value = np.max(data) * 1.03 # Don't bother graphing uninteresting genomes. Only # graph the ones that actually made it somewhere, in # this case at least higher than eight. if np.max(data) &lt; 8: # Move on to the next series. continue # Plot the graph. axis.plot(data, label=f&quot;{key}&quot;) # Wrap up last-minute configuration of the graph. axis.set_xlim(left=0, right=maximum_x_value) axis.set_ylim(bottom=0, top=maximum_y_value + 1.02) axis.set_title(&quot;Genetic Algorithm Simulation&quot;) axis.set_xlabel(&quot;Iterations&quot;) axis.set_ylabel(&quot;Population Count&quot;) axis.xaxis.set_major_locator(MultipleLocator(1)) axis.xaxis.set_major_formatter(&quot;{x:.0f}&quot;) axis.yaxis.set_major_locator(MultipleLocator(10)) axis.legend() # Save the image just in case we want to keep it. plt.savefig(&quot;simulation.png&quot;) # Display the image using PyPlot. plt.show() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:31:04.100", "Id": "268376", "Score": "1", "Tags": [ "python", "simulation", "genetic-algorithm", "knapsack-problem" ], "Title": "Solving the Knapsack Problem With a Genetic Algorithm Simulation in Python" }
268376
<p>I recently was asked to upgrade some C++11 code to add a feature by which the user can set a time duration from the command line of the program. The requirement was to have a default time of 1500 ms but to allow it to be overridden by the command line parameters if the parameters are valid; invalid conditions should result in a text message diagnostic, but the program should proceed with the default value. Negative time durations are not valid, so this code negates any value less than zero. The units of time can be ms, s, m, or h for milliseconds, seconds, minutes or hours. The <code>parseDuration</code> code is shown below, along with a simple <code>main</code> to demonstrate its intended use.</p> <pre><code>#include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; std::chrono::milliseconds parseDuration(std::chrono::milliseconds&amp; dur, const std::string&amp; num, const std::string&amp; unit) { static const std::unordered_map&lt;std::string, long&gt; suffix{ {&quot;ms&quot;, 1}, {&quot;s&quot;, 1000}, {&quot;m&quot;, 60*1000}, {&quot;h&quot;, 60*60*1000} }; try { auto n{std::stod(num)}; if (n &lt; 0) { n = -n; } dur = std::chrono::milliseconds{static_cast&lt;unsigned long&gt;(n * suffix.at(unit))}; } catch (const std::invalid_argument&amp; e) { std::cout &lt;&lt; &quot;ERROR: could not convert &quot; &lt;&lt; num &lt;&lt; &quot; to numeric value&quot; &lt;&lt; '\n'; } catch (const std::out_of_range&amp; e) { std::cout &lt;&lt; &quot;ERROR: &quot; &lt;&lt; unit &lt;&lt; &quot; is not one of ms,s,m,h&quot; &lt;&lt; '\n'; } return dur; } int main(int argc, char *argv[]) { if (argc != 3) { std::cerr &lt;&lt; &quot;Usage: duration num ms|s|m|h\n&quot;; return 1; } auto duration{std::chrono::milliseconds{1500}}; parseDuration(duration, argv[1], argv[2]); std::cout &lt;&lt; &quot;That's &quot; &lt;&lt; duration.count() &lt;&lt; '\n'; } </code></pre>
[]
[ { "body": "<p>Looks pretty good; these comments are mainly nitpicking:</p>\n<p>Error messages should be streamed to <code>std::cerr</code>, not <code>std::cout</code>. Whilst that's correctly done in <code>main()</code>, we're using the wrong stream in <code>parseDuration()</code>.</p>\n<p>I'm not a fan of both modifying the <code>dur</code> parameter and returning it. I would go for accepting a default by value and returning the parsed/default value:</p>\n<pre><code>std::chrono::milliseconds parseDuration(const std::string&amp; num, const std::string&amp; unit,\n std::chrono::milliseconds&amp; default_duration)\n</code></pre>\n<p>Then it's easier to use:</p>\n<pre><code>auto duration = parseDuration(argv[1], argv[2], std::chrono::milliseconds{1500});\nstd::cout &lt;&lt; &quot;That's &quot; &lt;&lt; duration.count() &lt;&lt; '\\n';\n</code></pre>\n<p>I would make <code>suffix</code> map strings to <code>double</code> values, which will eliminate a compiler warning when promoting to multiply with <code>n</code>.</p>\n<p>There's no need to name the caught exceptions we don't use.</p>\n<p>Plain map might be more (time/space) efficient than unordered map for this small mapping, though the difference will be very small, probably sub-measurable.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include &lt;chrono&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;unordered_map&gt;\n\nstd::chrono::milliseconds parseDuration(const std::string&amp; num, const std::string&amp; unit,\n const std::chrono::milliseconds&amp; default_duration) {\n static const std::unordered_map&lt;std::string, double&gt; suffix\n { {&quot;ms&quot;, 1},\n {&quot;s&quot;, 1000},\n {&quot;m&quot;, 60*1000},\n {&quot;h&quot;, 60*60*1000} };\n\n try {\n auto n{std::stod(num)};\n if (n &lt; 0) {\n n = -n;\n }\n return std::chrono::milliseconds{static_cast&lt;unsigned long&gt;(n * suffix.at(unit))};\n }\n catch (const std::invalid_argument&amp;) {\n std::cerr &lt;&lt; &quot;ERROR: could not convert &quot; &lt;&lt; num &lt;&lt; &quot; to numeric value\\n&quot;;\n }\n catch (const std::out_of_range&amp;) {\n std::cerr &lt;&lt; &quot;ERROR: &quot; &lt;&lt; unit &lt;&lt; &quot; is not one of ms,s,m,h\\n&quot;;\n }\n return default_duration;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 3) {\n std::cerr &lt;&lt; &quot;Usage: duration num ms|s|m|h\\n&quot;;\n return 1;\n }\n auto duration = parseDuration(argv[1], argv[2], std::chrono::milliseconds{1500});\n std::cout &lt;&lt; &quot;That's &quot; &lt;&lt; duration.count() &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T13:25:05.927", "Id": "268380", "ParentId": "268377", "Score": "6" } }, { "body": "<h1>Avoid defining your own constants</h1>\n<p>There's no need to use your own constants for the duration of a millisecond, second, minute and so on; just use the right <code>std::chrono</code> types:</p>\n<pre><code>static const std::unordered_map&lt;std::string, std::chrono::milliseconds&gt; suffix {\n {&quot;ms&quot;, std::chrono::milliseconds{1}},\n {&quot;s&quot;, std::chrono::seconds{1}},\n {&quot;m&quot;, std::chrono::minutes{1}},\n {&quot;h&quot;, std::chrono::hours{1}},\n};\n</code></pre>\n<p>It's even simpler in C++14 where you can make use of <a href=\"https://en.cppreference.com/w/cpp/symbol_index/chrono_literals\" rel=\"nofollow noreferrer\"><code>std::literals::chrono_literals</code></a>:</p>\n<pre><code>using namespace std::literals::chrono_literals;\n\nstatic const std::unordered_map&lt;std::string, std::chrono::milliseconds&gt; suffix {\n {&quot;ms&quot;, 1ms},\n {&quot;s&quot;, 1s},\n {&quot;m&quot;, 1min},\n {&quot;h&quot;, 1h},\n};\n</code></pre>\n<p>Now that you store the time as a <code>std::chrono::milliseconds</code>, you have to do much less casting, at least if you parse input as an integer instead of a <code>double</code>:</p>\n<pre><code>auto n = std::abs(std::stol(num));\nreturn n * suffix.at(unit);\n</code></pre>\n<p>If you want to support floating point numbers, then you'll have to still cast the result of the multiplication back to milliseconds:</p>\n<pre><code>auto n = std::abs(std::stod(num));\nreturn std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(n * suffix.at(unit));\n</code></pre>\n<h1>Support negative durations</h1>\n<p>I see you try to avoid negative durations, but I don't see why you would want to restrict that. I would just allow negative durations. If the caller wants to ensure it's always a positive number, they can call <code>std::abs()</code> on the result if so desired.</p>\n<h1>Don't <code>catch</code> exceptions if you can't do anything useful</h1>\n<p>You are catching exception, and in the body of the <code>catch</code> statements you log a message to <code>std::cerr</code>. However, afterwards you just return <code>default_duration</code>, and the program will continue as if nothing wrong has happened. Now the caller cannot distinguish between the input not being able to be parsed correctly and someone actually writing &quot;1500 ms&quot;.</p>\n<p>I suggest either not catching the exceptions, and let the caller do that if desired, or if you do want to avoid exceptions leaking out of <code>parseDuration</code>, ideally you would wrap the return type in <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> instead (but that requires C++17 support). The caller could then do:</p>\n<pre><code>auto duration = parseDuration(argv[1], argv[2]).value_or(1500ms);\n</code></pre>\n<p>Note that if the goal is to have a duration of 1500 ms that can be overridden by the command line, what you should write instead is:</p>\n<pre><code>int main(int argc, char *argv[]) {\n auto duration = std::chrono::milliseconds(1500); // default\n\n if (argc == 3) {\n // override specified, try to parse it\n duration = parseDuration(argv[1], argv[2]);\n }\n\n ...\n}\n</code></pre>\n<p>And have <code>parseDuration()</code> throw an exception if the time specified could not be parsed correctly. You can of course still catch the exception and print a nicer error message if so desired.</p>\n<h1>Making it more generic</h1>\n<p>What if you want the result in a higher precision? If you want it in nanoseconds instead, you'd have to modify all the places where you wrote <code>std::chrono::milliseconds</code> before. And what if you want to support multiple duration types? Consider turning it into a template:</p>\n<pre><code>template &lt;typename Duration = std::chrono::milliseconds&gt;\nstd::optional&lt;Duration&gt; parseDuration(const std::string&amp; num, const std::string&amp; unit) {\n using namespace std::literals::chrono_literals;\n static const std::unordered_map&lt;std::string, Duration&gt; suffix {...};\n try {\n ...\n return std::chrono::duration_cast&lt;Duration&gt;(...);\n } catch (const std::exception&amp;) {\n return {};\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T17:55:42.510", "Id": "529263", "Score": "0", "body": "Overall good suggestions, although I don't understand why support for negative durations should be added. What should the expected behaviour be in case of negative durations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T17:57:58.233", "Id": "529264", "Score": "1", "body": "@Mast Just return a negative duration in that case? Negative things can be very useful sometimes. Consider for example that you want a way to sync video frames with audio, and the audio can either be ahead or behind the video, and you want the user to specify a delay to be applied to the audio stream to correct for it. That's when you want to be able to handle both negative and positive durations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T08:43:52.073", "Id": "529290", "Score": "0", "body": "I like the constants idea, but they were introduced in C++14 and this code base is strictly C++11 as I mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T08:48:45.707", "Id": "529291", "Score": "0", "body": "I considered and rejected the use of `std::optional` because that’s C++17 and this is a C++11 code base." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T09:47:06.090", "Id": "529294", "Score": "0", "body": "Fair enough. You can still use the verbose way of writing the constants in C++11, a `using namespace std::chrono` at the top of the function might make it more palatable." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T17:48:44.160", "Id": "268387", "ParentId": "268377", "Score": "6" } } ]
{ "AcceptedAnswerId": "268387", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:42:47.903", "Id": "268377", "Score": "6", "Tags": [ "c++", "c++11", "timer" ], "Title": "Time duration conversion with units" }
268377
<p>The python code simulates an environment of an X number of persons with an Y number of places they can go to, puts the persons randomly in the places and calculates how many persons get infected, die or recover. It mostly work with lists, if you can optimize it in any way, thanks in advance!</p> <pre class="lang-py prettyprint-override"><code>import random import functools from time import perf_counter with open(&quot;results.txt&quot;, &quot;w&quot;) as results: results.seek(0) results.write(&quot;&quot;) results.close() time1 = perf_counter() @functools.lru_cache(maxsize=128) def simulation(): infected, non_infected = 10, 15999990 infectation_chance_c, death_chance, recovery_chance, reinfectation_chance, incubation_time = 1.4, 1 - 0.03, 1 - 0.97, 1 - 1 / 150, 2 death_chance, recovery_chance = death_chance / incubation_time, recovery_chance / incubation_time population_total, population_list = infected + non_infected, non_infected * [0] + infected * [1] place = 120000 day = 1 simulation_duration = 100000000 with open(&quot;results.txt&quot;, &quot;a&quot;) as results: print(&quot;Starting... \nPlease wait for results, this can take lots of time!&quot;) while infected &gt; 0 and simulation_duration &gt; 0: population = population_list.count(0) + population_list.count(-1) + population_list.count(1) healthy = population_list.count(0) + population_list.count(-1) recovered = population_list.count(-1) infected = population_list.count(1) died = population_total - len(population_list) p = {i: [] for i in range(1,place + 1)} results.write(f&quot;Day {day}: Infected: {infected} Healthy: {healthy} p-Imune: {recovered} Alive: {population} Died: {died} \n&quot;) print(f&quot;Day {day}: Infected: {infected} Healthy: {healthy} p-Imune: {recovered} Alive: {population} Died: {died}&quot;) for person in population_list: p[random.randint(1, place)].append(person) i = 0 while i &lt; place: i += 1 p_infected = p[i].count(1) try: infectation_chance = 1 - float(p_infected) / (float(len(p[i])) / infectation_chance_c) except: pass for j, crowd in enumerate(p[i]): if crowd == -1: if random.random() &gt; reinfectation_chance: p[i][j] = 1 elif random.random() &gt; reinfectation_chance: p[i][j] = 0 elif crowd: if random.random() &gt; death_chance: p[i].pop(j) elif random.random() &gt; recovery_chance: if random.random() &gt; 0.4: p[i][j] = -1 else: p[i][j] = 0 elif not crowd: if random.random()&gt;infectation_chance: p[i][j] = 1 i = 0 population_list = [] while i &lt; place: i += 1 population_list.extend(p[i]) simulation_duration -= 1 day += 1 return time1 simulation() print(f&quot;Simulation finishsed... \nProcessing time: {perf_counter()-time1}&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T14:40:21.943", "Id": "529251", "Score": "1", "body": "_persons get infected, die, recover, die_ - so like... zombies?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T15:09:18.373", "Id": "529252", "Score": "0", "body": "@Reinderien Sorry accidentally added one more \"die\", no it's about a virus, people can recover and be sort of immune for a period of time after recovered or die. We are talking about humans" } ]
[ { "body": "<h2>Readability ,Data Types, Potential Bugs</h2>\n<ul>\n<li><p>The code is quite hard to follow. We should break it up into functions and let's add a <code>if __main__==..</code></p>\n</li>\n<li><p>I'm renaming a couple of variable like place to rooms</p>\n</li>\n<li><p>Multiple assignments with such long variables makes it quite hard to read the value for each variable. Furthermore if they're constant for the simulations we can declare them as global constants.</p>\n</li>\n<li><p>I'm not going to be using it later but for future reference : <code>p = {i: [] for i in range(1,place + 1)}</code> can be replaced with a collections.defaultdict</p>\n</li>\n<li><p>Since you're only ever need the number of infected/healthy/recovered individuals and not the actual objects, in your case integers. We could easily replace the representation with something much shorter like a dict:\n<code>population = dict(healthy=n_healthy,infected=n_infected etc..)</code></p>\n</li>\n<li><p>Express the probabilities correctly: <code>deach_chance = 0.97</code> and <code>if random.random &gt; death_chance : he dies</code> means the actual death chance is 0.03</p>\n</li>\n<li><p><strong>BUG</strong> Popping an item by index during a list iteration changes the index for all following iterations don't do it. I'm quite certain this doesn't do what you intended to do for the following iterations:\n<code>if random.random() &gt; death_chance: p[i].pop(j) </code></p>\n</li>\n</ul>\n<h2>The algorithm</h2>\n<h4>The infected and the recovered</h4>\n<p>What happens to the infected and the recovered is independent of the room their in, we can treat all of them in one go. And you don't need to draw random variables for each of them. You can use binomial variables. If you have 100 infected and the death chance is 10% you can simply draw the number of deaths from <code>np.random.binomial(100,0.1)</code>. For both the infected and the recovered we therefore draw from succession of binomial variables and return their new states.</p>\n<h4>The healthy</h4>\n<p>There probably is some mathematical trickery to be done. I'm certain a probability distribution can be found for the number of heathy people who become infected as a function of all the other variables. But I'm too tired to solve the integrals so I simply kept the exact same logic except in numpy. The performance is acceptable IMO.</p>\n<h2>Final code</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom collections import Counter\nimport numpy as np\nfrom time import perf_counter\n\nINCUBATION_TIME = 2\nINFECTION_CHANCE = 1.4\nDEATH_CHANCE = 1 - (1 - 0.03) / INCUBATION_TIME\nRECOVERY_CHANCE = 1 - (1 - 0.97) / INCUBATION_TIME\nREINFECTION_CHANCE = 1 / 150\n\n\ndef simulate_n_infected_people(n):\n dead = np.random.binomial(n, DEATH_CHANCE)\n recovered_and_healty = np.random.binomial(n - dead, RECOVERY_CHANCE)\n healthy = np.random.binomial(recovered_and_healty, 0.4)\n recovered = recovered_and_healty - healthy\n infected = n - dead - recovered_and_healty\n return Counter(healthy=healthy, infected=infected, recovered=recovered)\n\n\ndef simulate_n_recovered_people(n):\n infected = np.random.binomial(n, REINFECTION_CHANCE)\n healthy = np.random.binomial(n - infected, REINFECTION_CHANCE)\n recovered = n - infected - healthy\n return Counter(healthy=healthy, infected=infected, recovered=recovered)\n\n\ndef simulate_n_healthy_people(population, n_rooms):\n rooms_array = np.zeros((n_rooms, 3), dtype=int)\n\n for i, key in enumerate([&quot;infected&quot;, &quot;recovered&quot;, &quot;healthy&quot;]):\n rooms_array[:, i] = np.bincount(\n np.random.randint(0, n_rooms, size=population[key]), minlength=n_rooms\n )\n\n local_infection_chances = (\n rooms_array[:, 0] / np.sum(rooms_array, axis=1) / INFECTION_CHANCE\n )\n infected = np.sum(np.random.binomial(rooms_array[:, 2], local_infection_chances))\n return Counter(\n healthy=population[&quot;healthy&quot;] - infected, infected=infected, recovered=0\n )\n\n\ndef single_day_simulation(population, n_rooms) -&gt; dict:\n next_days_populations = Counter(healthy=0, infected=0, recovered=0)\n\n next_days_populations += simulate_n_infected_people(\n population[&quot;infected&quot;]\n ) # independent from rooms\n next_days_populations += simulate_n_recovered_people(\n population[&quot;recovered&quot;]\n ) # independent from rooms\n next_days_populations += simulate_n_healthy_people(population, n_rooms)\n\n return next_days_populations\n\n\ndef simulation():\n infected, non_infected = 10, 15999990\n population_total = infected + non_infected\n population = Counter(healthy=15999990, infected=10, recovered=0)\n n_rooms = 120000\n day = 1\n simulation_duration = 100000000\n print(&quot;Starting... \\nPlease wait for results, this can take lots of time!&quot;)\n while infected &gt; 0 and day &lt;= simulation_duration:\n alive_population = sum(population.values())\n healthy = population[&quot;healthy&quot;]\n recovered = population[&quot;recovered&quot;]\n infected = population[&quot;infected&quot;]\n total_dead = population_total - alive_population\n print(\n f&quot;Day {day}: Infected: {infected} Healthy: {healthy} p-Imune: {recovered} Alive: {alive_population} Died: {total_dead}&quot;,\n )\n population = single_day_simulation(population, n_rooms)\n day += 1\n return time1\n\n\nif __name__ == &quot;__main__&quot;:\n time1 = perf_counter()\n simulation()\n print(f&quot;Simulation finishsed... \\nProcessing time: {perf_counter()-time1}&quot;)\n\n\n\n\n</code></pre>\n<h4>Speed-up:</h4>\n<ul>\n<li>The original code took about 10 seconds per day, had to kill it.</li>\n<li>The updated code finished running at Day 507, Time : 95s</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:23:54.253", "Id": "531347", "Score": "0", "body": "There seems to be a problem, I sometimes get the following error:\nRuntimeWarning: invalid value encountered in true_divide\nTraceback (most recent call last):\n simulation()\n population = single_day_simulation(population, n_rooms)\n next_days_populations += simulate_n_healthy_people(population, n_rooms)\n infected = np.sum(np.random.binomial(rooms_array[:, 2], local_infection_chances))\n File \"mtrand.pyx\", line 3368, in numpy.random.mtrand.RandomState.binomial\n File \"_common.pyx\", line 338, in numpy.random._common.check_array_constraint\nValueError: p < 0, p > 1 or p contains NaNs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:13:21.023", "Id": "531502", "Score": "0", "body": "The warning is not a problem. As for the error, it's weird that i don't get it, might be a different version you have. You might have to fill nan values in the local_infection_chances array to zeros." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T15:42:23.500", "Id": "269227", "ParentId": "268382", "Score": "2" } } ]
{ "AcceptedAnswerId": "269227", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T14:21:18.197", "Id": "268382", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "simulation", "generator" ], "Title": "The python code simulates an environment of a disease and calculates how many people get infected" }
268382
<p>Please find below my code. Any recommendations/suggestions on how to improve it and make it more readable will be hugely appreciated. I've tried to comment it as much as possible so everyone can understand what my purpose was in every part of the code, but please feel free to ask me for more clarifications.</p> <pre><code># Libraries import pandas as pd from datetime import datetime as dt, time as ti, timedelta as td import io import numpy as np # Custom library with some auxiliary functions import jtp_aux as aux dict_attempts = { 'Agency1': r'/path1/subpath/', 'Agency2': r'/path2/subpath2/', 'Agency3': r'/path3/subpath3/', 'Agency4': r'/path4/subpath4/' } def fetch_attempts(attempts_): # Connect to sftp server via method defined in custom library sftp_ = aux.sftp_connect() # Initialise the dataframe which I will use to concatenate the files read from the sftp server out = [] # Get the files between today at midnight and 1 week ago at midnight today_midnight = dt.combine(dt.today(), ti.min) last_week_midnight = today_midnight - td(days=7) for agency_, path_ in attempts_.items(): for file in sftp_.listdir_attr(path_): mtime = dt.fromtimestamp(file.st_mtime) if (last_week_midnight &lt;= mtime) and (mtime &lt;= today_midnight): with sftp_.open(path_ + file.filename) as fp: logger.info(path_ + file.filename) bytes_p = fp.read() file_obj = io.BytesIO(bytes_p) fp_aux = pd.read_excel( file_obj ) fp_aux.dropna(axis=0, how='all', inplace=True) # Delete the rows with all NaNs as they were causing issues fp_aux.dropna(axis=1, how='all', inplace=True) # Delete the columns with all NaNs as they were causing issues # Need to insert the agency name and the execution date as this info does not appear in the files fp_aux.insert(0, 'AGENCY', agency_) fp_aux.insert(0, 'EXEC_DATE', today_midnight) # Since the files have different column names (although same number of columns) need to standardise the # column names to concatenate the dataframes. fp_aux.set_axis( ['EXEC_DATE', 'AGENCY', 'CALL_DATE', 'CALL_TIME', 'CALL_TYPE', 'CALL_DIRECTION', 'LIVE_FINAL', 'CACONT_ACC', 'PHONE_NUMBER', 'DESCRIPTION', 'CONTACTS', 'ATTEMPTS', 'RPC', 'AGENT', 'DOM_SME' ], axis=1, inplace=True) # If the file is valid, append it out.append(fp_aux) logger.info(path_) # Note: not sure if I should handle here the errors in the files and pass to the following file without # making the program crash. # Concatenate the obtained dataframes into a sigle dataframe df_out = pd.concat(out) # Need to replace the strings 'nan' with actual nulls for inserting the data into a DB df_out = df_out.replace({np.nan: ''}) # The date is provided in string format in the xlsxs so I make sure it's converted to datetime df_out['CALL_DATE'] = pd.to_datetime(df_out['CALL_DATE'], dayfirst=True) # This commented part is one I use to debug the program. If the error happens after this line, I do not want to reexecute the whole # script but save the dataframe in a pickle file so I can take it from here. # df2pickle(df_out, r'output.pckl') # df_out = pickle2df(r'output.pckl') # I need to format this column to 12 digit string with leading 0 if needed. Example: from 1234 to '000000001234' df_out['CACONT_ACC'] = df_out['CACONT_ACC'].map('{:0&gt;12}'.format).astype(str).\ str.slice(0, 11) # These columns need to be numeric so I force them to be so. cols_number = ['CONTACTS', 'ATTEMPTS', 'RPC'] df_out[cols_number] = df_out[cols_number].apply(pd.to_numeric, errors='coerce').\ fillna(0, downcast='infer') # Convert these columns to string. cols_string = ['AGENCY', 'CALL_TIME', 'CALL_TYPE', 'CALL_DIRECTION', 'LIVE_FINAL', 'PHONE_NUMBER', 'DESCRIPTION', 'AGENT', 'DOM_SME'] cols_trunc10 = ['CALL_TYPE', 'CALL_DIRECTION', 'LIVE_FINAL'] cols_trunc50 = ['AGENCY', 'PHONE_NUMBER', 'AGENT', 'DOM_SME'] df_out[cols_string] = df_out[cols_string].astype(str) # Truncate the string fields not to break the DB df_out[cols_trunc10] = df_out[cols_trunc10].astype(str).apply(lambda x: x.str[:10]) df_out[cols_trunc50] = df_out[cols_trunc50].astype(str).apply(lambda x: x.str[:50]) return df_out # Logger path_logger = r'log_attempts.log' logger = aux.init_logger(path_logger) def main(): try: # Read Attempts from sftp server logger.info('START Read Attempts from sftp server') df_attempts = fetch_attempts(dict_attempts) logger.info('END Read Attempts from sftp server') except Exception as e: logger.error(e, exc_info=True) raise e if __name__ == &quot;__main__&quot;: main() </code></pre> <p>EDIT: sample data contained in an excel file in the sftp server.</p> <pre><code>Date Time Type Direction Live_Final AccountID Phone Description Contact Attempt RPC Agent Name DOM_SME 16/09/2021 08:29:13 Inbound Inbound Final 55509110555 55538488555 Description 1 1 0 1 Agent1 DOM 16/09/2021 08:32:22 Inbound Inbound Final 55591795555 Description 2 0 0 0 Agent2 16/09/2021 08:33:10 Inbound Inbound Final 55512508555 55591795555 Description 2 0 0 0 Agent2 16/09/2021 08:35:28 Inbound Inbound Final 55506159555 55532252555 Description 3 1 0 1 Agent2 DOM 16/09/2021 08:36:18 Inbound Inbound Final 55512508555 55591795555 Description 3 1 0 1 Agent3 DOM 16/09/2021 08:37:12 Inbound Inbound Final 55547003555 55525927555 Description 4 1 0 1 Agent3 DOM 16/09/2021 08:51:57 Inbound Inbound Final 55574811555 55568501555 Description 2 0 0 0 Agent2 DOM </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T16:53:08.010", "Id": "529258", "Score": "2", "body": "I understand if you don't want to publish SFTP details for your server here, but short of that, could you post the header and ten or so representative rows from an example excel file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:08:57.713", "Id": "529266", "Score": "1", "body": "@Reinderien I've edited my question with some sample data contained in the excel files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:35:04.170", "Id": "529335", "Score": "0", "body": "@Reinderien kindly let me know if my edit is enough or if you would need some additional data." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T15:46:55.303", "Id": "268385", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Wrangling and reading several xlsx files from sftp server and concatenating them into a single dataframe" }
268385
<p>This is just a practice exercise, I'm trying to understand dynamic programming as deeply as I can. I solved this using recursion, though I am not sure if it will always work. If anyone could tell me a case in which my solution does not work. And I would also appreciate knowing the time/space complexities of this solution. knowing a binary tree is usually <span class="math-container">\$\mathcal{O}(n^2)\$</span>, I believe my solution is <span class="math-container">\$\mathcal{O}(n)\$</span>.</p> <p><strong>AKA. Please tell me how efficient my solution is, if at all. Thanks.</strong></p> <pre><code>class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __repr__(self): if self.left and self.right: return f&quot;({self.value}, {self.left}, {self.right})&quot; if self.left: return f&quot;({self.value}, {self.left})&quot; if self.right: return f&quot;({self.value}, None, {self.right})&quot; return f&quot;({self.value})&quot; map={} def dup_trees(root): if(root.left): print(&quot;left found&quot;) try: if map[root.value]: print(&quot;duplicate Left&quot;) except KeyError: map[root.value]= str(root.value)+','+str(root.left.value) if(root.right): print(&quot;right found&quot;) try: if map[root.value]: print(&quot;duplicate Right&quot;) except KeyError: map[root.value]= str(root.value)+','+str(root.left.value) elif(not root.left and not root.right): print(&quot;no left or right&quot;) try: if map[root.value]: print(&quot;duplicate Leaf&quot;) except KeyError: map[root.value]= str(root.value)+',X' if root.left: dup_trees(root.left) if root.right: dup_trees(root.right) n3_1 = Node(3) n2_1 = Node(2, n3_1) n3_2 = Node(3) n2_2 = Node(2, n3_2) n1 = Node(1, n2_1, n2_2) dup_trees(n1) print(map) # Looks like # 1 # / \ # 2 2 # / / # 3 3 # There are two duplicate trees # # 2 # / # 3 # and just the leaf # 3 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:05:43.643", "Id": "529265", "Score": "0", "body": "There are some obvious errors in your code. In `dup_trees()`, inside the `if(root.right)`, you store `root.left.value` in the map. You also don't correctly handle the case where both left and right children are present, and you only store the immediate values, not the whole subtrees. You should use some larger test cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:24:25.503", "Id": "529267", "Score": "0", "body": "@G.Sliepen I see now, I am only storing the children of each root rather than whole trees. I'll try again" } ]
[ { "body": "<p>First off, for pure data, I've been getting into using dataclasses for my values. This will take care of doing that <code>__repr__</code> method and the constructor for you. Even better, if you can use a frozen dataclass, then it can also be used as a key in a dictionary, because it is safely hashable.</p>\n<p>Using these tools, all you will need to do is count the unique instances of each node. You can use the <code>Counter</code> class or a simple <code>defaultdict</code> to do this. To find the nodes without recursion, you can use a queue.</p>\n<pre><code>import dataclasses\nfrom collections import defaultdict\nfrom typing import Optional\n\n\n@dataclasses.dataclass(frozen=True)\nclass Node:\n value: int\n left: Optional[&quot;Node&quot;] = None\n right: Optional[&quot;Node&quot;] = None\n\n\ndef find_node_counts(node):\n node_counts = defaultdict(int)\n search_queue = [node]\n while search_queue:\n # Allow safely adding None values to the queue\n if curr_node := search_queue.pop():\n search_queue.append(curr_node.left)\n search_queue.append(curr_node.right)\n # Because its frozen, and has a deterministic hash\n # this will increment matching nodes correctly\n node_counts[curr_node] += 1\n\n return node_counts\n</code></pre>\n<p>Finding any duplicates is just checking if there any nodes with counts greater than 1.</p>\n<pre><code>n3_1 = Node(3)\nn2_1 = Node(2, n3_1)\nn3_2 = Node(3)\nn2_2 = Node(2, n3_2)\nn1 = Node(1, n2_1, n2_2)\n\nnode_counts = find_node_counts(n1)\nfor node, count in node_counts.items():\n if count &gt; 1:\n print(f&quot;Tree {node} appears {count} times&quot;)\n</code></pre>\n<pre><code>Tree Node(value=2, left=Node(value=3, left=None, right=None), right=None) appears 2 times\nTree Node(value=3, left=None, right=None) appears 2 times\n</code></pre>\n<hr />\n<p>Note: If you want the tree to still be mutable, then you can do:</p>\n<pre><code>@dataclasses.dataclass(unsafe_hash=True)\nclass Node:\n value: int\n left: Optional[&quot;Node&quot;] = None\n right: Optional[&quot;Node&quot;] = None\n</code></pre>\n<p>As a warning, if you do this then you need to make sure that you reconstruct any dictionaries relying the nodes any time you mutate part of the tree. This is because the underlying hash will change if you mutate the tree and you will get unexpected results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:59:36.217", "Id": "529276", "Score": "0", "body": "Slightly embarrassingly, this is my first time hearing of dataclasses. I see now that searching and logging counts of each tree's occurrence is much cleaner. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T19:39:04.153", "Id": "268390", "ParentId": "268388", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T18:23:39.507", "Id": "268388", "Score": "2", "Tags": [ "python", "recursion", "tree", "dynamic-programming", "binary-tree" ], "Title": "Find ALL duplicate subtrees. using recursion" }
268388
<p>Gave myself the challenge of solving the Gilded Rose with pure functions in C#. All one-line lambdas, all static, all the time. The original kata assumed the code would mutate the given array-- I've opted not to, for better or for worse. Let me know what you think!</p> <p>Linking to the GitHub repo since I broke the code out into several files and directories:</p> <p><a href="https://github.com/nedredmond/GildedRoseFunctional" rel="nofollow noreferrer"><strong>You can see my code and the problem statement here.</strong></a></p> <p>Here's the meat of my code, to be compliant with the paragraph on the right sidebar, though the full thing is at the link above:</p> <pre><code>public static partial class ItemExtensions { public static Item Update(this Item item) =&gt; item.AdjustQuality() .ConstrainQuality() .DecrementSellIn(); private static Item AdjustQuality(this Item item) =&gt; ItemUtils.GetRuleOrDefault(item, Rules.Quality.AdjustmentRules, ItemUtils.Quality.Adjust); private static Item ConstrainQuality(this Item item) =&gt; ItemUtils.GetRuleOrDefault(item, Rules.Quality.ConstraintRules, ItemUtils.Quality.Constrain); private static Item DecrementSellIn(this Item item) =&gt; ItemUtils.GetRuleOrDefault(item, Rules.SellIn.DecrementRules, ItemUtils.SellIn.Decrement); public static Item Clone(this Item item, ItemProps? props) =&gt; new() { Name = item.Name, Quality = props?.Quality ?? item.Quality, SellIn = props?.SellIn ?? item.SellIn }; public static Item Clone(this Item item) =&gt; item.Clone(null); } public static partial class ItemUtils { public static Item GetRuleOrDefault( Item item, Dictionary&lt;string, Func&lt;Item, Item&gt;&gt; rules, Func&lt;Item, Item&gt; defaultRule ) =&gt; GetRule(item, rules) is string rule ? rules[rule](item) : defaultRule(item); private static string GetRule(Item item, Dictionary&lt;string, Func&lt;Item, Item&gt;&gt; rules) =&gt; rules.Keys.FirstOrDefault(item.Name.Contains); public static class Quality { public static Item Adjust(Item item, int amount) =&gt; item.Clone(new ItemProps { Quality = item.Quality + amount * GetAdjustmentFactor(item) }); public static Item Adjust(Item item) =&gt; Adjust(item, -1); private static int GetAdjustmentFactor(Item item) =&gt; Rules.Quality.AdjustmentFactors .Where(f =&gt; f(item)) .Aggregate(1, (current, _) =&gt; current * 2); } } public static class Rules { public static class Quality { public static readonly List&lt;Predicate&lt;Item&gt;&gt; AdjustmentFactors = new() { item =&gt; item.SellIn &lt;= 0, Conjured.AdjustmentFactor }; public static readonly Dictionary&lt;string, Func&lt;Item, Item&gt;&gt; AdjustmentRules = new() { {Sulfuras.Name, Sulfuras.TheOneRuleOfRagnaros}, {BackstagePasses.Name, BackstagePasses.Adjust}, {AgedBrie.Name, AgedBrie.Adjust} } ; public static readonly Dictionary&lt;string, Func&lt;Item,Item&gt;&gt; ConstraintRules = new() { {Sulfuras.Name, Sulfuras.TheOneRuleOfRagnaros} }; public enum Constraints { Lower = 0, Upper = 50 } } public static class SellIn { public static readonly Dictionary&lt;string, Func&lt;Item, Item&gt;&gt; DecrementRules = new() { {Sulfuras.Name, Sulfuras.TheOneRuleOfRagnaros} }; } } public static class BackstagePasses { public static string Name =&gt; &quot;Backstage passes to a TAFKAL80ETC concert&quot;; public static Item Adjust(Item item) =&gt; ItemUtils.Quality.Adjust(item, GetAdjustmentAmount(item)); private static int GetAdjustmentAmount(Item item) =&gt; item.SellIn switch { &lt;= 0 =&gt; -item.Quality, &lt;= 5 =&gt; 3, &lt;= 10 =&gt; 2, _ =&gt; 1 }; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T20:51:23.793", "Id": "268393", "Score": "0", "Tags": [ "c#", "functional-programming", "asp.net-core" ], "Title": "Gilded Rose with pure functions in C#" }
268393
<p>I'm trying to implement a recursive+momoize version for <a href="https://leetcode.com/problems/dungeon-game/" rel="nofollow noreferrer">leetcode's dungeon game</a> question.</p> <p>I tried to use <code>@lru_cache()</code>:</p> <pre><code>________________________________________________________ Executed in 14.22 secs fish external usr time 14.13 secs 101.00 micros 14.13 secs sys time 0.04 secs 498.00 micros 0.04 secs </code></pre> <p>And comment it to make it unavailable:</p> <pre><code>________________________________________________________ Executed in 11.73 secs fish external usr time 11.65 secs 123.00 micros 11.65 secs sys time 0.04 secs 556.00 micros 0.04 secs </code></pre> <p>It sounds a lot like the <code>lru_cache</code> won't help in this case, just wondering if anything that I'd missed?</p> <pre class="lang-py prettyprint-override"><code>from typing import List from functools import lru_cache class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -&gt; int: height = len(dungeon) width = len(dungeon[0]) @lru_cache() def helper(start_x, start_y, acc, min): cur = dungeon[start_y][start_x] acc = cur + acc if cur &lt; 0 and acc &lt; min: min = acc if start_x == width - 1 and start_y == height - 1: return min if start_x &lt; width - 1: right_res = helper(start_x+1, start_y, acc, min) else: right_res = float(&quot;-inf&quot;) if start_y &lt; height - 1: down_res = helper(start_x, start_y+1, acc, min) else: down_res = float(&quot;-inf&quot;) ret = max(down_res, right_res) return ret res = helper(0,0,0,0) return 1 if res &gt; 0 else abs(res)+1 def main(): sol = Solution() long_case = [[2,-8,-79,-88,-12,-87,-5,-56,-55,-42,18,-91,1,-30,-36,42,-96,-26,-17,-69,38,18,44,-58,-33,20,-45,-11,11,15,-40,-92,-62,-51,-23,20,-86,-2,-90,-64,-100,-42,-16,-55,29,-62,-81,-60,7,-5,31,-7,40,19,-53,-81,-77,42,-87,37,-43,37,-50,-21,-86,-28,13,-18,-65,-76], [-67,-23,-62,45,-94,-1,-95,-66,-41,37,33,-96,-95,-17,12,30,-4,40,-40,-89,-89,-25,-62,10,-19,-53,-36,38,-21,1,-41,-81,-62,3,-96,-17,-75,-81,37,32,-9,-80,-41,-13,-58,1,40,-13,-85,-78,-67,-36,-7,48,-16,2,-69,-85,9,15,-91,-32,-16,-84,-9,-31,-62,35,-11,28], [39,-28,1,-31,-4,-39,-64,-86,-68,-72,-68,21,-33,-73,37,-39,2,-59,-71,-17,-60,4,-16,-92,-15,10,-99,-37,21,-70,31,-10,-9,-45,6,26,8,30,13,-72,5,37,-94,35,9,36,-96,47,-61,15,-22,-60,-96,-94,-60,43,-48,-79,19,24,-40,33,-18,-33,50,42,-42,-6,-59,-17], [-95,-40,-96,42,-49,-3,6,-47,-38,31,-25,-61,-18,-52,-80,-55,29,27,22,6,29,-89,-9,14,-77,-26,-2,-7,-2,-64,-100,40,-52,-15,-76,13,-27,-83,-70,13,-62,-54,-92,-71,-65,-18,26,37,0,-58,4,43,-5,-33,-47,-21,-65,-58,21,2,-67,-62,-32,30,-4,-46,18,21,2,-5], [-5,34,41,11,45,-46,-86,31,-57,42,-92,43,-37,-9,42,-29,-3,41,-71,13,-8,37,-36,23,17,-74,-12,-55,-18,-17,-13,-76,-18,-90,-5,14,7,-82,-19,-16,44,-96,-88,37,-98,8,17,9,-2,-29,11,-39,-49,-95,20,-33,-37,-42,42,26,-28,-21,-44,-9,17,-26,-27,24,-60,-19]] print(sol.calculateMinimumHP(long_case)) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T03:58:41.067", "Id": "529286", "Score": "0", "body": "This sort of problems would best be solved using a game-tree traversing algorithm such as minimax." } ]
[ { "body": "<p>With your example input, the function <code>helper</code> gets called with <code>400568</code> different parameters. According to its <a href=\"https://docs.python.org/3/library/functools.html\" rel=\"nofollow noreferrer\">documentation</a> <code>lru_cache</code> by default caches the parameters and results of the last <code>128</code> function calls.</p>\n<p>Try setting <code>maxsize</code> to something more reasonable, or use a non-lru cache (<code>@lru_cache(maxsize=None)</code>, or simply <code>@cache</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T17:16:45.603", "Id": "529315", "Score": "2", "body": "Notice, that `@cache` is only avaliable since Python 3.9." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T16:48:52.017", "Id": "268406", "ParentId": "268396", "Score": "2" } } ]
{ "AcceptedAnswerId": "268406", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T03:22:24.093", "Id": "268396", "Score": "2", "Tags": [ "python", "performance", "algorithm", "cache" ], "Title": "Python: lru_cache make leetcode's dungeon game more slower" }
268396
<p>Recently, I had to write a code to classify and rename lots of image files based on their content. So, I wrote a Python script which displays all those images as a slideshow to the me, and I can classify and rename them with one button click, instead of renaming every file manually.</p> <p>The directory structure looks like this:</p> <pre><code> ---rootDir +--dir1 | +--subDir | +--imgx1.png | +--imgx2.png | | +--dir2 | +--subDir | +--imgy1.png | +--imgy2.png | | </code></pre> <p>This is the script I wrote, and it is working correctly.</p> <pre><code>import util # local config file import os from tkinter import Tk, Canvas, Event from PIL import Image, ImageTk os.chdir(util.rootPath) def iterateImage(): global dirIter, imgIter global currDir, currImg try: currImg = next(imgIter) except StopIteration: try: currDir = next(dirIter) except StopIteration: exit() imgIter = iter(os.listdir(currDir)) iterateImage() return if not currImg.endswith('.png'): iterateImage() return def showImage(): global im iterateImage() im = ImageTk.PhotoImage(Image.open(fr'{currDir}\{currImg}')) canvas.delete('all') canvas.create_image(400, 400, anchor='center', image=im) root.title(currImg) root.update() def onKeyEvent(event:Event): if event.keysym == 'n': emo = 'neutral' elif event.keysym == 'h': emo = 'happy' elif event.keysym == 's': emo = 'sad' elif event.keysym == 'a': emo = 'angry' elif event.keysym == 'q': showImage() return else: return newName = fr'pic_{currDir}_{emo}.png' try: os.rename(fr'{currDir}\{currImg}', fr'{currDir}\{newName}') except FileExistsError as e: print('File Already Exists:', e.filename, e.filename2) showImage() def initSlideShow(): global root, canvas global dirIter, imgIter root = Tk() canvas = Canvas(root, width=800, height=800) canvas.pack() dirIter = iter(util.dirList) imgIter = iter(()) showImage() root.bind_all('&lt;KeyRelease&gt;', onKeyEvent) root.mainloop() currDir:str currImg:str print('As soon as you continue, you will be shown list of pictures.') print('Classify them accordingly into emotion categories.') print('n -&gt; Neutral') print('h -&gt; Happy') print('s -&gt; Sad') print('a -&gt; Angry') print('q -&gt; SKIP') print('Press ENTER to start slideshow') input() print('NOTE: In some cases you may have to manually bring the slideshow window into focus.') print() initSlideShow() </code></pre> <p>But I feel this is harder to maintain than it should be. So, is it possible to modify and restructure this code using async-await feature of Python to make it more managable? In particular, is it possible to write the above as this:</p> <pre><code>import util # local config file import os from tkinter import Tk, Canvas, Event from PIL import Image, ImageTk os.chdir(util.rootPath) async def slideShow(): global im, renamed global currDir, currImg for currDir in util.dirList: for currImg in os.listdir(currDir): if not currImg.endswith('.png'): continue im = ImageTk.PhotoImage(Image.open(fr'{currDir}\{currImg}')) canvas.delete('all') canvas.create_image(400, 400, anchor='center', image=im) root.title(currImg) root.update() renamed = False await ... # till renamed becomes True def onKeyEvent(event:Event): global renamed if event.keysym == 'n': emo = 'neutral' elif event.keysym == 'h': emo = 'happy' elif event.keysym == 's': emo = 'sad' elif event.keysym == 'a': emo = 'angry' elif event.keysym == 'q': renamed = True return else: return newName = fr'pic_{currDir}_{emo}.png' try: os.rename(fr'{currDir}\{currImg}', fr'{currDir}\{newName}') except FileExistsError as e: print('File Already Exists:', e.filename, e.filename2) renamed = True def initSlideShow(): global root, canvas root = Tk() canvas = Canvas(root, width=800, height=800) canvas.pack() root.bind_all('&lt;KeyRelease&gt;', onKeyEvent) slideShow() root.mainloop() print('As soon as you continue, you will be shown list of pictures.') print('Classify them accordingly into emotion categories.') print('n -&gt; Neutral') print('h -&gt; Happy') print('s -&gt; Sad') print('a -&gt; Angry') print('q -&gt; SKIP') print('Press ENTER to start slideshow') input() print('NOTE: In some cases you may have to manually bring the slideshow window into focus.') print() initSlideShow() </code></pre> <p>Mainly two things I want to change:<br /> <em>I manually handling iterators</em> vs <em>For loop handling iterators for me</em>.<br /> <em>Calling showImage function after every rename</em> vs <em>Calling slideShow function only once and it itself resuming after every rename</em>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T07:32:24.520", "Id": "268398", "Score": "1", "Tags": [ "python", "async-await", "tkinter" ], "Title": "Event handling with async await in Python" }
268398
<p>I have written following code for the this C++ Problem:</p> <p>Write a program to add only odd numbers between one to ten.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int num = 1, n = 0; int odd_num; while(num &lt;= 10) { if(num % 2 != 0) { odd_num = num; odd_num += n; n = odd_num; } num++; } cout&lt;&lt;&quot;Sum = &quot;&lt;&lt;odd_num; return 0; } </code></pre> <p>Please tell how I can improve this code .</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T18:20:38.200", "Id": "529399", "Score": "3", "body": "`odd_num` is a lousy name (if you'd used 8 instead of 10, `odd_num` would end up being 16, which is odd (strange) to call odd (not even)). Better would be `running_sum`." } ]
[ { "body": "<p><code>using namespace std;</code> is a poor practice and can be harmful, so it's good to rid yourself of that habit early on.</p>\n<p>The loop's structure is</p>\n<blockquote>\n<pre><code>int num = 1;\nwhile(num &lt;= 10)\n{\n ⋮\n num++;\n}\n</code></pre>\n</blockquote>\n<p>That is more familiar to C++ programmers as a <code>for</code> loop:</p>\n<pre><code>for (int num = 1; num &lt;= 10; ++num) {\n ⋮\n}\n</code></pre>\n<p><code>odd_num</code> shouldn't be necessary; it seems to be a temporary store for our total <code>n</code>, but we could just replace the three lines in the <code>if</code> with a simple <code>n += num</code>.</p>\n<p>Instead of incrementing by 1 each iteration, then testing whether we have a multiple of 2, we can avoid the test if we increment by 2 each iteration.</p>\n<p>Prefer short names for short-lived variables (e.g. loop counter) and longer, more descriptive names for variables with larger scope (e.g. our running total).</p>\n<p>When we print the output, it's usual to write a whole line (ending in a newline character):</p>\n<pre><code>std::cout &lt;&lt; &quot;Sum = &quot; &lt;&lt; odd_num &lt;&lt; '\\n';\n</code></pre>\n<p>We are allowed to omit <code>return 0;</code> from <code>main()</code> (though not from any other function).</p>\n<p>It may be useful to define a variable for the range of numbers we're considering (we might want to make that a program argument in future).</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include &lt;iostream&gt;\n\nconstexpr int limit = 10;\n\nint main()\n{\n int total = 0;\n for (int n = 1; n &lt;= limit; n += 2) {\n total += n;\n }\n std::cout &lt;&lt; &quot;Sum = &quot; &lt;&lt; total &lt;&lt; '\\n';\n}\n</code></pre>\n<hr />\n<h1>Closed-form solution</h1>\n<p>Some simple mathematics could allow us to determine the sum algebraicly, without using a loop. In real code, we would prefer the closed form (with suitable comment), but this seems to be practice code where the objective is to improve your loop logic, so I'm not proposing that right now.</p>\n<p>However, if you do want to follow this idea, it's fairly simple. Consider that we have 1 + 3 + ... + 7 + 9. If we pair 1 with 9, we get 10, or 5 + 5, giving us 5 + 3 + ... + 7 + 5; now pair 3 with 7, and so on, giving us 5 + 5 + ... + 5 + 5. We just need to work out how many 5s to multiply. See if you can work out a general formula to calculate this sum for any range of odd integers.</p>\n<p>Hint: we'll probably want make the range exact (e.g. by rounding the start and end to both be odd numbers) before applying a general formula.</p>\n<hr />\n<h1>Testing</h1>\n<p>A good way to approach the closed-form solution is to split the program, to create a function that can be independently tested. That would look like this:</p>\n<pre><code>int sum_of_odd_numbers(int min, int max)\n{\n ⋮\n}\n</code></pre>\n<p>We can then test it with different values. The simplest way is with asserts in <code>main()</code>; alternatively, use one of the available unit-test libraries to get better diagnostics from failing tests (and lots of other useful features).</p>\n<p>Here's values I tested with:</p>\n<pre><code>#include &lt;cassert&gt;\n\nint main()\n{\n // range 1-10 (from question)\n assert(sum_of_odd_numbers(1, 10) == 25);\n assert(sum_of_odd_numbers(0, 10) == 25);\n assert(sum_of_odd_numbers(0, 9) == 25);\n\n // trivial ranges\n assert(sum_of_odd_numbers(0, 0) == 0);\n assert(sum_of_odd_numbers(2, 2) == 0);\n assert(sum_of_odd_numbers(1, 1) == 1);\n assert(sum_of_odd_numbers(-1, -1) == -1);\n assert(sum_of_odd_numbers(3, 3) == 3);\n\n // simple ranges\n assert(sum_of_odd_numbers(0, 3) == 4);\n assert(sum_of_odd_numbers(3, 5) == 8);\n assert(sum_of_odd_numbers(-1, 1) == 0);\n assert(sum_of_odd_numbers(-3, -1) == -4);\n assert(sum_of_odd_numbers(-3, 1) == -3);\n}\n</code></pre>\n<p>And the closed-form calculation:</p>\n<pre><code>int sum_of_odd_numbers(int min, int max)\n{\n // N.B. we assume the arithmetic doesn't overflow\n if (min % 2 == 0) {\n ++min;\n }\n if (max % 2 == 0) {\n --max;\n }\n return (max + min) * (max - min + 2) / 4;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T13:35:00.727", "Id": "529301", "Score": "0", "body": "Thank you for reviewing . Can you explain why ```using namespace std``` is a wrong habit. Also why you have used ```constexper``` ? I'm not familiar to ```constexpr```." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T13:44:53.677", "Id": "529302", "Score": "0", "body": "[Why is \"using namespace std;\" considered bad practice?](//stackoverflow.com/q/1452721/4850040). `constexpr` is pretty much like `const` here, but it's a little stronger and allows us to use the variable for things that need to be *compile-time constant expressions* such as array dimensions. `const` would be fine for this program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T13:48:22.010", "Id": "529303", "Score": "0", "body": "okay thanks @Toby Speight . Also I'll try to solve the question you gave me of 5s to calculate sum of odd number upto any range." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T21:23:16.143", "Id": "529324", "Score": "0", "body": "Actually, `const` has the same effect as `constexpr` there. But better write what is meant instead of needlessly depending on some obscure rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T22:37:37.287", "Id": "529326", "Score": "0", "body": "@Toby Speight when should you use `static` along with `constexpr`, are there hard rules?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T22:39:50.253", "Id": "529327", "Score": "2", "body": "The last hint is likely to complicate the life of anyone that isn't familiar with bit twiddling, the compiler will convert the more understandable `(n/2)*2` and `(n/2)*2+1` to the bit functions itself, see https://godbolt.org/z/rcYnxfh44 ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:53:23.653", "Id": "529336", "Score": "0", "body": "Good point @12345ieee. The intent of the hint was more that we'll need to adjust the endpoints before the arithmetic (which I haven't worked out, but should be straightforward if you know how to derive Σi = ½n(n+1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:18:28.523", "Id": "529388", "Score": "3", "body": "An intermediary step between \"run a loop and test if `num` is odd at every step\" and \"calculate the sum algebraically\" could be \"run a loop, but increment 2 by 2 so you only see odd numbers\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T20:06:28.417", "Id": "529404", "Score": "1", "body": "@12345ieee: But note you had to use `unsigned int` for that optimization to be legal because C signed division rounds rounding towards 0 instead of -infinity. This code is using signed `int`, making the range possibly include negative numbers, and the compiler has to make asm that works for any input. You'd get wrong answers like `up_to_odd(-3) == -1`. If you'd used a right shift (on a C++ implementation where that's an arithmetic right shift), you'd be ok and compilers can optimize. https://godbolt.org/z/zs6E7nTnc. `n | 1` or `n &= -2` do work for this for 2's complement implementations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T06:58:00.513", "Id": "529427", "Score": "0", "body": "@stef - absolutely: I intended to mention that but forgot. Luckily, that suggestion is in [Ch3steR's review](/a/268408/75307)." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T13:23:44.177", "Id": "268402", "ParentId": "268401", "Score": "22" } }, { "body": "<h2>Using <a href=\"https://en.cppreference.com/w/cpp/language/using_declaration#In_namespace_and_block_scope\" rel=\"nofollow noreferrer\"><code>using</code></a> to bring function to into scope.</h2>\n<p>Like already mentioned by <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">@Toby Speight</a> <code>using namespace std;</code> is a bad habit. With <code>using</code> you can bring only <code>std::cout</code> into the scope.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n\nint main(){\n using std::cout;\n cout &lt;&lt; &quot;...&quot;; // Fine to use as we brought std::cout to main function's scope.\n // Not polluting the global scope.\n}\n</code></pre>\n<h2><a href=\"https://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators\" rel=\"nofollow noreferrer\">Bitwise <code>&amp;</code></a> the number with 1</h2>\n<p><s>Every odd number has the <a href=\"https://en.wikipedia.org/wiki/Bit_numbering#Least_significant_bit\" rel=\"nofollow noreferrer\">LSB</a> set to 1. To check if a bit is set bitwise <code>&amp;</code> with 1. If the result is 1 then the bit is set. If the bit is not set the result is 0.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: right;\">Decimal</th>\n<th style=\"text-align: left;\">Binary</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: right;\">1</td>\n<td style=\"text-align: left;\">0b1</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\">3</td>\n<td style=\"text-align: left;\">0b11</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\">5</td>\n<td style=\"text-align: left;\">0b101</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\">7</td>\n<td style=\"text-align: left;\">0b111</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\">9</td>\n<td style=\"text-align: left;\">0b1001</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre><code>#include &lt;cstddef&gt; // for size_t\nfor(size_t i=1; i &lt; 10; ++i){\n if (i&amp;1) total += i;\n}\n</code></pre>\n</s>\n<blockquote>\n<p>The bitwise trick seems like an unnecessary and premature optimization. Any decent compiler will optimize it to a bitwise AND on its own. num % 2 == 1 is more intuitive than num &amp; 1 - <a href=\"https://codereview.stackexchange.com/users/194215/rish\">Rish</a></p>\n</blockquote>\n<h2>Increment loop by 2</h2>\n<p>We all know odd and even numbers alternate with each other.</p>\n<pre><code>int total = 0\nfor(size_t i=1; i &lt; 10; i = i+2){\n // i -&gt; is always odd\n total += i;\n}\n</code></pre>\n<h2>Math based approach</h2>\n<p>Sum of <span class=\"math-container\">\\$N\\$</span> odd numbers(<code>1+3+5+7...</code>):\n<span class=\"math-container\">$$\\sum_{k=0}^N (2k+1) = N^2$$</span></p>\n<p>You need to find how many odd numbers are there between 1 to 10. You can generalize this approach to find the number of odd numbers b/w the range <code>[1, L]</code> using the logic that odd and even number alternate with each other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T20:49:24.687", "Id": "529323", "Score": "7", "body": "The bitwise trick seems like an unnecessary and premature optimization. Any decent compiler will optimize it to a bitwise AND on its own. `num % 2 == 1` is more intuitive than `num & 1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T04:04:37.583", "Id": "529329", "Score": "0", "body": "@Rish Yes, makes sense thank you. I'll strike that part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:55:21.417", "Id": "529337", "Score": "2", "body": "Agh - I meant to suggest changing the loop increment to 2, then completely forgot to mention it! I'm glad you wrote that suggestion, to close the hole." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:21:57.880", "Id": "529363", "Score": "0", "body": "@TobySpeight Thank you :) Your review is great as ever. Learning something new every day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:23:05.367", "Id": "529390", "Score": "1", "body": "I suggest parentheses in your math formula. `\\sum_{k=0}^N (2k+1)` and `(\\sum_{k=0}^N 2k)+1` are not the same quantities." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:55:36.253", "Id": "529394", "Score": "2", "body": "@Rish: `num % 2` is negative for negative integers, so the actual expression you want is `num % 2 != 0` like the question is using. `num % 2 == 1` on signed `int` requires the compiler to care about the sign bit as well. [What is the fastest way to find if a number is even or odd?](https://stackoverflow.com/q/2229107) Of course if you don't generalize this function like Blindman67's answer did, the compiler can prove that `num` will be non-negative and can optimize to just a bitwise test. But in general as a habit, write odd/even tests as `num % 2 !=0` unless you *want* to reject negative" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T17:41:17.013", "Id": "268408", "ParentId": "268401", "Score": "4" } }, { "body": "<h2>Use functions</h2>\n<p>Always define the task as functions (method) to make the code portable and give it more semantic meaning via the functions name.</p>\n<p>If you define the task as a function keep roles separate. The task of summing odd values should not display the result, it only returns the sum.</p>\n<p>If the task is to display the sum of odd values between 1 and 10 then you would not need any calculations as the value is a constant 25. So rather redefine the task to sum odd value between any two integers.</p>\n<h2>While loops</h2>\n<p>There is nothing wrong with using <code>while</code> loops. Many times while loops require less code making the code more readable and easier to maintain.</p>\n<h2>Example</h2>\n<p>The function <code>SumOdd</code> returns an <code>int</code> that is the sum of odd values between <code>min</code> and <code>max</code> inclusive.</p>\n<pre><code>#include &lt;iostream&gt;\n\nint SumOdd(int min, int max) {\n int val = min + ((abs(min) + 1) % 2); // start at closest odd &gt;= min\n int sum = 0; \n while (val &lt;= max) {\n sum += val;\n val += 2;\n }\n return sum;\n}\n\nint main() {\n std::cout &lt;&lt; &quot;Sum = &quot; &lt;&lt; SumOdd(-3, 10) &lt;&lt; std::endl;\n return 0;\n}\n\n</code></pre>\n<p>however this has some serious problems / limits...</p>\n<ul>\n<li>The sum can be greater than 32bit int can hold. Max sum between any two 32bit integers is ~1.2 quintillion, well above the max value for a 32 bit int.</li>\n<li>When the difference between <code>min</code> and <code>max</code> is very large it will take a long time to complete (at worst ~2.1 billion iterations)</li>\n</ul>\n<h2>Use a 64bit int</h2>\n<p>To fix the first problem we can make the sum a 64 bit int <code>long long</code></p>\n<h2>Don't brute force it</h2>\n<p>To fix the second is a little more complicated as the value is an int which can have a sign. The formula <span class=\"math-container\">\\$((1+n)/2)^2\\$</span> to sum odd values doe not work if some values are negative. Nor does it work if the we start summing above 1.</p>\n<p>To get the sum between any two values we need to calculate the sum from 0 to max and to min, and then sum those values correctly setting the sign depending on the sign of input arguments.</p>\n<p>Thus we get</p>\n<pre><code>long long SumOdd(int min, int max) { \n long long halfMax, halfMin;\n if (max &lt; min || max == -min) { return 0; }\n if (max == min) { return abs(min % 2) == 1 ? (long long) min : 0; } \n if (min &lt; 0) {\n halfMin = (long long) ((1 - min) / 2);\n halfMax = (long long) (max &lt; 0 ? (1 - max) / 2 : (1 + max) / 2);\n return -halfMin * halfMin + halfMax * halfMax;\n }\n halfMin = (long long) ((1 + min) / 2);\n halfMax = (long long) ((1 + max) / 2);\n return halfMax * halfMax - halfMin * halfMin;\n}\n</code></pre>\n<p><strong>Note</strong> that <code>long long</code> defines a signed (<em>at least</em>) 64 bit int. The <code>int</code> is automatically added to make <code>long long int</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:41:03.447", "Id": "529391", "Score": "0", "body": "Surprised you didn't discuss how your code optimizes away the `if` inside the loop by incrementing by 2. That's a good general thing to look for, iterating over interesting values rather than iterating everything and checking with an if. I guess it kind of speaks for itself in the simplicity, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:44:56.837", "Id": "529392", "Score": "0", "body": "Toby's answer points out that `n | 1` rounds upwards to the next odd number. For negative numbers, this works for 2's complement (e.g. consider setting the low bit in -2 to make -1). And I guess also sign/magnitude, but not 1's complement. However, modern ISO C++ is planning to drop support for non-2's-complement implementations. So it's at least worth mentioning, since the `(abs + 1) % 2` way is harder to think through and verify correct. But it doesn't depend on binary number representations, just arithmetic operations. However, abs has signed-overflow UB on INT_MIN." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:50:48.810", "Id": "529393", "Score": "0", "body": "Fun fact: clang can optimize the loop safely into closed-form asm. Oh, but not with the start and end both variable, it seems. https://godbolt.org/z/P193f1YM1. (Also included a `min|1` version to show it compiles nicely.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T06:33:08.557", "Id": "529422", "Score": "0", "body": "@Blindman67 I have not learnt abt functions in C++ yet. But thanks your answer is very informative." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T19:09:38.063", "Id": "268410", "ParentId": "268401", "Score": "8" } }, { "body": "<p>Maybe you could increment <code>n</code> by 2 instead of 1 to reduce the number of cycles when you get the first odd value. I know it may sound stupid and overengineered but your code was already fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:50:57.943", "Id": "529351", "Score": "0", "body": "Just curious, did you read the other answers on this question? There were a couple of problems in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:48:16.707", "Id": "529383", "Score": "1", "body": "The other answers already include this suggestion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:25:35.053", "Id": "268420", "ParentId": "268401", "Score": "0" } }, { "body": "<p>Using namespaces imports the said namespace globally into your code file, in this case you are importing the standard library.</p>\n<p>Let's say you have another custom namespace providing a function <code>cout</code> what will happen then.</p>\n<p><em><strong>Namespace Collision</strong></em></p>\n<p>Here your code will be confused on which function it can call, hence it will call them both leaving you with unwanted results.</p>\n<p>Also, the statement <code>std::cout</code> adds clarity to your code as here you are aware that the <code>cout</code> belongs to the standard library.</p>\n<h1><strong>For the answer to your question...</strong></h1>\n<p>Yes, your code can be shorter using these 2 ways:\n(PS: Both of them use mathematics)</p>\n<p>Here <code>limit</code> variable essentially asks, how many odd numbers you want to add? If you say 10 then it means add first 10 odd numbers not the odd numbers till 10...</p>\n<p><strong>First approach</strong></p>\n<pre><code>#include &lt;iostream&gt;\n\n/*\n * This method uses the formula (2 x n + 1) with a sign modification.\n * There n denotes the odd number at nth place and n = 0, 1, 2...\n * eg: if n = 2 then the odd number is 5 and sum till n is 9\n */\n\nint main(){\n int limit = 10, oddSum = 0;\n \n // Here you set a limit... i.e: The value of n\n // Notice we are subtracting one from the limit\n // Hence the value of n or limit ranges from 1, 2, 3, 4.....\n /*\n * limit &lt;&lt; 1 is a right shift operation which is an efficient way \n * of saying limit * 2, as right shift operation multiplies the \n * number given by 2\n */\n\n for(limit = limit; limit &gt; 0; limit--)\n oddSum += (limit &lt;&lt; 1) - 1;\n \n // Wola! You are done now print the sum\n // Yes, mathematics is important in coding\n\n std::cout &lt;&lt; oddSum &lt;&lt; std::endl;\n}\n</code></pre>\n<p><strong>Second approach</strong></p>\n<p>Here pow is a function in math.h</p>\n<p>It will raise the limit i.e n to the said exponent</p>\n<p>Please don't use it for squares, I added it so that you might learn a useful function.</p>\n<p>pow(value, exponent)... Fancy way of saying n<sup>2</sup></p>\n<pre><code>#include &lt;iostream&gt;\n\n#include &lt;math.h&gt;\n\n/*\n * Using mathematics we can always see that the sum of n odd numbers\n * is the square of itself... \n * This result makes the problem very simple\n */\n\nint main(){\n int limit = 10, oddSum = pow(limit, 2);\n\n // Boom! You are done now print the sum\n\n std::cout &lt;&lt; oddSum &lt;&lt; std::endl\n}\n</code></pre>\n<h2><strong>Approach without mathematics</strong></h2>\n<p><strong>First Approach</strong></p>\n<pre><code>#include &lt;iostream&gt;\n\nint main(){\n int limit, oddNumber = 1, oddSum = 0;\n\n for (limit = 10; limit &gt; 0; limit-- &amp;&amp; (oddNumber = oddNumber + 2))\n oddSum += oddNumber;\n\n std::cout &lt;&lt; oddSum &lt;&lt; std::endl;\n \n}\n</code></pre>\n<p><strong>Second Approach</strong></p>\n<p>Here <code>limit</code> means add all odd numbers till the number <code>limit</code>. If <code>limit = 10</code> then add 1, 3, 5, 7, 9...</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main(){\n int limit, oddSum = 0;\n\n for (limit = 10; limit &gt; 0; limit--)\n oddSum = (limit % 2 != 0) ? (oddSum + limit): oddSum;\n\n std::cout &lt;&lt; oddSum &lt;&lt; std::endl;\n}\n</code></pre>\n<p><strong>Third Approach</strong></p>\n<p>Here the meaning of <code>limit</code> is same as the previous approach...</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main(){\n int limit = 10, oddNumber, oddSum = 0;\n\n for (oddNumber = 1; oddNumber &lt;= limit; oddNumber = oddNumber + 2)\n oddSum += oddNumber;\n\n std::cout &lt;&lt; oddSum &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Increasing the variable range from <code>int</code> to <code>long</code> or <code>long long</code> will increase the number of values you can calculate... No need to overkill such a simple problem with methods. Its like bringing machine guns to a knife fight.</p>\n<p>Ohh! And please don't use <code>std::endl</code> on every line... It flushes out the buffer which is an expensive call. Use it at the end or if performance is necessary don't use it at all.</p>\n<h2><strong>Edit:</strong></h2>\n<p>I had some free time from my own personal projects, college projects and assignments. Therefore, I went over your problem of odd sums...</p>\n<p>If you have read this answer thoroughly, then you might wonder.. Why do the last 2 solutions change the definition of the variable <code>limit</code>?</p>\n<p>I wanted to give you and comments a simplified solution using loops and the initial approach of people when solving this problem. There are many complicated ways in which you can solve this problem, for example add in hash maps and mem sets, you will find some very different codes in either cases.</p>\n<p>This means you can even use dynamic programming and backtracking on such a simple problem... Why? Just so that you can calculate values larger than what <code>long long</code> can hold, while also calculating their sum. Then again as I said, this will be similar to killing an ant with 100 ballistic missiles.</p>\n<p>You might wonder why have I approached this problem using simple and concise codes? It is because of time complexity... Here in all the solutions not only including my answers but other as well, the solution which uses another overkill function <code>pow</code> will run the fastest for any values that fit under <code>long long</code>.</p>\n<p>Then how do I solve, when the definition of the variable <code>limit</code> changes for the last 2 approaches in my answer?</p>\n<h2>There is another efficient way using maths...</h2>\n<p>The odd numbers is a series values from 1 to infinity...</p>\n<p>That is: 1, 3, 5, 7, 9, 11, 13.... and so on.</p>\n<p>You know that using the formula 2*n - 1 you can find any odd number at any given position in the series... Here n ranges from 1 to infinity.</p>\n<p>That is, n can be any number in this series: 1, 2, 3, 4, 5, 6... infinity.</p>\n<p>Using mathematics again you can find the position (n) of any given odd number, if you do so then you simply square the position (n) of it to obtain the sum of odd number till the given odd number. Thus also answering the problem of finding a better way to solve for the last 2 approaches.</p>\n<p>Enough blabbering here is the code:</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n int limit = 10, n = 0, oddSum = 0;\n \n // Check if the given limit is even if yes then subtract 1 to make it odd\n\n limit = (limit % 2 == 0) ? limit - 1: limit;\n \n // Now calculate the position (n)\n \n n = (limit + 1) / 2;\n\n // Now calculate the sum\n\n oddSum = n * n;\n\n // Print the sum\n\n std::cout &lt;&lt; &quot;The sum of odd numbers is &quot; &lt;&lt; oddSum\n\n // No std::endl here and the time complexity should be O(1) if I am correct\n\n // This will net you say for limit = 10 the oddSum will be 25\n \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:27:53.383", "Id": "529666", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/130161/discussion-on-answer-by-neopentene-adding-odd-numbers-in-c)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T09:23:31.017", "Id": "268423", "ParentId": "268401", "Score": "-2" } }, { "body": "<p>Create a single <code>Sum</code> function that can accept any kind of predicate. If you want to find the sum of all odd elements, pass <code>IsOdd</code> function to it as follows.</p>\n<pre><code>Sum(&amp;IsOdd, data)\n</code></pre>\n<p>where <code>data</code> is a vector of <code>int</code>.</p>\n<p>For more details, see the complete code below.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;cmath&gt;\n\n\ntypedef bool (*Predicate)(int);\n\nint Sum(Predicate f, std::vector&lt;int&gt; data)\n{\n size_t N = data.size();\n int sum = 0;\n for (int i = 0; i &lt; N; ++i)\n if (f(data[i]))\n sum += data[i];\n return sum;\n}\n\nbool IsOdd(int x)\n{\n return x % 2 == 1;\n}\n\nbool IsEven(int x)\n{\n return x % 2 == 0;\n}\n\nbool IsPrime(int x)\n{\n if (x &lt; 2)\n return false;\n if (x == 2)\n return true;\n if (x % 2 == 0)\n return false;\n\n int N = (int)std::sqrt(x);\n for (int i = 2; i &lt; N; i = i + 2)\n if (x % (i + 1) == 0)\n return false;\n\n return true;\n}\n\nint main()\n{\n std::vector&lt;int&gt; data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 49};\n std::cout &lt;&lt; &quot;The total sum of prime elements: &quot; &lt;&lt; Sum(&amp;IsPrime, data) &lt;&lt; &quot;\\n&quot;;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T07:47:52.590", "Id": "268464", "ParentId": "268401", "Score": "0" } } ]
{ "AcceptedAnswerId": "268402", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T12:21:38.710", "Id": "268401", "Score": "5", "Tags": [ "c++" ], "Title": "Adding Odd numbers in C++" }
268401
<p>My goal is to safely consume an API without getting <code>429 Too Many Requests</code> error, activating DDoS protection or going over system limit of maximum open file descriptors. To achieve that I wrote this simple wrapper around <code>http.Client</code> using worker pool pattern:</p> <pre><code>package client import ( &quot;errors&quot; &quot;net/http&quot; &quot;time&quot; ) type job struct { req *http.Request respc chan *http.Response errc chan error } type client chan job func NewClient( HTTPClient *http.Client, MaxRequestsPerSecond float64, MaxParallelConnections int, ) (*client, error) { if MaxRequestsPerSecond &lt;= 0 { return nil, errors.New( &quot;client.NewClient: invalid MaxRequestsPerSecond&quot;, ) } if MaxParallelConnections &lt;= 0 { return nil, errors.New( &quot;client.NewClient: invalid MaxParallelConnections&quot;, ) } tasks := make(chan job) go func() { jobs := make(chan job) defer close(jobs) for i := 0; i &lt; MaxParallelConnections; i++ { go func() { for j := range jobs { resp, err := HTTPClient.Do(j.req) if err != nil { j.errc &lt;- err continue } j.respc &lt;- resp } }() } for task := range tasks { jobs &lt;- task time.Sleep( time.Duration( float64(time.Second) / MaxRequestsPerSecond, ), ) } }() return (*client)(&amp;tasks), nil } func (c *client) Close() { close(*c) } func (c *client) Do(req *http.Request) (*http.Response, error) { respc := make(chan *http.Response) errc := make(chan error) *c &lt;- job{req, respc, errc} select { case resp := &lt;- respc: return resp, nil case err := &lt;- errc: return nil, err } } </code></pre> <p>I already see comments like &quot;export X to separate function&quot; coming, but please make them more detailed.</p> <ul> <li><p>Should I make the channels buffered? If so, how big should they be, or should the consumer provide the size?</p> </li> <li><p>Should I make <code>MaxParallelConnections</code> <code>uint</code> and ditch the corresponding check?</p> </li> <li><p>Could the problem be solved with a different approach altogether?</p> </li> </ul> <p>I am pretty new to Go, so any and all additional input is very welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T15:19:20.910", "Id": "268404", "Score": "1", "Tags": [ "web-scraping", "go", "concurrency", "connection-pool" ], "Title": "golang http.Client wrapper with rate and concurrency limiting" }
268404
<p>I have recently learned Merge Sort algorithm in C++ with 2 ways of writing it.</p> <p>1st Way:</p> <pre><code> void merge(int arr[],int low,int mid,int high){ const int n1=(mid-low+1); const int n2=(high-mid); int*a=new int[n1],*b=new int[n2];//dynamically allocated because of MSVC compiler for(int i=0;i&lt;n1;i++) a[i]=arr[low+i]; for(int i=0;i&lt;n2;i++) b[i]=arr[mid+1+i]; int i=0,j=0,k=low; while(i&lt;n1 &amp;&amp; j&lt;n2){ if(a[i]&lt;b[j]){ arr[k]=a[i]; i++; }else{ arr[k]=b[j]; j++; } k++; } while(i&lt;n1){ arr[k]=a[i]; k++,i++; } while(j&lt;n2){ arr[k]=b[j]; k++,j++; } delete[]a; delete[]b; } void mergeSort(int arr[],int start,int end){ if(start&lt;end){ int mid=(start+end)/2; mergeSort(arr,start,mid); mergeSort(arr,mid+1,end); merge(arr,start,mid,end); } } int main(){ int arr[]={9,14,4,8,6,7,5,2,1}; unsigned size=sizeof(arr)/sizeof(arr[0]); printArray(arr,size); mergeSort(arr,0,size-1); printArray(arr,size); return 0; } </code></pre> <p>2nd Way:</p> <pre><code> void merge(int arr[],int temp[],int low,int mid,int high){ //passed temp array from the beginning int i=low,k=low,j=mid+1; while(i&lt;=mid &amp;&amp; j&lt;=high){ if(arr[i]&lt;arr[j]){ temp[k]=arr[i]; i++; }else{ temp[k]=arr[j]; j++; } k++; } while(i&lt;=mid){ temp[k]=arr[i]; k++,i++; } while(j&lt;=high){ temp[k]=arr[j]; k++,j++; } for(int i=low;i&lt;=high;i++) arr[i]=temp[i]; } void mergeSort(int arr[],int temp[],int start,int end){ if(start&lt;end){ int mid=(start+end)/2; mergeSort(arr,temp,start,mid); mergeSort(arr,temp,mid+1,end); merge(arr,temp,start,mid,end); } } int main(){ int arr[]={9,14,4,8,6,7,5,2,1}; unsigned size=sizeof(arr)/sizeof(arr[0]); int*buffer=new int[size]; printArray(arr,size); mergeSort(arr,buffer,0,size-1); printArray(arr,size); delete[]buffer; return 0; } </code></pre> <p>Edited:</p> <p><code>printArray</code> method:</p> <pre><code>void printArray(int arr[],int n){ for(int i=0;i&lt;n;i++) printf(&quot;%d &quot;,arr[i]); printf(&quot;\n&quot;); } </code></pre> <p>I tried out both the methods on LeetCode exercise- <code>Sort an Array</code>, here the 1st method gave less runtime than the 2nd. Which way of writing the merge function is better and more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T16:10:30.077", "Id": "529307", "Score": "0", "body": "`printArray()` seems to be undefined." } ]
[ { "body": "<p>I haven't got time to do this comprehensively but here is a start...</p>\n<p>Which method is better must be decided by what is important to you.</p>\n<p>Both methods are <em>recursive</em>. The pro's and con's of that are worth reading up about. At its heart <em>recursion</em> hammers the <em>call stack</em> (which is usually very limited in size relative to <em>heap memory</em>) and can cause programs to crash after a fairly modest number of recursive calls.</p>\n<p>The first method dynamically allocates memory inside <code>merge()</code>. This impacts the cost in memory terms but (taking your word for it - see the remark on how to measure below) gives it the speed advantage.</p>\n<p>The second method works &quot;in place&quot;, making its use of memory more efficient at the expense of speed.</p>\n<p>The analysis of algorithms is a big topic on its own. Read up on the basics of Big O notation <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">Big O Notation</a>. You will probably find that assessing your algorithms for both speed and memory in relation to the number of elements being sorted will answer your own question.</p>\n<p>What should be important to you in choosing? If the arrays you need to sort can become large then space efficiency (stability under load) should probably be the dominant consideration (but then I'd also spend time on getting rid of the recursion).</p>\n<p>How should you measure? Start here: <a href=\"https://en.wikipedia.org/wiki/Benchmark_(computing)\" rel=\"nofollow noreferrer\">Benchmarking</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:39:24.317", "Id": "268434", "ParentId": "268405", "Score": "0" } }, { "body": "<p><code>void merge(int arr[],int low,int mid,int high)</code><br />\nThat's not normal C++, for two reasons. First, <code>int arr[]</code> is actually a pointer and is discouraged from writing it this way. Second, you should be using <strong>iterators</strong> rather than an &quot;array&quot; and index values.</p>\n<hr />\n<pre><code>const int n1=(mid-low+1);\nconst int n2=(high-mid);\nint*a=new int[n1],*b=new int[n2];//dynamically allocated because of MSVC compiler\n</code></pre>\n<p>What do you mean &quot;because of MSVC compiler&quot;? If you expected to write a C-style VLA, that's not allowed in C++. <code>n1</code> and <code>n2</code> are not compile-time constants but merely run-time local variables that happen to be constant once initialized.</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new\" rel=\"nofollow noreferrer\">⧺C.149</a> — no naked <code>new</code> or <code>delete</code>.</p>\n<p>Use <code>std::vector</code> for this.</p>\n<hr />\n<pre><code>for(int i=0;i&lt;n1;i++)\n a[i]=arr[low+i];\nfor(int i=0;i&lt;n2;i++)\n b[i]=arr[mid+1+i];\n</code></pre>\n<p>I think you want <code>std::copy_n</code> here. Don't write loops — <em>use algorithms</em>. Same with other half of the function which copies the two parts into <code>temp</code> or <code>arr</code>.</p>\n<pre><code> unsigned size=sizeof(arr)/sizeof(arr[0]);\n</code></pre>\n<p>Don't do that. use <code>std::size(arr)</code> to get that value. But ideally you don't need that value; you'll be using <code>begin</code> and <code>end</code> instead.</p>\n<hr />\n<p>See also the answers to similar code<br />\n<a href=\"https://codereview.stackexchange.com/questions/264301/parallezing-merge-step-and-divide-step-in-mergesort-algorithm-with-openmp/264323#264323\">Parallezing merge step and divide step in mergesort algorithm with OpenMP</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:18:58.660", "Id": "268444", "ParentId": "268405", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T15:25:03.393", "Id": "268405", "Score": "1", "Tags": [ "c++", "comparative-review", "mergesort" ], "Title": "Comparison of 2 different ways of writing Merge Sort Algorithm" }
268405
<p>In work I was asked to fix a bug which involved me making changes in a class. To fix the bug I needed to add a collection of a class that looks like this.</p> <pre><code>public class Branch { public int StartNode { get; set; } public int EndNode { get; set; } } </code></pre> <p>The collection</p> <pre><code>List&lt;Branch&gt; _vistedBranch = new List&lt;Branch&gt;(); </code></pre> <p>My concern is I was always taught to hate seeing &quot;new&quot; in any of my classes as it tightly couples my class to other classes. However this class is just a POCO class that doesn't have any functionality. I am just using it in the class I am working on to store a collection of start nodes and end nodes.</p> <p>This is how I have used it in the class</p> <pre><code>public class CustomerCountRequestProcessor : ICustomerCountRequestProcessor { List&lt;Branch&gt; _vistedBranch = new List&lt;Branch&gt;(); private INetwork _network; public CustomerCountRequestProcessor(INetwork network) { _network = network ?? throw new ArgumentNullException(nameof(network)); } public int GetCustomersForSelectedNode(IRoot request) { if (request == null) throw new ArgumentNullException(nameof(request)); _network = request.Network; return ProcessSelectedNode(request.SelectedNode); } private int ProcessSelectedNode(int node) { var nc = _network.Customers.FirstOrDefault(c =&gt; c.Node == node); var customersForNode = nc != null ? nc.NumberOfCustomers : 0; foreach (var subNode in _network.Branches.Where(b =&gt; b.StartNode == node)) { bool has = _vistedBranch.Any(b =&gt; b.StartNode == subNode.StartNode &amp;&amp; b.EndNode == subNode.EndNode); if (has) { throw new ArgumentNullException(nameof(node)); } _vistedBranch.Add(new Branch() { StartNode = subNode.StartNode, EndNode = subNode.EndNode }); customersForNode += ProcessSelectedNode(subNode.EndNode); } return customersForNode; } } </code></pre> <p>1.Do I make a class out of the collection. Then make an interface out of the class then bring it in using dependency injection?</p> <p>2.Do I make a factory class, stick that collection in there and then new up the factory when I need the class? These options above seem a lot of code for one simple POCO class. Maybe its just as simple as putting the new part into the constructor like this.</p> <pre><code>List&lt;Branch&gt; _vistedBranch; private INetwork _network; public CustomerCountRequestProcessor(INetwork network) { _vistedBranch = new List&lt;Branch&gt;(); _network = network ?? throw new ArgumentNullException(nameof(network)); } </code></pre> <p>How do I do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T22:18:02.090", "Id": "529325", "Score": "0", "body": "I think that KISS applies in this scenario. `_visitedBranch` is not a public-facing property, and is used in one place purely for validation. Writing more code to try and hide the `new` keyword in this instance is counter-productive, especially since it's a simple POCO. I'd go as far to say that if `Branch` is only ever used in that class, make it a Tuple to remove the need for that class entirely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:24:29.720", "Id": "529333", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:17:48.827", "Id": "529342", "Score": "0", "body": "@user16405900 Why do want to have Dependency Injection or Factory method? What would be your gain then? What is your main concern that you want to address with these techniques?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T09:13:28.897", "Id": "529346", "Score": "0", "body": "My main concern is stated in the question, whats the best way to refactor a POCO class. I discuss Dependency Injection and Factory's because I am newing up classes in another class and when you do that they come into the conversation. So if you understand why people use DI and factories then you understand what the gain is. I guess if I want to extend the the functionality of my POCO class or Test and Moq the POCO class then I would need DI or Factory. But as this POCO class will never be used in anyother way than to collect data in this class then I can just leave as is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T09:48:23.173", "Id": "529347", "Score": "0", "body": "@user16405900 *what's the best way to refactor a POCO class* Refactoring is not a concern, it is a tool. Testability might be a concern, Independent deployability, reuse or responsibility segregation might be a concern. DI and Factory methods are common solutions to address the above problems. Maybe if I rephrase my question it might help: What is the problem with your current solution that you want to address?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:32:20.650", "Id": "529364", "Score": "0", "body": "Ok to be clear. My concern as a relatively new developer is I am told to hate seeing the keyword new in classes. So I guess I am asking you should I be concerned with what I have done. Or am I maintaining clean coding principles. So when you look at that Code is it clean and how you would have done it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:12:56.920", "Id": "529371", "Score": "0", "body": "@user16405900 `new` should be avoided if you are dealing with dependencies. `ClassA` should not be responsible for `ClassB`'s life-cycle. The best way to avoid to is to delegate this to a separate component, like DI. In your case `_visitedBranch` is not a dependency, it is an implementation detail from your class's consumer point of view. So, it is not a problem to use here `new`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T05:21:12.280", "Id": "529567", "Score": "0", "body": "Thank you for your help. Makes sense" } ]
[ { "body": "<blockquote>\n<p>Do I make a class out of the collection</p>\n</blockquote>\n<p>You did - <code>List&lt;Branch&gt;</code>, but it is not being used. Everywhere <code>_vistedBranch</code> (spelling?) is iterated something like <code>_vistedBranch.Find(&lt;expression&gt;)</code>, <code>Contains(item)</code>, etc. could be used.</p>\n<p>MS recommends NOT inheriting <code>List&lt;T&gt;:</code> but encapsulation is better anyway:</p>\n<pre><code>public class Branches {\n public List&lt;Branch&gt; _branches { get; protected set; }\n \n public Branches { _branches = new List&lt;Branch&gt;(); }\n \n public bool Add ( Branch newBranch ) {\n if ( newBranch == null ) return false;\n if ( _branches.Contains( newBranch ) return false;\n _branches.Add( newBranch );\n return true;\n }\n</code></pre>\n<p>The collection itself controls what is allowed or not. Keeps the coder (<code>Branch</code>'s client code) from screwing up or screwing around with the extensive <code>List</code> functionality.</p>\n<hr />\n<blockquote>\n<p>Do I make a factory class</p>\n</blockquote>\n<p>No. A properly implemented <code>Branches</code> class is inherently reusable and flexible.</p>\n<hr />\n<blockquote>\n<p>Then make an interface out of the class</p>\n</blockquote>\n<p>No. How many differently-functioning <code>List&lt;Branches&gt;</code> are needed. Or, more to the purpose of <code>interface</code>, what non-<code>List&lt;Branch&gt;</code> objects need that functionality? I suspect that <code>List</code> methods (see above) with their parameterized (injectable) expressions makes an <code>interface</code> moot.</p>\n<hr />\n<blockquote>\n<p>bring it in using dependency injection</p>\n</blockquote>\n<p>Yes. But all the collection functionality has to be taken oout of <code>CustomerCountRequestProcessor</code> first.</p>\n<hr />\n<p><strong>Implement <code>IEquatable</code> and <code>IComparable</code> in <code>Branch</code> ?</strong></p>\n<p>This code makes me wonder:</p>\n<pre><code>Any(b =&gt; b.StartNode == subNode.StartNode\n &amp;&amp; b.EndNode == subNode.EndNode)\n \n</code></pre>\n<p>That is easily replaced by <code>_vistedBranch.Contains(otherBranch)</code> for example <strong>if <code>Branch</code> had identity equality</strong>.</p>\n<blockquote>\n<p>hate seeing &quot;new&quot; in any of my classes as it tightly couples my class to other classes.</p>\n</blockquote>\n<p><code>CustomerCountRequestProcessor</code> is the collection for all practical purposes. The coupling is not in <code>new</code> but the collection functionaly usurped by <code>CustomerCountRequestProcessor</code>. Instantiating the internal reference makes a lot of sense if an empty collection is a valid use case or valid initial state.</p>\n<p><code>Branches.Add()</code> (above) works the very first time because the internal collection is empty, not null. Thus empty &amp; not-empty collections are treated the same without special <code>null</code> handling code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T05:53:14.450", "Id": "529331", "Score": "0", "body": "Thanks for this. But I feel my question hasnt been answered or maybe I dont understand. As now I am back to square one. If I implement your Branches class into my CustomerCountRequestProcessor, I have to use the new keyword like this new Branches();. Should I do that or should I bring it in using dependency injection and in order to do dependency injection I will need to make the Branches class an Interface?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T21:17:47.073", "Id": "529408", "Score": "0", "body": "That \"no new\" heuristic is nonsense. Any other-class reference is coupling, that's how software works. Passing in a collection is coupling. Extreme decoupling is one \"god\" class - the opposite of good software structure, OO or not. **It is a design issue of composition vs aggregation**: [here](https://medium.com/swlh/aggregation-vs-composition-in-object-oriented-programming-3fa4fd471a9f) ... [here](https://softwareengineering.stackexchange.com/q/61376/38663) and [here](https://softwareengineering.stackexchange.com/a/200487/38663)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T21:34:22.123", "Id": "529409", "Score": "0", "body": "`new` up a collection in `CustomerCountRequestProcessor` if you want aggregation, pass in a collection if you want composition. That is independent of `Branches` implementation/functionality. Using internal collection object reference will be exactly the same either way. If `CCRP` will ever have only one collection and might want to control access and contents then use aggregation. The collection must be instantiated *somewhere*, if not this class then some other class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T05:20:50.970", "Id": "529566", "Score": "0", "body": "Thank you for your help. Makes sense" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T04:07:53.027", "Id": "268417", "ParentId": "268409", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T19:07:57.577", "Id": "268409", "Score": "0", "Tags": [ "c#", ".net" ], "Title": "Whats the best way to refactor a POCO class" }
268409
<p>I code in Rust, but one doesn't need to be familiar with Rust to understand the question.</p> <p>We are given the two vectors, <em>first</em> and <em>res</em>. Our goal is to append <em>res</em> to <em>first</em>, and then to assign the result to <em>res</em>.</p> <p>Let's consider the following two approaches. The first one is</p> <pre class="lang-rust prettyprint-override"><code>first.extend(res); res = first; </code></pre> <p>The second one is</p> <pre class="lang-rust prettyprint-override"><code>res = first.into_iter().chain(res.into_iter()).collect(); </code></pre> <p>The former seems to be more readable, but the latter is somewhat more straightforward: &quot;take <em>first</em>, turn it into the iterator, chain it with the iterator obtained from consuming <em>res</em>, then collect the result&quot;. Also, there is only one line of code instead of two.</p> <p>I would prefer the first one. What do you think?</p>
[]
[ { "body": "<p>Actually, you want:</p>\n<pre><code>res = [first, rest].concat(); // require your type to be cloneable\n</code></pre>\n<p>Or:</p>\n<pre><code>res.splice(0..0, first);\n</code></pre>\n<p>Or:</p>\n<pre><code>res = vec![first, rest].into_iter().flatten().collect();\n</code></pre>\n<p>But it seems odd that you are assembling the <code>Vec</code> this way. Usually we try to assemble it from beginning to end. I'd look to see if there is a better way to structure to code to avoid this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:02:19.983", "Id": "529332", "Score": "0", "body": "Unfortunately, when I try using `res = [first, res].concat();` a compiler tells me that \"the trait `Clone` is not implemented\", but `splice` looks like what is needed. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:05:57.827", "Id": "529378", "Score": "0", "body": "@memoryallocator, hmm.., the concat method doesn't seem to require cloneability, so I'm not sure why it didn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T19:16:09.520", "Id": "529400", "Score": "0", "body": "As I understand, that's because `[first, res]` requires cloneability. `vec![first, res]` works, though, but I would like to avoid the unnecessary construction of a vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T23:09:42.327", "Id": "529411", "Score": "0", "body": "@memoryallocator, `vec!` doesn't work when I test it. It looks to me like `concat` does actually require `Clone`, although its it a bit roundabout since it goes through an unstable `Concat` trait." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T05:01:23.427", "Id": "268418", "ParentId": "268411", "Score": "0" } } ]
{ "AcceptedAnswerId": "268418", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T20:42:43.700", "Id": "268411", "Score": "0", "Tags": [ "rust" ], "Title": "Concatenate two vectors and store the result" }
268411
<p>I wrote this bash script to try to make sure save games don't get mixed between different steam users using the same Ubuntu account.</p> <p>It uses inotify to try to figure out when a user changes and a soft link to point to the correct folder.</p> <pre><code>#!/bin/bash link_name=~/.factorio check_username=$(awk -F'&quot;' '/AutoLoginUser/{print $4}' ~/.steam/registry.vdf) function check_link_username { local link_from=$1 local username=$2 if [[ -L ${link_from} ]] then if [[ &quot;${link_from}&quot; -ef &quot;${link_from}_${username}&quot; ]] then return 0 fi if [[ -d ${link_from} ]] then mkdir -p &quot;${link_from}_${username}&quot; elif [[ ! -f &quot;${link_from}_${username}&quot; ]] then cp &quot;${link_from}&quot; &quot;${link_from}_${username}&quot; fi rm ${link_from} else echo mv &quot;${link_from}&quot; &quot;${link_from}_${username}&quot; mv &quot;${link_from}&quot; &quot;${link_from}_${username}&quot; fi ln -s &quot;${link_from}_${username}&quot; &quot;${link_from}&quot; } check_link_username &quot;$link_name&quot; &quot;$check_username&quot; while inotifywait -qqe delete_self -e modify ~/.steam/registry.vdf || true do if newcheck=$(awk -F'&quot;' '/AutoLoginUser/{print $4}' ~/.steam/registry.vdf) then if [[ ! &quot;${newcheck}&quot; = &quot;${check_username}&quot; ]] then check_username=&quot;${newcheck}&quot; echo new user:${check_username} check_link_username &quot;$link_name&quot; &quot;$check_username&quot; fi fi done </code></pre> <p>When trying to figure out which inotify events to watch for I monitored the parent folder:</p> <pre><code>~$ inotifywait --monitor --timefmt '%T' --format '%T %e %f' ~/.steam/| grep registry.vdf Setting up watches. Watches established. 19:55:34 OPEN registry.vdf 19:55:34 ACCESS registry.vdf 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:34 CREATE registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 MODIFY registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 CLOSE_WRITE,CLOSE registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534 19:55:34 MOVED_TO registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_FROM registry.vdf 19:55:34 MOVED_TO registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_TO registry.vdf 19:55:34 DELETE registry.vdf20210926195534 19:55:34 CREATE registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 MODIFY registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 OPEN registry.vdf 19:55:34 ACCESS registry.vdf 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 CLOSE_WRITE,CLOSE registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534 19:55:34 MOVED_TO registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_FROM registry.vdf 19:55:34 MOVED_TO registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_TO registry.vdf 19:55:34 DELETE registry.vdf20210926195534 19:55:34 CREATE registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 MODIFY registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 OPEN registry.vdf 19:55:34 ACCESS registry.vdf 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 CLOSE_WRITE,CLOSE registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534 19:55:34 MOVED_TO registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_FROM registry.vdf 19:55:34 MOVED_TO registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_TO registry.vdf 19:55:34 DELETE registry.vdf20210926195534 19:55:34 OPEN registry.vdf 19:55:34 ACCESS registry.vdf 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:34 CREATE registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 MODIFY registry.vdf20210926195534 19:55:34 OPEN registry.vdf20210926195534 19:55:34 ACCESS registry.vdf20210926195534 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf20210926195534 19:55:34 CLOSE_WRITE,CLOSE registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534 19:55:34 MOVED_TO registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_FROM registry.vdf 19:55:34 MOVED_TO registry.vdf20210926195534 19:55:34 MOVED_FROM registry.vdf20210926195534.tmp.swap 19:55:34 MOVED_TO registry.vdf 19:55:34 DELETE registry.vdf20210926195534 19:55:34 OPEN registry.vdf 19:55:34 ACCESS registry.vdf 19:55:34 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:35 OPEN registry.vdf 19:55:35 ACCESS registry.vdf 19:55:35 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:35 OPEN registry.vdf 19:55:35 ACCESS registry.vdf 19:55:35 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:35 CREATE registry.vdf20210926195535 19:55:35 OPEN registry.vdf20210926195535 19:55:35 MODIFY registry.vdf20210926195535 19:55:35 OPEN registry.vdf20210926195535 19:55:35 ACCESS registry.vdf20210926195535 19:55:35 CLOSE_NOWRITE,CLOSE registry.vdf20210926195535 19:55:35 CLOSE_WRITE,CLOSE registry.vdf20210926195535 19:55:35 MOVED_FROM registry.vdf20210926195535 19:55:35 MOVED_TO registry.vdf20210926195535.tmp.swap 19:55:35 MOVED_FROM registry.vdf 19:55:35 MOVED_TO registry.vdf20210926195535 19:55:35 MOVED_FROM registry.vdf20210926195535.tmp.swap 19:55:35 MOVED_TO registry.vdf 19:55:35 DELETE registry.vdf20210926195535 19:55:35 OPEN registry.vdf 19:55:35 ACCESS registry.vdf 19:55:35 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:35 OPEN registry.vdf 19:55:35 ACCESS registry.vdf 19:55:35 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:36 OPEN registry.vdf 19:55:36 ACCESS registry.vdf 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:36 CREATE registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 MODIFY registry.vdf20210926195536 19:55:36 CLOSE_WRITE,CLOSE registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536 19:55:36 MOVED_TO registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_FROM registry.vdf 19:55:36 MOVED_TO registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_TO registry.vdf 19:55:36 DELETE registry.vdf20210926195536 19:55:36 OPEN registry.vdf 19:55:36 ACCESS registry.vdf 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:36 OPEN registry.vdf 19:55:36 ACCESS registry.vdf 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:36 CREATE registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 MODIFY registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 ACCESS registry.vdf20210926195536 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf20210926195536 19:55:36 CLOSE_WRITE,CLOSE registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536 19:55:36 MOVED_TO registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_FROM registry.vdf 19:55:36 MOVED_TO registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_TO registry.vdf 19:55:36 DELETE registry.vdf20210926195536 19:55:36 OPEN registry.vdf 19:55:36 ACCESS registry.vdf 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf 19:55:36 CREATE registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 MODIFY registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 ACCESS registry.vdf20210926195536 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf20210926195536 19:55:36 CLOSE_WRITE,CLOSE registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536 19:55:36 MOVED_TO registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_FROM registry.vdf 19:55:36 MOVED_TO registry.vdf20210926195536 19:55:36 OPEN registry.vdf20210926195536 19:55:36 ACCESS registry.vdf20210926195536 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf20210926195536 19:55:36 MOVED_FROM registry.vdf20210926195536.tmp.swap 19:55:36 MOVED_TO registry.vdf 19:55:36 DELETE registry.vdf20210926195536 19:55:36 OPEN registry.vdf 19:55:36 ACCESS registry.vdf 19:55:36 CLOSE_NOWRITE,CLOSE registry.vdf </code></pre> <p>I was hoping to just be able to monitor the registry file, but since it gets deleted and replaced, I took the tack of just repeatedly trying to monitor it. Unfortunately, the watch sometimes fails (I'm presuming due to trying to start watching in the middle of a swap) That's why I've added the <code>|| true</code> to the while loop.</p> <p>I'm a bit concerned about the reliability of this, and was hoping a code review might come up with some ideas.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T00:09:37.467", "Id": "268413", "Score": "2", "Tags": [ "bash" ], "Title": "Reliable separation of Steam users" }
268413
<p>I'm looking to develop a validation library which can be extended by adding custom validation rules. To write a custom rule, simply write a class and apply the ValidationRule decorator like so:</p> <pre><code>@ValidationRule('array') class IsArray { constructor(a?: number, b?: number, c?: number) { } evaluate(value: any) { return Array.isArray(value); } getErrorMessage(path: string) { return `${path} failed the 'IsArray' validation rule`; } getErrorMessageForRoot() { return `The provided object failed the 'IsArray' validation rule`; } } </code></pre> <p>This is how I implemented the decorator:</p> <pre><code>type Constructor&lt;T&gt; = { new(...args: any[]): T; } interface IValidationRule { evaluate(value: any): boolean; getErrorMessageForRoot(): string; getErrorMessage(path: string): string; } function ValidationRule(name: string) { return &lt;T extends Constructor&lt;IValidationRule&gt;&gt; (rule: T) =&gt; { // Registering the validation rule ValidationRuleRegistry.set(name, rule); // Runtime error if the user defines a method called getHash on his class if (rule.prototype.getHash) { throw new Error(&quot;The method name 'getHash' is reserved&quot;); } return class extends rule { hash: string; constructor(...args: any) { super(...args); // I haven't developped the hashing algorithm yet this.hash = (args.length === 0) ? `${rule.name}-${args}` : rule.name ; } getHash() { return this.hash; } }; } } </code></pre> <p>Below is partially how the library is to be consumed (I only left the relevant parts):</p> <pre><code>function validate(data: any, path: string, rules: string[] | IValidationRule[]) { const validationRules: IValidationRule[] = []; for (let rule of rules) { const ruleToAdd = (typeof(rule) == 'string') ? parseRule(rule) : rule; if (!validationRules .map(e =&gt; (e as any).getHash()) .includes((ruleToAdd as any).getHash())) { validationRules.push(ruleToAdd); } } // use the rules to validate the path on the data object } validate({ }, 'path', ['array:1,2,3']); validate({ }, 'path', [new IsArray(1, 2, 3)]); </code></pre> <p>A class decorated with ValidationRule will be extended by adding the getHash() method which generates a hash based on the name of the validation rule (the 'name' parameter) and the argument list. This is to prevent duplicate validations but I feel this is a really bad way of doing it. Basically, I want the getHash method to be recognized by the typechecker when called inside the validate method (right now I have to cast rules into any), and to raise typecheck errors when the user attempts to define a method getHash or a property hash on his custom rule (instead of the runtime error I'm raising in the decorator).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:43:37.637", "Id": "529344", "Score": "0", "body": "Welcome to Code Review! Asking about code that you haven't written yet is specifically [outside the scope](/help/on-topic) of Code Review. Can you confirm that the requirements in your final paragraph are fully implemented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:56:55.263", "Id": "529354", "Score": "0", "body": "@TobySpeight Yes, it's implmented and even functional but I chose to leave out some parts which aren't relevant. My question concerns finding a better way to attach the getHash method in a type-safe manner while preventingg children classes from overriding it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T02:09:44.227", "Id": "268414", "Score": "0", "Tags": [ "typescript" ], "Title": "Extendable Validation Library" }
268414
<p>I'm working on a user-pairing algorithm using socket.io, and it is running on Node.js. I want to make sure that no repeated pairings will happen when people connect in.</p> <p>The steps of the algorithm as follows:</p> <ol> <li>Divide the players into two rooms, one for retailers and the other for suppliers.</li> <li>When a player enters one of the rooms, I will fetch the socketlist from the other room and pair the player with the first socket of it. <ul> <li>If the pairing succeeds, remove both players from the rooms.</li> <li>If it fails (i.e. no one in the other room), retry every five seconds.</li> </ul> </li> </ol> <p>I'm not sure about whether there would be any race-condition problems during the process of fetching the socketlist of the room. In short, is it possible that a socket in the socketlist would be paired twice, and both pairings succeed?</p> <p>Here is the code:</p> <pre><code>const wait = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms)) io.on('connection', (socket) =&gt; { console.log('New websocket connection', socket.id) socket.on('match', async (userId, role, classroomId) =&gt; { let roles = { 'retailer': 'supplier', 'supplier': 'retailer' } room = role + classroomId otherroom = roles[role] + classroomId socket.userId = userId socket.join(room) for (let i = 0; i &lt; 60; ++i) { if (socket.rooms.has(room)) { const sockets = await io.in(otherroom).fetchSockets() if (sockets.length &gt; 0 &amp;&amp; io.sockets.sockets.get(socket[0].id).rooms.has(otherroom)) { const teammate = io.sockets.sockets.get(sockets[0].id) console.log(teammate.userId) console.log(room, otherroom) socket.leave(room) teammate.leave(room) const pair = await models.Pair.create({ supplierId: role == 'supplier' ? userId : teammate.userId, retailerId: role == 'supplier' ? teammate.userId : userId, currentTime: new Date().toISOString().slice(0, 10) }) io.to(teammate.id).to(socket.id).emit('match-success', pair) console.log((role == 'supplier' ? 's' : 'r'), pair) break } console.log(socket.id, i) // if no match, rematch every 5 seconds. await wait(5000) } else { break } } socket.on('join', (room) =&gt; { console.log('join' + room) socket.join(room) }) socket.on('leave', (room, callback) =&gt; { socket.leave(room) callback() }) }) }) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T02:53:13.900", "Id": "268415", "Score": "0", "Tags": [ "algorithm", "node.js", "socket.io" ], "Title": "Socket.io: Pairing from two rooms without repeated pairing?" }
268415
<p>I am once again attempting another CP problem, and I have ONCE AGAIN run into an optimization issue because of the time limit of one second: <a href="https://open.kattis.com/problems/doctorkattis" rel="nofollow noreferrer">https://open.kattis.com/problems/doctorkattis</a></p> <blockquote> <p>It is common for cats to have puncture wounds with different severity of infections. To help her local neighbourhood, Doctor Kattis decided to open a clinic! However, there are too many injured cats that come so she needs to prioritise her patients.</p> <p>Given the names of N injured cats, their level of severity, and subsequent updates of their infection level, determine which cat Doctor Kattis needs to give her most attention to.</p> <p>A cat with higher infection level has higher priority. If there are more than one cat with the same infection level, Doctor Kattis will give priority to the cat who arrived at the clinic first.</p> <p>There will be 4 types of commands:</p> <ul> <li>ArriveAtClinic(catName, infectionLevel): This will be indicated by a starting integer 0 followed by catName and infectionLevel, e.g. 0 LUNA 31. catName is a String that is all UPPERCASE with length 1 to<br /> 15 characters. The cat names are all unique. infectionLevel is an<br /> integer (30≤ infectionLevel ≤100).</li> <li>UpdateInfectionLevel(catName, increaseInfection): This will be indicated by a starting integer 1 followed by catName and<br /> increaseInfection, e.g. 1 LUNA 24. catName is guaranteed to have<br /> already arrived at clinic. increaseInfection is an integer (0≤<br /> increaseInfection ≤70). The infection level has a maximum value of<br /> 100 and the update infection commands are given in such a way that<br /> the overall infection level of any cat will not exceed 100.</li> <li>Treated(catName): This will be indicated by a starting integer 2 followed by catName, e.g. 2 KITTY. catName is guaranteed to have<br /> already arrived at the clinic. catName leaves the clinic after being<br /> treated.</li> <li>Query(): This will be indicated by a single integer 3. Your job is to print the catName with the highest infection level or “The clinic is empty” if there are no more cats.</li> </ul> <p><strong>Input:</strong> The first line of input contains an integer N, denoting the number of commands (1≤N≤1000000). There will be up to 200000 cats. This will be followed by N commands as described above.</p> <p>Output Each time the Query() command is encountered, the catName with highest infection level or “The clinic is empty” is to be printed in one line.</p> <p><strong>Subtasks</strong>:</p> <ul> <li>(30 points): 1≤N≤100, there will be up to 15 cats</li> <li>(30 points): 1≤N≤1000000, there will be up to 200000 cats. However, there is no call to UpdateInfectionLevel command and the cat with the highest infection level is always the first to be be treated, i.e.<br /> you can see this as Treated(Query())</li> <li>(40 points): 1≤N≤1000000, there will be up to 200000 cats. However, there will be frequent UpdateInfectionLevel commands and the cat with the highest infection level is not always the first to be treated</li> </ul> <p><strong>Explanation</strong> In the sample test case, we have N=15 commands:</p> <ul> <li>ArriveAtClinic(“LUNA”, 31)</li> <li>ArriveAtClinic(“NALA”, 55)</li> <li>ArriveAtClinic(“BELLA”, 42)</li> <li>Query(). You have to print out “NALA”, as she is currently the one with the highest infection level. To be precise, at the moment the order is:<br /> (NALA, 55), (BELLA, 42), (LUNA, 31).</li> <li>ArriveAtClinic(“KITTY”, 77)</li> <li>Query(). Now you have to print out “KITTY”. The current order is:<br /> (KITTY, 77), (NALA, 55), (BELLA, 42), (LUNA, 31).</li> <li>UpdateInfectionLevel(“LUNA”, 24). After this event, the one with the highest infection level is still KITTY with infectionLevel = 77. “LUNA” now has infection level = 31+24 = 55, but this is still 22 smaller than “KITTY”. Note that “NALA” also has infection level = 55 but “LUNA” is in front of “NALA” because “LUNA” arrived at the clinic earlier. The current order is:<br /> (KITTY, 77), (LUNA, 55), (NALA, 55), (BELLA, 42).</li> <li>Treated(“KITTY”). “KITTY” now has been treated ‘instantly’, and “KITTY” leaves Doctor Kattis’s clinic.</li> <li>Query(). Now you have to print out “LUNA”, as the current order is:<br /> (LUNA, 55), (NALA, 55), (BELLA, 42).</li> <li>Treated(“BELLA”). “BELLA” leaves Doctor Kattis’s clinic.</li> <li>Query(). The answer is still: “LUNA”. The current order is:<br /> (LUNA, 55), (NALA, 55).</li> <li>Treated(“LUNA”). “LUNA” leaves Doctor Kattis’s clinic.</li> <li>Query(). You have to answer: “NALA”. The current order is:<br /> (NALA, 55).</li> <li>Treated(“NALA”). “NALA” leaves Doctor Kattis’s clinic.</li> <li>Query(). You have to answer: “The clinic is empty”.</li> </ul> <p><strong>Sample Input 1</strong></p> <pre><code>15 0 LUNA 31 0 NALA 55 0 BELLA 42 3 0 KITTY 77 3 1 LUNA 24 2 KITTY 3 2 BELLA 3 2 LUNA 3 2 NALA 3 </code></pre> <p><strong>Sample Output 1</strong></p> <pre><code>NALA KITTY LUNA LUNA NALA The clinic is empty </code></pre> </blockquote> <p>I put each cat into a dictionary/hashmap and set their names to the keys and their infection level as their value. Then I update them in order, delete them when they 'get treated' and return the key with the largest value when they ask a query. This is the fastest solution I can think of, and I'm pretty sure the Python program runs in O(n) time. After my Python program wasn't able to complete it in time, I spent some time translating it into C++, but that also didn't work. I'm not sure if that was because I barely know anything about C++ and I accidentally increased the time complexity with my for loops, or that there's a better solution.</p> <p>My Python Program:</p> <pre><code>order = {} n = int(input().strip()) for _ in range(n): line = input().strip().split() if line[0] == '0': order[line[1]] = int(line[2]) elif line[0] == '1': order[line[1]] += int(line[2]) elif line[0] == '2': order.pop(line[1]) else: if len(order) &gt; 0: print(max(order, key=order.get)) else: print('The clinic is empty') </code></pre> <p>C++ Attempt:</p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; pair&lt;string, int&gt; findEntryWithLargestValue(map&lt;string, int&gt; sampleMap){ pair&lt;string, int&gt; entryWithMaxValue= make_pair(&quot;&quot;, 0); map&lt;string, int&gt;::iterator currentEntry; for (currentEntry = sampleMap.begin(); currentEntry != sampleMap.end(); ++currentEntry) { if (currentEntry-&gt;second &gt; entryWithMaxValue.second) { entryWithMaxValue = make_pair( currentEntry-&gt;first, currentEntry-&gt;second); } } return entryWithMaxValue; } int main(){ int n; cin &gt;&gt; n; map&lt;string, int&gt; order; for (int i = 0; i &lt; n; i++){ int cmd, inf; string name; cin &gt;&gt; cmd; if (cmd == 0){ cin &gt;&gt; name &gt;&gt; inf; order.insert(pair&lt;string, int&gt;(name, inf)); }else if (cmd == 1){ cin &gt;&gt; name &gt;&gt; inf; auto check = order.find(name); if(check != order.end()){ check-&gt;second += inf; } }else if (cmd == 2){ cin &gt;&gt; name; order.erase(name); }else{ pair&lt;string, int&gt; query = findEntryWithLargestValue(order); if (query.first != &quot;&quot;){ cout &lt;&lt; query.first &lt;&lt; '\n'; }else{ cout &lt;&lt; &quot;The clinic is empty&quot; &lt;&lt; '\n'; } } } return 0; } </code></pre> <p>I found another attempt using a heap, but that Python program didn't work either: <a href="https://github.com/jed1337/Kattis/blob/master/doctor_kattis.py" rel="nofollow noreferrer">https://github.com/jed1337/Kattis/blob/master/doctor_kattis.py</a></p> <blockquote> <pre><code>&quot;&quot;&quot; A heap is used to order the patients by infection level, then arrival time at the clinic &quot;&quot;&quot; import heapq INFECTION_INDEX = 0 ARRIVAL_INDEX = 1 NAME_INDEX = 2 command_count = int(input()) arrive_time = 0 patient_heap = [] for _ in range(command_count): command = input().split() opcode = command[0] if opcode == &quot;0&quot;: _, name, infection = command # Store the infection in negative so that the most infected will be at the first heapq.heappush(patient_heap, [-int(infection), int(arrive_time), name]) arrive_time += 1 elif opcode == &quot;1&quot;: _, name, increase_value = command for i in range(len(patient_heap)): if patient_heap[i][NAME_INDEX] == name: patient_heap[i][INFECTION_INDEX] -= int(increase_value) heapq.heapify(patient_heap) break elif opcode == &quot;2&quot;: _, name = command for i in range(len(patient_heap)): if patient_heap[i][NAME_INDEX] == name: del patient_heap[i] heapq.heapify(patient_heap) break elif opcode == &quot;3&quot;: if patient_heap: print(patient_heap[0][NAME_INDEX]) else: print(&quot;The clinic is empty&quot;) </code></pre> </blockquote> <p>Am I missing another obvious solution? This probably isn't possible in Python since the <a href="https://open.kattis.com/problems/doctorkattis/statistics" rel="nofollow noreferrer">solution statistics</a> have no Python solutions in them, but there are many solutions in C, C++, Java, Kotlin, and Rust. If there is any way I could speed it up, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T07:04:35.130", "Id": "529339", "Score": "2", "body": "Welcome to Code Review! Could you clarify what you mean when you say the program \"failed\"? If it gives incorrect results, it's not yet ready for review (we require _working_ code here). If it just takes too long, then replace [programming-challenge] tag with [time-limit-exceeded]. Also, your title should just summarise the _purpose_ of the code (something like \"Prioritise injured cats for treatment\"?). Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:37:53.497", "Id": "529365", "Score": "1", "body": "Consider adding `std::ios::sync_with_stdio(false)` at the start of `main`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:39:25.860", "Id": "529375", "Score": "0", "body": "In the `heapq` documentation, take a look at the sample code under [Priority Queue Implementation Notes](https://docs.python.org/3.9/library/heapq.html#priority-queue-implementation-notes)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T19:42:16.037", "Id": "529473", "Score": "3", "body": "\"_I found another attempt using a heap, but that Python program didn't work either_\" suggests the following code is not your own. We require code posted here to either be written by (or maintained by) the OP. We cannot review third-party code. This should be removed from your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T12:16:26.203", "Id": "529512", "Score": "0", "body": "`We can review the C++ code if and only if you wrote that`, we can't review the python solution you found online, and we have to close the question unless you remove the python code." } ]
[ { "body": "<p>I'm just reviewing the C++ code here.</p>\n\n<h1>Pass by reference where appropriate</h1>\n<p>Unlike Python, C++ by default passes parameters by <em>value</em>. This means that with your version of <code>findEntryWithLargestValue()</code>, a copy of the whole map is made every time you call it. Instead, pass by reference:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto findEntryWithLargestValue(const std::map&lt;string, int&gt;&amp; sampleMap) {\n std::pair&lt;std::string, int&gt; entryWithMaxValue{};\n ...\n return entryWithMaxValue;\n}\n</code></pre>\n<h1>Use range-<code>for</code> where appropriate</h1>\n<p>Make use of C++'s range-<code>for</code> for more concise code:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (auto&amp; currentEntry: sampleMap) {\n if (currentEntry.second &gt; entryWithMaxValue.second) {\n entryWithMaxValue = currentEntry;\n }\n}\n</code></pre>\n<p>But it can be simplified even further:</p>\n<h1>Consider using STL algorithms</h1>\n<p>The standard library comes with lots of useful <a href=\"https://en.cppreference.com/w/cpp/header/algorithm\" rel=\"nofollow noreferrer\">algorithms</a> that can operate on containers, for example it can find the largest element using <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"nofollow noreferrer\"><code>std::max_element()</code></a>. Using this, I would remove <code>findEntryWithLargestValue()</code> and just write this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto it = std::max_element(std::begin(order), std::end(order), [](auto &amp;a, auto &amp;b) {\n return a.second &lt; b.second;\n};\n\nif (it != order.end()) {\n std::cout &lt;&lt; it-&gt;first &lt;&lt; '\\n';\n} else {\n std::cout &lt;&lt; &quot;The clinic is empty\\n&quot;;\n}\n</code></pre>\n<h1>Add an index on infection level</h1>\n<p>The problem you have is that you have to be able to search both on a cat's name and on its infection level. The <code>std::map</code> you created is sorted on name, but to find the cat with the highest infection level, you are doing an expensive <span class=\"math-container\">\\$\\mathcal{O}(N)\\$</span> search. You can speed that up if you also have a map of cats sorted by infection level, so that you can find the next cat to treat in <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> time.</p>\n<p>Since unlike names, infection levels don't have to be unique, I would create a <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"nofollow noreferrer\"><code>std::set</code></a> with each element being a <code>std::pair&lt;string, int&gt;</code> repesenting a cat, and a custom comparator function that orders by infection level first and name second, like so:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static bool compare_by_infection(const std::pair&lt;std::string, int&gt; &amp;a, const std::pair&lt;std::string, int&gt; &amp;b) {\n return a.second != b.second ? a.second &lt; b.second : a.first &lt; b.first;\n}\n\nstd::set&lt;std::pair&lt;std::string, int&gt;, decltype(compare_by_infection)&gt;\n order_by_infection(compare_by_infection);\n</code></pre>\n<p>It's a bit of work (it can be written more compact with recent versions of C++ though), but then looking up the cat with the highest infection level is just:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (order_by_infection.empty()) {\n std::cout &lt;&lt; &quot;The clinic is empty\\n&quot;;\n} else {\n std::cout &lt;&lt; order_by_infection.back().first &lt;&lt; '\\n';\n}\n</code></pre>\n<p>Updating a cat's infection level is now a bit harder though; you have to remove it from <code>order_by_infection</code>, then change the level, then add it back.</p>\n<h1>Use a <code>std::unordered_map</code> to store cats by name</h1>\n<p>A <code>std::map</code> is not the best choice for <code>order</code>, as you don't need it to be sorted on name. A <code>std::unordered</code> map has faster insertion, removal and lookup (<span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> vs <span class=\"math-container\">\\$\\mathcal{O}(\\log N)\\$</span> for <code>std::map</code>).</p>\n<h1>Use <code>emplace()</code> instead of <code>insert()</code></h1>\n<p>Instead of:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>order.insert(std::pair&lt;std::string, int&gt;(name, inf));\n</code></pre>\n<p>Write:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>order.emplace(name, inf);\n</code></pre>\n<p>This avoids having to create a temporary <code>std::pair</code>, which avoids unnecessary copies.</p>\n<h1>Don't use <code>&lt;bits/stdc++.h&gt;</code></h1>\n<p><a href=\"//stackoverflow.com/q/31816095\">You should not <code>#include &lt;bits/stdc++.h&gt;</code>.</a> It is not standard C++. Just <code>#include</code> the proper header files, like <code>&lt;map&gt;</code>, <code>&lt;utility&gt;</code>, <code>&lt;string&gt;</code> and <code>&lt;iostream&gt;</code>.</p>\n<p>Note that also <a href=\"//stackoverflow.com/q/1452721\"><code>using namespace std</code> is considered bad practice</a>, although it's valid C++. Coding challenge sites often teach you these bad habits, it saves a little bit of typing but it doesn't affect performance, and you might run into problems if you use these shortcuts in real programs.</p>\n<h1>Consider creating a <code>struct Cat</code></h1>\n<p>A <code>std::pair</code> is a quick solution to pass two variables at once, but if you use them a lot you'll notice that you have to use <code>.first</code> and <code>.second</code> everywhere. It would be much clearer if you create a <code>struct</code> to group these variables, so you can give them proper names:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Cat {\n std::string name;\n int infection_level;\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T12:58:45.043", "Id": "529517", "Score": "0", "body": "Some questions, as I'm not much of a C++ guy: Instead of `set<pair<string,int>>` with custom comparator, can't we just use a `multimap<int,string>`? Does `order.emplace(name, inf)` differ from `order[name] = inf`? Both their code and yours order by cat name instead of by which cat arrived first, so aren't both wrong? I'd like to look up the complexity of `set::back` but I can't find it, can you share a link?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:07:29.087", "Id": "529519", "Score": "0", "body": "I missed the rule about the arrival order, yes then we're both wrong. I didn't think about `std::multimap`, that's a good suggestion. Then probably the arrival time should also be stored, and then use `equal_range()` followed by a `min_element()`? That might still be slow if you have many cats with equal infection levels..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:25:24.127", "Id": "268426", "ParentId": "268416", "Score": "5" } }, { "body": "<blockquote>\n<p>This probably isn't possible in Python since the <a href=\"https://open.kattis.com/problems/doctorkattis/statistics\" rel=\"nofollow noreferrer\">solution statistics</a> have no Python solutions in them</p>\n</blockquote>\n<p>Now they do :-)</p>\n<p><a href=\"https://i.stack.imgur.com/O3QZN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O3QZN.png\" alt=\"enter image description here\" /></a></p>\n<p>Some things about yours:</p>\n<ul>\n<li>Yours isn't <span class=\"math-container\">\\$O(n)\\$</span> but rather <span class=\"math-container\">\\$O(nc)\\$</span>, where <span class=\"math-container\">\\$c\\$</span> is the number of cats currently in the clinic. Because your <code>max(order, key=order.get)</code> goes through all <span class=\"math-container\">\\$c\\$</span> cats to find the maximum. And <span class=\"math-container\">\\$c\\$</span> can be as large as <span class=\"math-container\">\\$200000\\$</span>, so that's a problem.</li>\n<li>You don't need <code>strip()</code>, as <code>split()</code> takes care of that.</li>\n<li><code>max</code> has a default parameter, so you can just do<br />\n<code>print(max(order, key=order.get, default='The clinic is empty'))</code><br />\ninstead of your <code>if-else</code>.</li>\n</ul>\n<p>Now, how to make it fast enough to get accepted:</p>\n<ul>\n<li>Iterate <code>sys.stdin</code> instead of repeating <code>input()</code>.</li>\n<li>Organize the cats in a heap.</li>\n<li>Some optimizations.</li>\n</ul>\n<p>My solution (accepted in 0.76 seconds, a bit slower but cleaner than my fastest), notes below:</p>\n<pre><code>import sys, heapq\n\nheap = [(0, 0)]\ncurrent = [heap[0]]\nindexes = {}\nnames = ['The clinic is empty']\n\nnext(sys.stdin)\nfor line in sys.stdin:\n command, *args = line.split()\n if command == '0':\n name, level = args\n index = indexes[name] = len(names)\n names.append(name)\n entry = -int(level), index\n current.append(entry)\n heapq.heappush(heap, entry)\n elif command == '1':\n name, increase = args\n index = indexes[name]\n old_level = current[index][0]\n entry = old_level - int(increase), index\n current[index] = entry\n heapq.heappush(heap, entry)\n elif command == '2':\n name, = args\n index = indexes[name]\n current[index] = None\n else:\n while heap[0] is not current[heap[0][1]]:\n heapq.heappop(heap)\n print(names[heap[0][1]])\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>On my <strong><code>heap</code></strong>, I store pairs of <code>(negated infection level, cat index)</code>. Negated level because Python's <a href=\"https://docs.python.org/3/library/heapq.html\" rel=\"nofollow noreferrer\">heapq</a> module does <em>min</em>-heaps but I want <em>larger</em> levels first. And whenever a new cat arrives (command type 0), I give them a new index (1, 2, 3, etc). This ensures proper order among cats with the same infection level and allows fast heap entry comparisons. My <strong><code>names</code></strong> and <strong><code>indexes</code></strong> let me look up names and indexes from indexes and names.</li>\n<li>In <strong><code>current</code></strong> I keep, for every cat, a reference to its <em>current</em> heap entry. This allows me to recognize obsolete entries when answering queries (command type 3).</li>\n<li>I use a sentinel<sup>(*)</sup> cat named <code>'The clinic is empty'</code> which is perfectly healthy. It'll always be on the heap, so I don't need special checking code to test whether the clinic is empty.<br />\n<sub><sup>(*)</sup> Darn, &quot;feline&quot; and &quot;sentinel&quot; share so many letters, but I couldn't come up with a nice portmanteau.</sub></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T20:36:15.190", "Id": "529477", "Score": "1", "body": "\"Hi, this is your cat's veterinary clinic. We're having some computer trouble...\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T20:37:54.000", "Id": "529478", "Score": "2", "body": "@user673679 Oh, dear - Did she break something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T03:25:34.730", "Id": "529565", "Score": "0", "body": "I am very impressed by the fact that you pulled it off!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T20:27:26.223", "Id": "268490", "ParentId": "268416", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T03:33:20.280", "Id": "268416", "Score": "4", "Tags": [ "python", "c++", "performance", "hash-map" ], "Title": "Prioritise injured cats for treatment (dictionary/map search optimization Python and C++)" }
268416
<p>Just experimenting some things with css, I made a centered circle div (inner) which is inside a circle div (outer). <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Document&lt;/title&gt; &lt;style&gt; body { margin: 0; } .outer { background-color: skyblue; height: 200px; width: 200px; border-radius: 50%; padding: 25px 25px 25px 25px; } .inner { background-color: lightgreen; height: 150px; width: 150px; border-radius: 50%; margin: 25px 25px 25px 25px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="outer"&gt; &lt;div class="inner"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>The thing is I had to give padding in &quot;outer&quot; and also margin to &quot;inner&quot;. So I want to know if there is a better way of doing this.</p>
[]
[ { "body": "<p>instead of the margin and padding, you can declare the outer circle as a grid, which allows you alignment control of its children:\n(note that <code>place-items</code> aligns vertically and horizontally)</p>\n<pre><code> display: grid;\n place-items: center;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T09:26:24.690", "Id": "268424", "ParentId": "268419", "Score": "1" } }, { "body": "<p>There are many ways to achieve this, from them here are 3 examples...</p>\n<p>Check the code below and here is how it works:</p>\n<p><strong>The first one</strong> uses flex with the css class center-f-inside <em>(shorthand for: center everything inside this element with flex)</em>. You can add this to the outer circle. In the code I have also added this class to the inner circle so that I can center the text inside.</p>\n<p><strong>The second one</strong> uses grid with the css class center-g-inside <em>(shorthand for: center everything inside this element with grid)</em>. You can add this to the outer circle. In the code I have also added this class to the inner circle so that I can center the text inside. Note that this is not supported in legacy browsers like IE, as grid was implemented only a few years ago.</p>\n<p><strong>The third one</strong> uses positioning with the css class center-p-inside <em>(shorthand for: center this element with position absolute in relation with some parent)</em> and css class relative <em>(adds position: relative to the parent)</em>. You can add relative to the outer circle and center-p-inside to the inner circle. The after pseudo element is used so that I can center the text inside using flex.</p>\n<p>I am using transform in the center-p-inside class to center it evenly as top: 50% and left: 50% will position your div's top-left corner to the center of the parent div. Hence using translate (-50%, -50%) makes it so that now the center of your child div is positioned exactly at the center of your parent div from the origin of child div (origin of your child div is by default at the center of your child div).</p>\n<p><em>Now you don't need those pesky margin and padding hacks</em> :)</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-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n &lt;title&gt;Document&lt;/title&gt;\n &lt;style&gt;\n\n body {\n margin: 0;\n }\n\n .outer {\n background-color: skyblue;\n height: 200px;\n width: 200px;\n }\n\n .inner {\n background-color: lightgreen;\n height: 150px;\n width: 150px;\n }\n\n /* Special circle class to enhance html readability */\n .circle {\n border-radius: 50%;\n }\n\n /* Add this to the outer circle - Flex */ \n /* Added to the inner circle to center text */\n .center-f-inside {\n display: flex;\n justify-content: center;\n align-items: center;\n }\n\n /* Add this to the outer circle - Grid */ \n /* Added to the inner circle to center text */\n .center-g-inside {\n display: grid;\n place-items: center;\n }\n\n /* Add this to the outer circle - Positioning */\n .relative {\n position: relative;\n }\n\n /* Add this to the inner circle - Positioning */\n .center-p-inside {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n }\n\n /* This pseudo element is only used to center text, ignore */\n .center-p-inside::after {\n content: \"absolute\";\n width: 100%;\n height: 100%;\n background-color: transparent;\n display: flex;\n justify-content: center;\n align-items: center;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;!--With Flex--&gt;\n &lt;div class=\"outer circle center-f-inside\"&gt;\n &lt;div class=\"inner circle center-f-inside\"&gt;flex&lt;/div&gt;\n &lt;/div&gt;\n\n &lt;!--With Grid--&gt;\n &lt;div class=\"outer circle center-g-inside\"&gt;\n &lt;div class=\"inner circle center-g-inside\"&gt;grid&lt;/div&gt;\n &lt;/div&gt;\n\n &lt;!--With Positioning--&gt;\n &lt;div class=\"outer circle relative\"&gt;\n &lt;div class=\"inner circle center-p-inside\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T11:52:22.920", "Id": "529511", "Score": "1", "body": "You don't have a Stack Overflow account?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T08:06:06.143", "Id": "529654", "Score": "1", "body": "I think I do... But its been so long that I forgot about it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:51:41.067", "Id": "268427", "ParentId": "268419", "Score": "2" } } ]
{ "AcceptedAnswerId": "268427", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T06:28:34.227", "Id": "268419", "Score": "2", "Tags": [ "html", "css" ], "Title": "A circle in a circle" }
268419
<p>My code runs exactly as it should. However, I would like to make it run a bit faster. I have tried defining some variables as <code>Long</code> to run it faster but it is still a bit slow.</p> <p>Is it possible to remove some code to make the macro run faster?</p> <pre><code>Sub sortiereninl() Dim sort As Worksheet Set sort = Worksheets(&quot;Inland&quot;) Dim count As Long Dim n As Long Dim wkn As Long wkn = sort.Cells.Find(&quot;WKN&quot;).Column Dim lastcolumn As Long lastcolumn = sort.UsedRange.SpecialCells(xlCellTypeLastCell).Column Dim lastrow As Long lastrow = sort.UsedRange.SpecialCells(xlCellTypeLastCell).Row Dim allrows As Long allrows = WorksheetFunction.CountA(Range(Cells(2, wkn), Cells(lastrow, lastcolumn))) For i = 2 To allrows + 1 If Cells(i, wkn).Value &lt;&gt; &quot;&quot; Then count = sort.Cells(i, Columns.count).End(xlToLeft).Column - wkn If count &lt;&gt; 0 Then sort.Range(Cells(i + 1, wkn), Cells(i + count, wkn)).EntireRow.Insert sort.Range(Cells(i, wkn + 1), Cells(i, count + wkn)).Copy sort.Cells(i + 1, wkn).PasteSpecial Transpose:=True End If End If Next i With sort.Range(Cells(1, wkn + 1), Cells.SpecialCells(xlCellTypeLastCell)) .ClearContents End With End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T10:54:47.817", "Id": "529352", "Score": "2", "body": "What is the code solving? We can only help you optimize the code when we know what it is doing. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T11:01:46.663", "Id": "529356", "Score": "0", "body": "Yes, it is possible. Changing the variable to long is not going to improve performance. Here are some tips to help: [Top Ten Tips To Speed Up Your VBA Code](http://www.eident.co.uk/2016/03/top-ten-tips-to-speed-up-your-vba-code/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T11:35:31.177", "Id": "529358", "Score": "0", "body": "I will say that a variable named `sort` will throw people off. I presume it means something in your language that's different from what it means in English, remember, though that [`Range.Sort`](https://docs.microsoft.com/en-us/office/vba/api/excel.range.sort) is the same in VBA no matter what spoken language you use. I'm only on my 1st cup of coffee, but I saw all those lines beginning `sort.Range(...` and though you were sorting your data in a loop which would be slow..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T11:45:05.893", "Id": "529360", "Score": "1", "body": "Your best bet would probably be to copy the data from the worksheet to `Dim sourceData() as Variant`, copy/transpose it to `Dim destData() as Variant`, then past `destData()` back to the worksheet. Reading/writing to the worksheet is going to be the slowest operation you're doing in that loop, though I'm not sure where `PasteSpecial.Transpose` falls in the \"speed\" range. There are plenty of answers here and at [StackOverflow](https://stackoverflow.com) on how to copy a range from a worksheet to an array and back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T18:11:47.583", "Id": "529398", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/268422/2) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<h2>Turn Off ScreenUpdating and Calculations to Optimize Performance</h2>\n<p>This stops VBA from having to want for Excel to recalculate formulas and refresh the screen.</p>\n<p>Turn Off ScreenUpdating and Calculations:</p>\n<pre><code>With Application\n .Calculation = xlCalculationManual\n .ScreenUpdating = False\nEnd With\n</code></pre>\n<p>Restore ScreenUpdating and Calculations:</p>\n<pre><code>With Application\n .Calculation = xlCalculationAutomatic\n .ScreenUpdating = False\nEnd With\n</code></pre>\n<h2>Option Explicit</h2>\n<p>Adding <code>Option Explicit</code> to the top of the Modules forces us to declarer our variables. This prevents use from testing code that has typos.</p>\n<h2>Ranges Should be Fully Qualified</h2>\n<p>Ranges should be &quot;fully qualified&quot; to their Worksheet. This ensures that you code is processing the cells on the correct worksheet.</p>\n<pre><code>Set sort = Worksheets(&quot;Inland&quot;)\nWith sort.Range(Cells(1, wkn + 1), Cells.SpecialCells(xlCellTypeLastCell))\n .ClearContents\nEnd With\n</code></pre>\n<p>Sort is qualified to the Inland worksheet. <code>Cells(1, wkn + 1)</code> references the ActiveSheet. The code will throw an error if Inland is not the active worksheet.</p>\n<p>The code below is fully qualified. It will run as expected as long as the Workbook is the active Workbook.</p>\n<pre><code>With Worksheets(&quot;Inland&quot;)\n With sort.Range(.Cells(1, wkn + 1), .Cells.SpecialCells(xlCellTypeLastCell))\n .ClearContents\n End With\nEnd With\n</code></pre>\n<p>When working with multiple workbooks, Ranges should be fully qualified to their workbook like this:</p>\n<pre><code>With ThisWorkbook.Worksheets(&quot;Inland&quot;)\n With sort.Range(.Cells(1, wkn + 1), .Cells.SpecialCells(xlCellTypeLastCell))\n .ClearContents\n End With\nEnd With\n</code></pre>\n<h2>Variable Naming</h2>\n<p>Variables should have clear unambiguous names. Ideally, our code should make sense when spoken.</p>\n<h2>Use <code>Range.CurrentRegion</code> when Applicable</h2>\n<p>Here is my fallback order for setting up data in excel</p>\n<ol>\n<li>Tables: the ideal way to reference data in Excel</li>\n<li>Lists: a contiguous block of related cells. The block of code may have a header row but no completely empty rows and no extra rows that have nothing to do with you target data.</li>\n</ol>\n<p>Setting your data up like this will make it easy to reference your ranges.</p>\n<p>In the following examples we have a list that starts in the first cell on the Inland tab.</p>\n<p>Example 1: Header and Data Rows</p>\n<pre><code>With Worksheets(&quot;Inland&quot;)\n Set Target = .Range(&quot;A1&quot;).CurrentRegion\nEnd With\n</code></pre>\n<p>Example 2: Only Header Row</p>\n<pre><code>With Worksheets(&quot;Inland&quot;)\n Set Target = .Range(&quot;A1&quot;).CurrentRegion.Rows(1)\nEnd With\n</code></pre>\n<p>Example 3: Only Header Row</p>\n<pre><code>With Worksheets(&quot;Inland&quot;)\n Set target = .Range(&quot;A1&quot;).CurrentRegion\n Set target = Intersect(target, target.Offset(1))\nEnd With\n</code></pre>\n<h2>Refactored Code</h2>\n<p>The fun part of the review!</p>\n<p>Notice that I clearly define all ranges that I will be working with. While writing the code I use <code>Range.Select</code> to ensure the correct range is getting targeted.</p>\n<pre><code>Sub RefactoredSortiereninl()\n\n\n With Application\n .Calculation = xlCalculationAutomatic\n .ScreenUpdating = False\n End With\n \n With Worksheets(&quot;Inland&quot;)\n Dim DataRange As Range\n Set DataRange = .Range(&quot;A1&quot;).CurrentRegion\n \n Dim DataBodyRange As Range\n Set DataBodyRange = Intersect(DataRange, DataRange.Offset(1))\n \n Dim WKNColumn As Range\n Set WKNColumn = Intersect(DataRange, DataRange.Rows(1).Find(&quot;WKN&quot;).EntireColumn)\n \n Dim DataColumns As Range\n Rem The next line was originally posted but would return extra columns if WKNColumn was the last column\n Rem Set DataColumns = WKNColumn.Resize(, WKNColumn.End(xlToRight).Column - WKNColumn.Column + 1)\n Set DataColumns = WKNColumn.Resize(, .Columns(.Columns.count).End(xlToLeft).Column - WKNColumn.Column + 1)\n Dim WKN As Long\n WKN = WKNColumn.Column\n \n Dim NewLastRow As Long\n NewLastRow = WorksheetFunction.CountA(DataColumns) + 1\n \n Dim r As Long, count As Long\n For r = 2 To NewLastRow\n If .Cells(r, WKN).Value &lt;&gt; &quot;&quot; Then\n count = .Cells(r, .Columns.count).End(xlToLeft).Column - WKN\n If count &lt;&gt; 0 Then\n .Range(.Cells(r + 1, WKN), .Cells(r + count, WKN)).EntireRow.Insert\n .Range(.Cells(r, WKN + 1), .Cells(r, count + WKN)).Copy\n .Cells(r + 1, WKN).PasteSpecial Transpose:=True\n End If\n End If\n Next r\n \n Rem Rem The next line was originally posted but would fail if DataColumns last column was the last column in the Worksheet\n Rem DataColumns.Offset(, 1).ClearContents\n DataColumns.Resize(, DataColumns.Columns.count - 1).Offset(, 1).ClearContents\n \n End With\n \n With Application\n .Calculation = xlCalculationManual\n .ScreenUpdating = False\n End With\n \nEnd Sub\n</code></pre>\n<h2>Optimal Performance</h2>\n<p>Performing all work in memory using arrays will give you the optimal performance. Here are the steps:</p>\n<ol>\n<li>Read the data into an array</li>\n<li>Declare a second array to hold the results</li>\n<li>Size the results array to fit the new data</li>\n<li>Assign the old values to the results array</li>\n<li>Clear the old data</li>\n<li>Write the new data to the worksheet</li>\n</ol>\n<p>I find that this technique is able to process ~60,000 values per second.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:09:07.627", "Id": "529370", "Score": "0", "body": "@CDP1802 Good catch! I removed `Option Explicit` when I was testing the OP's code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T07:55:49.790", "Id": "529428", "Score": "0", "body": "Thank you so much! This was such a detailed solution and you explained well. Really amazing work!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:26:36.910", "Id": "529432", "Score": "0", "body": "I am just getting one error with the refactored code on the line - DataColumns.Offset(, 1).ClearContents . The error reads as Application-defined or object-defined error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T16:50:59.783", "Id": "529461", "Score": "0", "body": "@Kanishkgarg I modified the code to handle some edge cases. Let me know if it works for you. CDP1802 's is faster then mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:50:47.927", "Id": "529503", "Score": "0", "body": "Hey, I am still getting the same error for the line - DataColumns.Resize(, DataColumns.Columns.count - 1).Offset(, 1).ClearContents. I think your comment about Datacolumns being the last column holds true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:51:58.777", "Id": "529504", "Score": "0", "body": "@Kanishkgarg Can you send me some sample data to tinmanse@aol.com?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:53:08.083", "Id": "529505", "Score": "0", "body": "Sure! Ill find some sample data and send it soon." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:57:29.577", "Id": "268431", "ParentId": "268422", "Score": "4" } }, { "body": "<p>It is faster to read the data from the Sheet into an array, process the array values into a new array, then write the new array back to the sheet.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Sub sortierenin2()\n\n Dim sort As Worksheet\n Dim count As Long, i As Long, n As Long, newrows As Long\n Dim WKN As Long, lastcolumn As Long, lastrow As Long\n Dim arIn, arOut, iOut As Long, j As Long, t0 As Single: t0 = Timer\n\n Set sort = Worksheets(&quot;Inland&quot;)\n With sort\n WKN = .Cells.Find(&quot;WKN&quot;).Column\n lastcolumn = .UsedRange.SpecialCells(xlCellTypeLastCell).Column\n lastrow = .UsedRange.SpecialCells(xlCellTypeLastCell).Row\n newrows = WorksheetFunction.CountA(.Range(.Cells(2, WKN + 1), .Cells(lastrow, lastcolumn)))\n ' Copy from sheet into array\n arIn = .UsedRange\n End With\n ' Size array to take existing rows and new rows\n ReDim arOut(1 To UBound(arIn) + newrows, 1 To WKN)\n For i = 1 To UBound(arIn)\n iOut = iOut + 1\n For j = 1 To lastcolumn\n If j &gt; WKN Then\n ' Insert a new row for every column after WKN\n If (i &gt; 1) And (arIn(i, j) &lt;&gt; &quot;&quot;) Then\n iOut = iOut + 1\n arOut(iOut, WKN) = arIn(i, j)\n End If\n Else\n ' Copy existing row\n arOut(iOut, j) = arIn(i, j)\n End If\n Next\n Next\n \n ' Write array with inserted rows back to sheet.\n Application.ScreenUpdating = False\n With sort\n .UsedRange.ClearContents\n .Range(&quot;A1&quot;).Resize(UBound(arOut), UBound(arOut, 2)) = arOut\n End With\n Application.ScreenUpdating = True\n\n MsgBox Format(Timer - t0, &quot;0.00 secs&quot;)\n \nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:23:34.197", "Id": "529374", "Score": "2", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T17:22:40.393", "Id": "529397", "Score": "2", "body": "We Appreciate the added bit about the reason for using Arrays, but could you add more explanation around the steps that you took to convert the OP Code to your Code with the Arrays? it would help the OP understand how to write better code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T09:25:37.323", "Id": "529507", "Score": "0", "body": "@CDP1802 thanks a lot for this code! It works perfectly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T13:48:23.397", "Id": "268432", "ParentId": "268422", "Score": "0" } } ]
{ "AcceptedAnswerId": "268432", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T09:12:03.747", "Id": "268422", "Score": "3", "Tags": [ "performance", "vba", "excel" ], "Title": "Sorting worksheet by a given column" }
268422
<p>I wrote a minimal CSV parser for my machine learning toy project.</p> <pre><code>class CSV { public: using data_type = std::variant&lt;int32_t, float, std::string&gt;; using row_type = std::vector&lt;data_type&gt;; private: std::vector&lt;row_type&gt; rows; std::vector&lt;row_type&gt; columns; std::vector&lt;std::string&gt; column_names; std::vector&lt;int&gt; column_data_types; public: CSV(std::istream&amp; is) { ParseCSV(is); } int32_t to_int(const std::string&amp; str) { int32_t result = 0; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result); return result; } float to_float(const std::string&amp; str) { float result = 0; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result); return result; } data_type to_data(const std::string&amp; str, std::size_t col_index) { switch (column_data_types[col_index]) { case 0: return to_int(str); break; case 1: return to_float(str); break; case 2: return str; break; default: float result = 0.0f; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result); if (ec == std::errc::invalid_argument) { // this data type is a string column_data_types[col_index] = 2; return str; } else if (result == std::floor(result)) { // this may be an integer column_data_types[col_index] = 0; return to_int(str); } else { column_data_types[col_index] = 1; return result; } break; } assert(0); return {}; } void ParseHeader(std::istream&amp; is, std::streamsize&amp; len) { constexpr std::streamsize buf_len = 1024; std::array&lt;char, buf_len&gt; buffer = {0}; std::string cell; while (len &gt; 0) { std::streamsize read_len = std::min(len, buf_len); is.getline(&amp;buffer[0], read_len); for (int i = 0; i &lt; read_len; ++i) { if (buffer[i] == ',') { column_names.push_back(std::move(cell)); cell = &quot;&quot;; } else if (buffer[i] == '\n' || buffer[i] == '\0') { column_names.push_back(std::move(cell)); cell = &quot;&quot;; len -= i; column_data_types.resize(column_names.size(), -1); return; } else { cell += buffer[i]; } } len -= read_len; } column_data_types.resize(column_names.size(), -1); } void ParseCSV(std::istream&amp; is) { is.seekg(0, std::ios::end); std::streamsize len = is.tellg(); is.seekg(0, std::ios::beg); auto t1 = std::chrono::steady_clock::now(); ParseHeader(is, len); constexpr std::streamsize buf_len = 1024; std::array&lt;char, buf_len&gt; buffer = {0}; std::string cell; row_type row; std::size_t col_index = 0; while (len &gt; 0) { std::streamsize read_len = std::min(len, buf_len); is.read(&amp;buffer[0], read_len); for (int i = 0; i &lt; read_len; ++i) { if (buffer[i] == ',') { row.push_back(to_data(cell, col_index)); cell = &quot;&quot;; col_index++; } else if (buffer[i] == '\n') { row.push_back(to_data(cell, col_index)); cell = &quot;&quot;; col_index = 0; rows.push_back(std::move(row)); row = {}; } else { cell += buffer[i]; } } len -= read_len; } auto t2 = std::chrono::steady_clock::now(); auto dt = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(t2 - t1); std::cout &lt;&lt; rows.size() &lt;&lt; &quot; element read in &quot; &lt;&lt; dt.count() &lt;&lt; &quot; us\n&quot;; } }; </code></pre> <p>Reading 20628 lines from <a href="https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.tgz" rel="nofollow noreferrer">https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.tgz</a> gives, in my machine:</p> <pre><code>20628 element read in 89734 us </code></pre> <p>Feel free to comment anything!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:23:05.737", "Id": "529373", "Score": "0", "body": "I'm wondering why you have a 2-D array for `rows` _and_ for `columns`. Does it hold the same data twice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:52:35.490", "Id": "529434", "Score": "1", "body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T12:28:31.603", "Id": "529441", "Score": "0", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>It's surprisingly efficient. If I were to implement it myself, I would have gone with a <code>while(std::getline(...))</code> loop, so I always know I am dealing with a whole line at a time, and can pass a <code>std::string_view</code> into the line buffer instead of making a copy of each item into <code>cell</code>. But this was more than twice as slow as your solution, even if I reduce <code>buf_len</code> to just 16. There are a few improvements that could be made that I'll list below, but nothing really impacted performance.</p>\n<h1>Use an <code>enum class</code> for the possible types</h1>\n<p>Instead of using raw integers to represent the type, create an <code>enum class</code> for it:</p>\n<pre><code>enum class type {\n UNKNOWN,\n INT,\n FLOAT,\n STRING,\n};\n\nstd::vector&lt;type&gt; column_data_types;\n</code></pre>\n<p>This avoids magic constants and having to remember the index into <code>data_type</code> for a given type.</p>\n<h1>Remove unused variables</h1>\n<p>The member variable <code>columns</code> is unused, as well as the local variables <code>ptr</code> and <code>ec</code> in <code>to_int()</code> and <code>to_float()</code>. Just remove them.</p>\n<h1>Passing string iterators</h1>\n<p>Instead of calling <code>std::from_chars()</code> with <code>str.data()</code> and <code>str.data() + str.size()</code> as the parameters, just pass <code>str.begin()</code> and <code>str.end()</code>.</p>\n<h1>Avoid unnecessary copies</h1>\n<p>Inside <code>ParseCSV()</code> you build a row in the temporary variable <code>row</code>, and then <code>std::move()</code> that into <code>rows</code>. While this is rather efficient since <code>std::vector</code> has a move constructor, you can avoid this altogether by adding an empty row to <code>rows</code> first, and then add cells to that row:</p>\n<pre><code>row.emplace_back(); // Ensure there is an empty row\n...\nwhile (len &gt; 0) {\n ...\n if (buffer[i] == ',') {\n rows.back().emplace_back(to_data(cell, col_index));\n ...\n } else if (buffer[i] == '\\n') {\n rows.back().emplace_back(to_data(cell, col_index));\n rows.emplace_back(); // This row is done, add a new one\n ...\n } else ...\n</code></pre>\n<h1>Consider making it more generic</h1>\n<p>It would be possible to reduce the amount of code you have to write somewhat by making more use of the type system. Instead of <code>column_data_types</code> being just a vector of <em>indices</em> into <code>data_type</code>, just make it a vector of <code>data_type</code> itself:</p>\n<pre><code>std::vector&lt;data_type&gt; column_data_types;\n</code></pre>\n<p>Then, instead of having <code>to_data()</code> having a <code>switch</code>-statement to call the right <code>to_something()</code> function, create a template <code>to&lt;T&gt;()</code> with overloads for the types you want to support, and <code>to_data()</code> use <a href=\"https://en.cppreference.com/w/cpp/utility/variant/visit\" rel=\"nofollow noreferrer\"><code>std::visit()</code></a> to call the right overload:</p>\n<pre><code>template&lt;typename T&gt;\nT to(const std::string &amp;str) = delete;\n\ntemplate&lt;&gt;\nint to&lt;int&gt;(const std::string &amp;str) {\n int32_t result = 0;\n std::from_chars(str.begin(), str.end(), result);\n return result;\n}\n\n...\n\ndata_type to_data(const std::string &amp;str, std::size_t col_index) {\n if (std::holds_alternative(column_data_types[col_index])) {\n return std::visit([&amp;](auto&amp; type) {\n return to&lt;decltype(type)&gt;(str);\n }, column_data_types[col_index]);\n }\n\n // Else check the string to determine what type it is\n ...\n if (/* it's an int */) {\n column_data_types[col_index] = int{};\n return to&lt;int&gt;(str);\n }\n ... \n}\n</code></pre>\n<p>If you just support three types it's not worth it, but it might pay off when you want to support more types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:50:28.150", "Id": "268435", "ParentId": "268428", "Score": "2" } }, { "body": "<p>Your primitive conversion functions don't report errors. Since your data type is a variant anyway, you could include an error type among them and return an error.</p>\n<p>Use of <code>from_chars</code> is good! These are new, efficient functions.</p>\n<p><code>to_data</code> uses hard-coded numbers in the switch statement and elsewhere. It would be better to use an enumeration type.</p>\n<p>You don't need to <code>break</code> after <code>return</code>. The <code>return</code> itself is enough!</p>\n<p>Why are you using fixed-size buffers for reading the lines?</p>\n<p><code>cell = &quot;&quot;;</code> use <code>{}</code> for an empty string. Converting <code>&quot;&quot;</code> is inefficient because it uses the general string literal constructor! But in this case, just use <code>cell.clear();</code>.</p>\n<p>The code in <code>ParseHeader</code> is pretty slow and laborious. You're reading one character at a time, using a loop over <code>i</code> the index for that matter (use a range-based <code>for</code> loop to do it directly), and pushing the character onto a string until you see the comma. I scan for the comma or separators using standard algorithms and then grab the whole token at once.</p>\n<p>I see <code>ParseCSV</code> is doing the same thing. You don't need to copy the chars into another string, one-at-a-time or otherwise! Find the delimiter, and then you have two pointers to the start and end of the token. That's what <code>from_chars</code> wants!</p>\n<p>It looks like you determine the cell type when reading the first row. That might give false results, if the first value is &quot;1&quot; but it actually supports floating point so the next row has &quot;2.4&quot;. Or, it's not an integer but actually a string, as the second row has &quot;B&quot;.</p>\n<p>Here's my code that splits a string up at the commas. It needs to know the number of fields at compile-time and thus avoids any dynamic memory allocation, but look at the body of the <code>for</code> loop for the actual logic; you can adapt that to whatever collections you are using.</p>\n<pre><code>template &lt;size_t N&gt;\nauto split (char separator, std::string_view input)\n{\n std::array&lt;std::string_view, N&gt; results; \n auto current = input.begin();\n const auto End = input.end();\n for (auto&amp; part : results)\n {\n if (current == End) {\n const bool is_last_part = &amp;part == &amp;(results.back());\n if (!is_last_part) throw std::invalid_argument (&quot;not enough parts to split&quot;);\n }\n // core logic is here\n auto delim = std::find (current, End, separator);\n part = { &amp;*current, size_t(delim-current) };\n current = delim;\n // \n if (delim != End) ++current;\n }\n if (current != End) throw std::invalid_argument (&quot;too many parts to split&quot;);\n return results;\n}\n</code></pre>\n<h2>architecture</h2>\n<p>You code has:</p>\n<ol>\n<li>reading from a file</li>\n<li>separating at delimiters</li>\n<li>converting the tokens to the desired type</li>\n<li>storing those converted tokens</li>\n</ol>\n<p>all mixed together in one piece of code. You may notice from my sample that it <em>only</em> does point 2. Where that line of text came from is irrelevant, and subsequent points are not its responsibility.</p>\n<p>Input doesn't have to come from a file or even a <code>istream</code> object: it can scan a memory-mapped file that's already visible in RAM, or lines already in an array that came across via some message protocol, or literal constants, or anything. The code does not need to be configured for this because it simply does not matter to what this code does, so none of that is part of it. It takes a <code>string_view</code> to process one line.</p>\n<p>I don't store the results in a two-dimensional array of variants, either. I assign a row directly to a normal C++ structure that has named members with full type information. Handling the conversion of strings to the proper types is another, general purpose, piece of code that's unrelated to the task of separating CSV fields. Adding a user-defined type or other previously unused type does not require changing <em>this</em> code, because conversions is not part of it.</p>\n<p><strong>Separations of Concerns</strong> is good. Even if you don't need flexibility, it makes each task simple and testable in isolation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:10:07.097", "Id": "529379", "Score": "0", "body": "Can you benchmark your solution? I tried something similar after reading in a whole line, but it was less efficient than OP's solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:19:23.003", "Id": "529380", "Score": "0", "body": "@G.Sliepen Yes it's _fast_. That's because the separator is a single char, not a string or choice of characters, and because it doesn't allocate any memory on the heap nor copies the strings it finds. I didn't count the time needed to read a line from the file; that is a separate concern and this can be called with a whole file that's been slurped in and \"separated\" at newline, or an array of strings given to my code already in that form." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T02:15:20.150", "Id": "529417", "Score": "0", "body": "@JDługosz Thanks for your feedback, but when I've tried your solution (using ```std::string_view```), it turned out to be slower than the original solution for the reason I don't know. I'll post my two implementations and benchmark result" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T02:28:31.687", "Id": "529418", "Score": "1", "body": "@G.Sliepen (and JDlugosz) Wait, I've benchmarked wrongly. The std::string_view approach definitely improved performance hugely. Posted the result" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:59:42.913", "Id": "268438", "ParentId": "268428", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T11:01:39.227", "Id": "268428", "Score": "2", "Tags": [ "c++", "csv" ], "Title": "C++ Minimal CSV parser" }
268428
<p>I created an input that accepts and formats phone numbers into XXX-XXX-XXX. The user should be able to type numbers and the dashes should insert themselves automatically.</p> <p>Example #1: The user types 1 2 3 4. The input shows 123-4.</p> <p>Example #2: The user types 1 2 3 4 BACKSPACE. The input shows 123. Note the lack of dash!</p> <p>This is my solution with react.js, typescript and use state. I didn't implement validation, that only numeric can be inserted. How can I improve my solution with react, typescript and use state?</p> <p><strong>My solution:</strong></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>import { useState } from "react"; export function PhoneNumberBonus() { const [phone, setPhone] = useState(""); function onChange(value: string) { if (isNonEmptyString(value) &amp;&amp; value.length % 4 == 0 &amp;&amp; value.slice(-1) != "-") { let index: number = value.length - 1; value = addStr(value, index, "-"); setPhone(value); } else { setPhone(value); } } function addStr(str: string, index: number, stringToAdd: string) { return str.substring(0, index) + stringToAdd + str.substring(index, str.length); } function isNonEmptyString(str: string) { return str &amp;&amp; str.length &gt; 0; } return &lt;div&gt;Bonus: Phone Number &lt;input value={phone} onChange={(e) =&gt; onChange(e.target.value)} /&gt; &lt;/div&gt;; }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T06:41:18.563", "Id": "529493", "Score": "0", "body": "Why not use one of the many libraries that are available? https://www.npmjs.com/search?q=react%20phone%20number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:48:00.947", "Id": "529502", "Score": "0", "body": "yes, but I would like to create myself, because I learn react.js" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T11:39:36.577", "Id": "530008", "Score": "0", "body": "You haven't implemented the second example, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T16:09:22.070", "Id": "530027", "Score": "0", "body": "I implemented two examples" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T12:21:43.767", "Id": "268430", "Score": "3", "Tags": [ "react.js", "formatting", "typescript" ], "Title": "Use formats phone numbers into XXX-XXX-XXX" }
268430
<p>I'm new to C++ (not to programming in general), which I want to learn to participate in some programming contests.</p> <p>I solved the <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;category=13&amp;page=show_problem&amp;problem=1130" rel="nofollow noreferrer">Online Judge Minesweeper Challange</a>.</p> <p>Since I'm not familiar with C++, any feedback (including nitpicking) is very welcome.</p> <p>My algorithm:</p> <p>For each field...</p> <ol> <li>Read the dimensions and initialize a 2d-array.</li> <li>Simultainiously read and parse the cells: <ol> <li>If it's not a bomb, continue.</li> <li>Otherwise, set the cell to a negative value, then increase all existing, non-negative neighbours.</li> </ol> </li> <li>Print each value, <code>*</code> for negative numbers (i.e. bombs).</li> </ol> <p>I considered to separate the reading and parsing parts, but then I'd need to traverse the array once more.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; using namespace std; int **parseField(int n, int m); void printField(int **field, int fieldIndex, int n, int m); int main() { int n, m, fieldIndex = 1; while (cin &gt;&gt; n &gt;&gt; m &amp;&amp; !(n == 0 &amp;&amp; m == 0)) { if (fieldIndex &gt; 1) cout &lt;&lt; endl; int **field = parseField(n, m); printField(field, fieldIndex++, n, m); } } int **parseField(int n, int m) { int **field = new int *[n]; for (int i = 0; i &lt; n; i++) field[i] = new int[m]; string line; for (int i = 0; i &lt; n; i++) { cin &gt;&gt; line; for (int j = 0; j &lt; m; j++) { if (line[j] != '*') continue; field[i][j] = -1; for (int k = 0; k &lt; 9; k++) { int x = i + (k / 3) - 1, y = j + (k % 3) - 1; if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= m) continue; if (field[x][y] &gt;= 0) field[x][y]++; } } } return field; } void printField(int **field, int fieldIndex, int n, int m) { cout &lt;&lt; &quot;Field #&quot; &lt;&lt; fieldIndex &lt;&lt; &quot;:&quot; &lt;&lt; endl; for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; m; j++) { if (field[i][j] &lt; 0) cout &lt;&lt; '*'; else cout &lt;&lt; field[i][j]; } cout &lt;&lt; endl; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:19:34.010", "Id": "529549", "Score": "0", "body": "PS. Your code fails for the online Judge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:53:46.817", "Id": "529551", "Score": "0", "body": "Working code: https://codereview.stackexchange.com/q/268521/507" } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<p>The style in C++ is to put the <code>*</code> or <code>&amp;</code> with the <em>type</em>, not the identifier. This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.</p>\n<hr />\n<p>Put the functions in the opposite order, so you don't need to forward-declare them. Note that C++ has overloading, so if your declaration at the top doesn't match the actual function you'll get confusing link-time errors and not a compiler error for this file!</p>\n<hr />\n<p>Don't use <code>new</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new\" rel=\"nofollow noreferrer\">⧺C.149</a> — no naked <code>new</code> or <code>delete</code>.\nUse a <code>std::vector</code> here.</p>\n<p>You are leaking memory: I don't see any <code>delete</code>!</p>\n<pre><code>int **field = parseField(n, m);\nprintField(field, fieldIndex++, n, m);\n</code></pre>\n<p>Every time through the loop, you are dropping <code>field</code> on the floor.</p>\n<hr />\n<p><code> int n, m, fieldIndex = 1;</code><br />\nDon't declare multiple variables in one statement. Don't declare all your variables at the top, but declare where first needed and when you are ready to give it a value.</p>\n<p>Here, the nature of <code>cin</code> input means you have to declare <code>m</code> and <code>n</code> before making that call. That's not the usual case.</p>\n<h1>architectural</h1>\n<p>Your <code>parse</code> and <code>print</code> are being passed the raw pointer thing, <em>and</em> the two sizes. Those should be combined into a single data structure, say a class named <code>Field</code>. Then these two function can be <strong>member functions</strong> of that class.</p>\n<p>Your data structure is laborious and unnecessary. Back it with a <code>std::vector&lt;int&gt;</code>, and also store the height and width, all as members of the class. Write a lookup function that takes two indexes (r,c) and calculates a linear value <code>r*width+c</code> and feeds that to the underlying vector.</p>\n<p>Use a type alias for the cell type rather than <code>int</code>. You can easily change it to (say) <code>int8_t</code> and see if it's faster as well as smaller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:49:33.127", "Id": "268442", "ParentId": "268436", "Score": "3" } }, { "body": "<p>Nit-Picking: You have come to the correct place</p>\n<hr />\n<p>First, your whole style is more C rather C++ like. I don't see any abstraction or encapsulation.</p>\n<p>Though, C++ can include C as (mostly) a subset. The styles of how the language is used are different. This is C like more than C++ like. The things that stand out are:</p>\n<ul>\n<li>passing pointers (C++ prefers references or smart pointer or containers).</li>\n<li>const correctness (Adding this later is a pain, so do it upfront).</li>\n<li>Abstraction (Wrap your data in a class)</li>\n</ul>\n<hr />\n<p>Memory Management.</p>\n<p>Total fail you leak memory. For every new, there should be a call to delete. Or you should use higher-level constructs to handle the memory management automatically. If you want fast sure use C to avoid this.</p>\n<hr />\n<p>Arrays:</p>\n<p>Speed:</p>\n<p>You use an array of arrays.<br />\nWhy not allocate an <code>n*m</code> block of integers than calculate the position in the block. This will save on allocation time and be faster on lookup.</p>\n<p>Support:</p>\n<p>In C++ we don't usually manually allocate memory like this. It is easier (and safer) to use the existing containers. So I would use <code>std::vector&lt;int&gt;</code> to handle the memory allocation for me.</p>\n<hr />\n<h2>NitPick Section</h2>\n<p>Don't do this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>Bad habit. Even doing this is a source file is bad. It will eventually come back to bite you.</p>\n<p>see: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is &quot;using namespace std;&quot; considered bad practice?</a></p>\n<hr />\n<p>Sure looks very C like interface:</p>\n<pre><code>int **parseField(int n, int m);\nvoid printField(int **field, int fieldIndex, int n, int m);\n</code></pre>\n<p>I would have written it like this:</p>\n<pre><code>class Data\n{\n public:\n Data(int n, int m);\n print(int fieldIndex);\n};\n</code></pre>\n<p>No need to accidentally pass in the wrong <code>n</code> and <code>m</code> values to the second function when you know they are going to be the same for both calls.</p>\n<hr />\n<p>One line per variable please.</p>\n<pre><code> int n, m, fieldIndex = 1;\n</code></pre>\n<p>This is just lazy. Also it makes it harder to read and has no real benefit.</p>\n<hr />\n<p>That's a bit hard to read.</p>\n<pre><code> while (cin &gt;&gt; n &gt;&gt; m &amp;&amp; !(n == 0 &amp;&amp; m == 0))\n</code></pre>\n<p>Use the <code>Self Documenting Code</code> principle.</p>\n<pre><code> while (cin &gt;&gt; n &gt;&gt; m &amp;&amp; isValidSize(n, m))\n</code></pre>\n<hr />\n<p>Always use braces around sub blocks (even if they are one line).</p>\n<pre><code> if (fieldIndex &gt; 1)\n cout &lt;&lt; endl;\n</code></pre>\n<p>This will save you from so many mistakes in the long term. I just wish it was a required part of the language.</p>\n<pre><code> if (fieldIndex &gt; 1) {\n cout &lt;&lt; endl;\n }\n</code></pre>\n<hr />\n<p>This is a performance issue.</p>\n<pre><code> cout &lt;&lt; endl;\n</code></pre>\n<p>The <code>std::endl</code> puts a newline character onto the stream then flushes the stream. Forcing the stream to flush is expensive. You should not be doing this unless there is a very good reason. The system will do this automatically when a flush is needed so there is rarely a need for you to do it.</p>\n<p>Replace with:</p>\n<pre><code> cout &lt;&lt; &quot;\\n&quot;; // Yes use a string.\n // If you try and print a character it\n // builds a string internally making it\n // slower.\n</code></pre>\n<hr />\n<p>This the C way of declaring a variable:</p>\n<pre><code> int **field = parseField(n, m);\n</code></pre>\n<p>In C++ types are much more important than in C. As a result, we keep all the type information together:</p>\n<pre><code> int** field = parseField(n, m);\n</code></pre>\n<hr />\n<p>I don't see a delete for this:</p>\n<pre><code> int **field = new int *[n];\n</code></pre>\n<p>You may be saying to yourself well I did not want to do that because of speed. I am not sure that's a good argument. Because each time through the <code>while</code> loop in main you are allocating a field. So you are doing a whole bunch of memory allocation (which is the expensive part). Deallocation though not free is relatively cheap in comparison (nothing in the standard requires this,but it is what I have seen from looking at implementations of memory managers (you keep lists of similar sized objects that have been deleted for potential reuse)).</p>\n<p>C++ designers realized a long time ago that objects are often reused a lot (or objects of a similar size are re-used a lot). As a result the memory management can (in good implementations) keep track of recently deleted objects under the assumption that they will quickly be reused. In this design I can quite easily see a lot of same size (or similar size) arrays being allocated and the memory management could take advantage of this to make the reallocation quicker than if the memory was split out of the main resevour.</p>\n<p>But as always worth testing.</p>\n<hr />\n<p>Prefer the prefix <code>++</code>.</p>\n<pre><code> for (int i = 0; i &lt; n; i++)\n</code></pre>\n<p>Try this:</p>\n<pre><code> for (int i = 0; i &lt; n; ++i)\n</code></pre>\n<p>For integers, there is absolutely no difference. But in C++ we use iterators a lot. Iterators are not always pointers they can be objects so the prefix version is slightly faster (because of the standard pattern of how they are written).</p>\n<p>So prefer to always use the prefix version that way you always get the optimal increment technique no matter what the type. Since a lot of times changes to C++ are simply changing a type (without changing any other code) this means your code will continue to be optimal.</p>\n<p>see: <a href=\"https://stackoverflow.com/a/3846374/14065\">How to overload the operator++ in two different ways for postfix a++ and prefix ++a?</a></p>\n<hr />\n<p>How I would do it:</p>\n<pre><code>#include &lt;memory&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\n\n// Each member of the grid is either a mine\n// which is printed as a '*' or empty which is represented by a number.\nstruct MineCount\n{\n bool mine;\n int count;\n};\n\n// We need to save the size of the grid.\nusing Size = std::pair&lt;int, int&gt;;\n\n// MineField\n// Knows about mines and counts only.\n//\n// The maximum size of the field is [100 * 100]\n// But to maximize speed we use contiguous piece of memory\n// rather than an array of arrays. This reduces the cost\n// of memory access as we only have to do one accesses to get\n// the required location.\n//\n// To simplify the code we add a border of cells around the\n// minefield. So all accesses to the grid is increment by 1\n// in both X and Y dimensions. This allows us to increment\n// the count in all adjoining fields without having to check if\n// we are on the border of the field and thus incrementing\n// beyond the edge of the array\n//\n// This should make the code faster and simpler to read.\nclass MineField\n{\n Size size;\n std::vector&lt;MineCount&gt; mines;\n\n static constexpr int maxSize = 103;\n\n int index(int x, int y) {return x + (y * maxSize);}\n public:\n MineField()\n : size{0, 0}\n , mines(maxSize * maxSize)\n {}\n\n // Re-Use a minefield.\n // Reset only the state needed (previously used).\n // without having to reallocate the array.\n void reset(int n, int m)\n {\n for(int xLoop = 0; xLoop &lt; size.first; ++xLoop) {\n for(int yLoop = 0; yLoop &lt; size.second; ++ yLoop) {\n mines[index(xLoop, yLoop)] = {false, 0};\n }\n }\n // Store Size +2 as we have an extra border around\n // the field.\n size.first = n + 2;\n size.second = m + 2;\n }\n // Add a mine to location X, Y\n void add(int x, int y)\n {\n ++x;\n ++y;\n\n // We have a mine in this square.\n mines[index(x, y)].mine = true;\n\n // Increment the count of all surrounding squares.\n // I was tempted to manually onroll this loop.\n for(int xLoop = -1; xLoop &lt; 2; ++xLoop) {\n for(int yLoop = -1; yLoop &lt; 2; ++yLoop) {\n ++mines[index(x + xLoop, y + yLoop)].count;\n }\n }\n }\n\n // Get the character for a specific location.\n char get(int x, int y) const\n {\n ++x;\n ++y;\n\n if (mines[index(x, y)].mine) {\n return '*';\n }\n return '0' + mines[index(x, y)].count;\n }\n};\n\n// Wrapper class that understands about reading and writing\n// to a stream for a minefield.\n// This class does not know about the extra border on the field.\nclass Field\n{\n Size size;\n MineField mineField;\n public:\n void reset(int n, int m);\n\n // Functionality to read and write. :-)\n void read(std::istream&amp; stream);\n void write(std::ostream&amp; stream) const;\n\n // Standard friend functions to make\n // reading and writting look like C++.\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Field&amp; data) {\n data.read(stream);\n return stream;\n }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Field const&amp; data) {\n data.write(stream);\n return stream;\n }\n};\n\nvoid Field::reset(int n, int m)\n{\n size = {n, m};\n mineField.reset(n, m);\n}\n\nvoid Field::read(std::istream&amp; stream)\n{\n // Assumes input file is correctly formatted.\n // The operator&gt;&gt; will ignore white space so we\n // don't need to deal with new line characters.\n // You can probably make it faster by manually handling this.\n for(int y = 0; y &lt; size.second; ++y) {\n for(int x = 0; x &lt; size.first; ++x) {\n char c;\n std::cin &gt;&gt; c;\n // Only care about '*'\n // Everything else is a '.' and can be ignored.\n if (c == '*') {\n mineField.add(x, y);\n }\n }\n }\n}\nvoid Field::write(std::ostream&amp; stream) const\n{\n for(int y = 0; y &lt; size.second; ++y) {\n for(int x = 0; x &lt; size.first; ++x) {\n std::cout &lt;&lt; mineField.get(x, y);\n }\n stream &lt;&lt; &quot;\\n&quot;;\n }\n}\n\nbool isField(int n, int m)\n{\n return n != 0 &amp;&amp; m != 0;\n}\n\nint main()\n{\n // Only allocate the memory once.\n // Will reuse inside the loop by calling reset.\n Field field;\n int loop = 0;\n\n int n;\n int m;\n\n while (std::cin &gt;&gt; n &gt;&gt; m &amp;&amp; isField(n,m)) {\n // Reset then read the new field.\n field.reset(m, n);\n std::cin &gt;&gt; field;\n\n // The Judge does not want a trailing empty line.\n // So print it before each new field. But not before\n // the first one.\n if (loop != 0) {\n std::cout &lt;&lt; &quot;\\n&quot;;\n }\n // Increment count and output.\n ++loop;\n std::cout &lt;&lt; &quot;Field #&quot; &lt;&lt; loop &lt;&lt; &quot;:\\n&quot;\n &lt;&lt; field;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:57:36.893", "Id": "268475", "ParentId": "268436", "Score": "3" } } ]
{ "AcceptedAnswerId": "268442", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:52:25.353", "Id": "268436", "Score": "3", "Tags": [ "c++", "beginner", "programming-challenge", "minesweeper" ], "Title": "Online Judge 10189: Minesweeper (C++)" }
268436
<p>This code replaces each element in an array with the product of every other element in the array but the current element, without using division. So, for the array [5,2,3], the program outputs [6,18,108].</p> <p>The code is below, but in essence, it iterates through each element, and sets the element to the product of the other elements.</p> <p>So, for the array [5,2,3], it replaces the first element with the product of 2*3, so the array becomes [6,2,3]. Then it replaces the second element with the product of 6 and 3, so the array becomes [6,18,3]. Finally, it replaces the third element with the product of 6 and 18, so the array becomes [6,18,108].</p> <p>Looking for general suggestions here, like how to improve the time complexity (<a href="https://codereview.stackexchange.com/questions/267846/replace-array-values-with-product-of-all-other-values">someone suggested using some sort of different type of product or something</a> but I don't know how to do that)</p> <pre><code>// productOfArray // This function calculates the product of every value in the given array. function productOfArray(array: number[]) { let product = 1; for (let x of array) product *= x; // should I be using *= or write product = product * x? return product; } // replaceWithProduct // This function replaces each element in an array with the product of // every other element in the array but the current element. function replaceWithProduct(array: number[]) { for (let i=0; i&lt;array.length; i++) { let arrayWithoutElement = array.slice(0,i).concat(array.slice(i+1,array.length)); array[i] = productOfArray(arrayWithoutElement); } return array; } // Test the above functions. let array = [5,2,3]; console.assert(productOfArray(array) === 30); let newArray = replaceWithProduct(array); let testArray = [6,18,108]; // This is what newArray should be. for (let i=0; i&lt;testArray.length; i++) console.assert(newArray[i] === testArray[i]); console.log(&quot;Finished&quot;); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T23:38:12.343", "Id": "529483", "Score": "5", "body": "I'm not convinced that the result you are aiming for is the result that the \"question\" is aiming for. I'd expect `[5, 2, 3]` to be `[6, 15, 10]` by the description ..." } ]
[ { "body": "<p>The <code>productOfArray</code> could be implemented by <a href=\"https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a>.</p>\n<pre><code>function productOfArray(array: number[]): number {\n return array.reduce((product, e) =&gt; product *= e, 1)\n}\n</code></pre>\n<p>The <code>reduce</code> method could also be used to implement the <code>replaceWithProduct</code> function, if you reorganize the algorithm a bit.</p>\n<pre><code>function replaceWithProduct(source: number[]): number[] {\n return source.reduce(reducer, []);\n}\n\nfunction reducer(acc: number[], e: number, i: number, source: number[]): number[] {\n return acc.concat(productOfArray(acc) * productOfArray(source.slice(i + 1)));\n}\n</code></pre>\n<p>It calculates a sprecific element by mulitplying the product of the already considered elements with all <em>rest</em> elements. This approach is only simpler, if you are familar with <code>reduce</code>, I guess.</p>\n<p>To minimize the computations, you could cache and update the products instead of recalculating them in every <code>reducer</code> call.</p>\n<pre><code>function replaceWithProduct(source: number[]): number[] {\n return source.reduce(withReducer(source), []);\n}\n\nfunction withReducer(source: number[]): (acc: number[], e: number) =&gt; number[] {\n let lastAccProduct = 1;\n let lastRestProduct = productOfArray(source);\n\n return (acc: number[], e: number): number[] =&gt; {\n lastRestProduct /= e;\n const currentProduct = lastAccProduct * lastRestProduct;\n lastAccProduct *= currentProduct;\n return acc.concat(currentProduct);\n };\n}\n</code></pre>\n<p>The example encapsulates the cache values within a <a href=\"https://en.wikipedia.org/wiki/Higher-order_function\" rel=\"nofollow noreferrer\">High Order Function</a>, which means, that <code>withReducer</code> is a function, which returns another function. If the concept is new to you, it's possibly hard to understand.</p>\n<hr />\n<p>With the restriction of avoiding division, you need to compute the <em>rest products</em> by processing the array from right to left. Therefore you can use <code>reduceRight</code>. The complexity keeps the same as with last example.</p>\n<pre><code>function replaceWithProduct(source: number[]): number[] {\n return source.reduce(withReducer(source), []);\n}\n\nfunction withReducer(source: number[]): (acc: number[], e: number) =&gt; number[] {\n const restProducts = calculateRestProducts(source);\n let accProduct = 1;\n\n return (acc: number[], e: number): number[] =&gt; {\n const currentProduct = accProduct * restProducts.shift();\n accProduct *= currentProduct;\n return acc.concat(currentProduct);\n };\n}\n\nfunction calculateRestProducts(source: number[]): number[] {\n let lastRestProduct = 1;\n return source\n .slice(1)\n .reduceRight((acc, e) =&gt; acc.concat(lastRestProduct *= e), [1])\n .reverse();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:20:24.950", "Id": "529466", "Score": "0", "body": "Why wouldn't I need to recalculate the product?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T23:39:31.330", "Id": "529484", "Score": "0", "body": "The code presented here is not well-behaved when the input array contains a 0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T00:52:20.877", "Id": "529486", "Score": "0", "body": "That, and your code feels hacky." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:23:44.130", "Id": "529500", "Score": "0", "body": "I guess, if you are familar with functional programming concepts, it's straighforward. The introduction of the cache variables reduces the complexity from n^2 to n, because the full recalculation of the product would consinder (n-1) elements, which isn't necessary with the cache variables `lastAccProduct`, `lastRestProduct`. Since there was nothing said about the zero handling, I didn't cover it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T05:37:45.377", "Id": "268459", "ParentId": "268437", "Score": "3" } }, { "body": "<p>Do you actually need to replace the result into the original array? That makes it unnecessarily complicated in my opinion (and is bad practice). Why not just return a new array?</p>\n<p>The logic can also be simplified by just calculating the product of all numbers and then dividing that with each number in turn:</p>\n<pre><code>function productsOfOthers(numbers) {\n const product = numbers.reduce((product, e) =&gt; product * e, 1);\n return numbers.map(n =&gt; product / n);\n}\n</code></pre>\n<p>And if you really need it to be the same array at the end, wrap it in a function that copies the result back:</p>\n<pre><code>function copyIntoArray(source, target) {\n source.forEach((n, i) =&gt; target[i] = n);\n\n // Could be left out, if you know/assume they are the same length,\n // as it is in this case\n if (target.length &gt; source.length) {\n target.length = source.length;\n }\n}\n\nfunction replaceWithProduct(numbers) {\n const products = productsOfOthers(numbers);\n copyIntoArray(products, numbers);\n\n // Could just as well not return anything since you are reusing the array anyway\n return numbers;\n}\n</code></pre>\n<p>This is the <span class=\"math-container\">\\$O(2n)\\$</span> (or <span class=\"math-container\">\\$O(3n)\\$</span> in case of the copying) = <span class=\"math-container\">\\$O(n)\\$</span> instead of (i believe) <span class=\"math-container\">\\$O(n^2)\\$</span> due to the repeated multiplication.</p>\n<p>One draw back maybe a slight risk of overflow, however if the product of all numbers overflow, it's very likely that the product of all except one would overflow too anyway. Or use BigInt.</p>\n<hr />\n<h1>If zeros are allowed...</h1>\n<p>This makes it a bit more complicated, however one could write a product method, that counts the zeros and ignores them for the product:</p>\n<pre><code>function product(numbers) {\n return numbers.reduce(\n ({product, zeros}, n) =&gt; \n n === 0 ? \n {product, zeros: zeros + 1} :\n {product: product * n, zeros}, \n {product: 1, zeros: 0}\n );\n}\n</code></pre>\n<p>And then build the result based on the number of zeros counted:</p>\n<pre><code>function productsOfOthers(numbers) {\n const {product, zeros} = product(numbers);\n switch (zeros) {\n case 0: \n return numbers.map(n =&gt; product / n);\n case 1:\n return numbers.map(n =&gt; n === 0 ? product : 0)\n default:\n return Array(numbers.length).fill(0);\n }\n}\n</code></pre>\n<hr />\n<h1>When division isn't allowed</h1>\n<p>In this case I'd avoid all the expensive slicing and concatenating and write a product function that ignores a specific index:</p>\n<pre><code>function product(numbers, ignoreIndex) {\n return numbers.reduce(\n (product, n, index) =&gt; \n index === ignoreIndex ? product : product * n, \n 1\n );\n}\n\nfunction productsOfOthers(numbers) {\n return numbers.map((_, index, array) =&gt; product(array, index));\n}\n</code></pre>\n<hr />\n<p>And since I seem to be on a roll, here is a version that reuses the product of the first numbers. I moved away from functional programming, because I believe it would become too difficult to read in this case.</p>\n<pre><code>function productFromIndex(numbers, index) {\n let product = 1;\n for (let i = index; i &lt; numbers.length; i++) {\n product *= numbers[i];\n }\n return product;\n}\n\nfunction productsOfOthers(numbers) {\n let previousProduct = 1;\n const result = [];\n for (let i = 0; i &lt; numbers.length; i++) {\n result[i] = previousProduct * productFromIndex(numbers, i + 1);\n previousProduct *= numbers[i];\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T22:43:14.650", "Id": "529481", "Score": "0", "body": "Forgot to mention: The original challenge does not allow division." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T23:28:56.977", "Id": "529482", "Score": "0", "body": "This algorithm utterly fails if the array contains zeros. Even if you attempt to avoid dividing by zero, having two (or more) zeros in the array should give a result of all zeros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T05:38:48.717", "Id": "529490", "Score": "0", "body": "@Vogel612 I've added some alternatives." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T05:44:24.437", "Id": "529491", "Score": "0", "body": "@moonman239 I've added some alternatives." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T19:07:57.067", "Id": "268485", "ParentId": "268437", "Score": "2" } }, { "body": "<blockquote>\n<p>There are two ways of constructing a software design: One way is to\nmake it so simple that there are obviously no deficiencies, and the\nother way is to make it so complicated that there are no obvious\ndeficiencies.</p>\n<p>— C. A. R. Hoare</p>\n</blockquote>\n<pre><code>const productWithout = (arr: number[], idx: number) =&gt;\n arr.reduce((acc, v, idx2) =&gt; (idx === idx2 ? acc : v * acc), 1);\n\nconst replaceIn = (arr: number[], idx: number, v: number) =&gt;\n arr.map((r, idx2) =&gt; (idx === idx2 ? v : r));\n\nconst replaceWithProduct = (arr: number[]) =&gt;\n arr.reduce(\n (acc, _, idx) =&gt; replaceIn(acc, idx, productWithout(acc, idx)),\n arr\n );\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T18:30:08.883", "Id": "268578", "ParentId": "268437", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:58:46.427", "Id": "268437", "Score": "2", "Tags": [ "typescript" ], "Title": "This code replaces each element of an array with the product of every element of the array except the current one. Suggestions for improvement?" }
268437
<p>I want to check null values in excel files where there are many sub folders. I have wrote a python code to check the null values in excel files in each and every folder and the code was working fine but I need to simplify the code.</p> <pre><code>import os ,uuidtre import numpy as np import pandas as pd import logging path =r&quot;C:\Users\Documents\python\Emp&quot; files = os.listdir(path) for filename in files: pathchild=path+'\\'+filename file = os.listdir(pathchild) files_xls = [f for f in file if f[-4:]== 'xlsx' ] child_folders= [f for f in file if f[-4:]!= 'xlsx'] for f1 in files_xls: filepath=pathchild+'\\'+f1 df = pd.read_excel(filepath, engine='openpyxl') count_nan = df.isnull().sum().sum() logging.basicConfig(filename='nanTest.log', level=logging.INFO,format='%(message)s') if count_nan ==0: none=' No none value in the excel file' else: none=' There is none values founded in the excel file' output='File name: '+ f1, 'File path: '+ filepath, none logging.info(output) for f2 in child_folders: patha=pathchild+'\\'+f2 file1 = os.listdir(patha) files_xls1 = [f for f in file1 if f[-4:]== 'xlsx'] for f3 in files_xls1: filechildpath=patha+'\\'+f3 df = pd.read_excel(filechildpath, engine='openpyxl') count_nan = df.isnull().sum().sum() if count_nan ==0: none=' No none value in the excel file' else: none=' There is none values founded in the excel file' output='File name: '+ f3,'File path: '+ filepath, none logging.info(output) </code></pre>
[]
[ { "body": "<p>Use <code>print()</code> or <code>write()</code> for normal program output. The <code>logging</code> module is generally for recording information about how the program is running, e.g., for debugging, performance monitoring, etc.</p>\n<p>I'd recommend using <code>pathlib</code> in the standard library. <code>Path.rglob()</code> would be useful, it recursively searches directories for files with names that match a pattern, such as &quot;*.xlsx&quot;. Using it lets you eliminate the nested loops and a lot of the file/path handling code.</p>\n<p><code>pd.read_excel()</code> accepts a <code>pathlib.Path</code> for the first argument.</p>\n<p>The code collects the counts and path for each file, so the information can be sorted. This makes it easier to see which files have nulls, because they are grouped together.</p>\n<p>Use <code>f-strings</code> instead of string concatenation.</p>\n<p>I don't have excel files on this machine, so this code isn't tested:</p>\n<pre><code>import pandas as pd\nimport pathlib\n\nnull_counts = []\n\nstart_path = pathlib.Path(r&quot;C:\\Users\\Documents\\python\\Emp&quot;)\n\nfor file_path in start_path.rglob('*.xlsx'):\n\n df = pd.read_excel(file_path, engine='openpyxl')\n count_nan = df.isnull().sum().sum()\n\n null_counts.append((count_nan, file_path))\n\n\nnull_counts.sort(reverse=True)\n\nwith open('nanTest.log', 'wt') as output:\n for count, filepath in null_counts:\n print(f&quot;{count:5} {filepath}&quot;, file=output)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T20:29:54.690", "Id": "268451", "ParentId": "268439", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:07:35.237", "Id": "268439", "Score": "1", "Tags": [ "python-3.x" ], "Title": "Python code to check the null values in excel files" }
268439
<p>After implementing a serial CLOCK second-chance cache in C++ without having enough rope to shoot myself in the foot, decided to dive into Javascript through NodeJs and write an asynchronous one. I think on basic functionality it's nearly complete but there might be some things that I've missed on implementation and unit testing. Also what kind of design pattern could be better? I added Promise-based and multiple key request based versions of get and set methods.</p> <p>Edit: using new Map instead of plain object for the mapping doubled the cache miss performance, lowered its latency for both reads and writes.</p> <p>Implementation: (<a href="https://github.com/tugrul512bit/LruJS/blob/main/lrucache.js" rel="nofollow noreferrer">single file source</a> )</p> <pre><code>'use strict'; /* * cacheSize: number of elements in cache, constant, must be greater than or equal to number of asynchronous accessors / cache misses * callbackBackingStoreLoad: user-given cache(read)-miss function to load data from datastore * takes 2 parameters: key, callback * example: * async function(key,callback){ * redis.get(key,function(data,err){ * callback(data); * }); * } * callbackBackingStoreSave: user-given cache(write)-miss function to save data to datastore * takes 3 parameters: key, value, callback * example: * async function(key,value,callback){ * redis.set(key,value,function(err){ * callback(); * }); * } * elementLifeTimeMs: maximum miliseconds before an element is invalidated, only invalidated at next get() or set() call with its key * flush(): all in-flight get/set accesses are awaited and all edited keys are written back to backing-store. flushes the cache. * reload(): evicts all cache to reload new values from backing store * reloadKey(): only evicts selected item (to reload its new value on next access) * */ let Lru = function(cacheSize,callbackBackingStoreLoad,elementLifeTimeMs=1000,callbackBackingStoreSave){ const me = this; const aTypeGet = 0; const aTypeSet = 1; const maxWait = elementLifeTimeMs; const size = parseInt(cacheSize,10); const mapping = new Map(); const mappingInFlightMiss = new Map(); const bufData = new Array(size); const bufVisited = new Uint8Array(size); const bufEdited = new Uint8Array(size); const bufKey = new Array(size); const bufTime = new Float64Array(size); const bufLocked = new Uint8Array(size); for(let i=0;i&lt;size;i++) { let rnd = Math.random(); mapping.set(rnd,i); bufData[i]=&quot;&quot;; bufVisited[i]=0; bufEdited[i]=0; bufKey[i]=rnd; bufTime[i]=0; bufLocked[i]=0; } let ctr = 0; let ctrEvict = parseInt(cacheSize/2,10); const loadData = callbackBackingStoreLoad; const saveData = callbackBackingStoreSave; let inFlightMissCtr = 0; // refresh all items time-span in cache this.reload=function(){ for(let i=0;i&lt;size;i++) { bufTime[i]=0; } }; // refresh item time-span in cache by triggering eviction this.reloadKey=function(key){ if(mapping.has(key)) { bufTime[mapping[key]]=0; } }; // get value by key this.get = function(keyPrm,callbackPrm){ // aType=0: get access(keyPrm,callbackPrm,aTypeGet); }; // set value by key (callback returns same value) this.set = function(keyPrm,valuePrm,callbackPrm){ // aType=1: set access(keyPrm,callbackPrm,aTypeSet,valuePrm); }; // aType=0: get // aType=1: set function access(keyPrm,callbackPrm,aType,valuePrm){ const key = keyPrm; const callback = callbackPrm; const value = valuePrm; // stop dead-lock when many async get calls are made if(inFlightMissCtr&gt;=size) { setTimeout(function(){ // get/set access(key,function(newData){ callback(newData); },aType,value); },0); return; } // if key is busy, then delay the request towards end of the cache-miss completion if(mappingInFlightMiss.has(key)) { setTimeout(function(){ // get/set access(key,function(newData){ callback(newData); },aType,value); },0); return; } if(mapping.has(key)) { // slot is an element in the circular buffer of CLOCK algorithm let slot = mapping.get(key); // RAM speed data if((Date.now() - bufTime[slot]) &gt; maxWait) { // if slot is locked by another operation, postpone the current operation if(bufLocked[slot]) { setTimeout(function(){ access(key,function(newData){ callback(newData); },aType,value); },0); } else // slot is not locked and its lifespan has ended { // if it was edited, update the backing-store first if(bufEdited[slot] == 1) { bufLocked[slot] = 1; bufEdited[slot]=0; mappingInFlightMiss.set(key,1); // lock key inFlightMissCtr++; // update backing-store, this is async saveData(bufKey[slot],bufData[slot],function(){ mappingInFlightMiss.delete(key); // unlock key bufLocked[slot] = 0; inFlightMissCtr--; mapping.delete(key); // disable mapping for current key // re-simulate the access, async access(key,function(newData){ callback(newData); },aType,value); }); } else { mapping.delete(key); // disable mapping for current key access(key,function(newData){ callback(newData); },aType,value); } } } else // slot life span has not ended { bufVisited[slot]=1; bufTime[slot] = Date.now(); // if it is a &quot;set&quot; operation if(aType == aTypeSet) { bufEdited[slot] = 1; // later used when data needs to be written to data-store (write-cache feature) bufData[slot] = value; } callback(bufData[slot]); } } else { // datastore loading + cache eviction let ctrFound = -1; let oldVal = 0; let oldKey = 0; while(ctrFound===-1) { // give slot a second chance before eviction if(!bufLocked[ctr] &amp;&amp; bufVisited[ctr]) { bufVisited[ctr]=0; } ctr++; if(ctr &gt;= size) { ctr=0; } // eviction conditions if(!bufLocked[ctrEvict] &amp;&amp; !bufVisited[ctrEvict]) { // eviction preparations, lock the slot bufLocked[ctrEvict] = 1; inFlightMissCtr++; ctrFound = ctrEvict; oldVal = bufData[ctrFound]; oldKey = bufKey[ctrFound]; } ctrEvict++; if(ctrEvict &gt;= size) { ctrEvict=0; } } // user-requested key is now asynchronously in-flight &amp; locked for other operations mappingInFlightMiss.set(key,1); // eviction function. least recently used data is gone, newest recently used data is assigned let evict = function(res){ mapping.delete(bufKey[ctrFound]); bufData[ctrFound]=res; bufVisited[ctrFound]=0; bufKey[ctrFound]=key; bufTime[ctrFound]=Date.now(); bufLocked[ctrFound]=0; mapping.set(key,ctrFound); callback(res); inFlightMissCtr--; mappingInFlightMiss.delete(key); }; // if old data was edited, send it to data-store first, then fetch new data if(bufEdited[ctrFound] == 1) { if(aType == aTypeGet) bufEdited[ctrFound] = 0; // old edited data is sent back to data-store saveData(oldKey,oldVal,function(){ if(aType == aTypeGet) loadData(key,evict); else if(aType == aTypeSet) evict(value); }); } else { if(aType == aTypeSet) bufEdited[ctrFound] = 1; if(aType == aTypeGet) loadData(key,evict); else if(aType == aTypeSet) evict(value); } } }; this.getAwaitable = function(key){ return new Promise(function(success,fail){ me.get(key,function(data){ success(data); }); }); } this.setAwaitable = function(key,value){ return new Promise(function(success,fail){ me.set(key,value,function(data){ success(data); }); }); } // as many keys as required can be given, separated by commas this.getMultiple = function(callback, ... keys){ let result = []; let ctr1 = keys.length; for(let i=0;i&lt;ctr1;i++) result.push(0); let ctr2 = 0; keys.forEach(function(key){ let ctr3 = ctr2++; me.get(key,function(data){ result[ctr3] = data; ctr1--; if(ctr1==0) { callback(result); } }); }); }; // as many key-value pairs ( in form of { key:foo, value:bar } ) can be given, separated by commas this.setMultiple = function(callback, ... keyValuePairs){ let result = []; let ctr1 = keyValuePairs.length; for(let i=0;i&lt;ctr1;i++) result.push(0); let ctr2 = 0; keyValuePairs.forEach(function(pair){ let ctr3 = ctr2++; me.set(pair.key,pair.value,function(data){ result[ctr3] = data; ctr1--; if(ctr1==0) { callback(result); } }); }); }; // as many keys as required can be given, separated by commas this.getMultipleAwaitable = function(... keys){ return new Promise(function(success,fail){ me.getMultiple(function(results){ success(results); }, ... keys); }); }; // as many key-value pairs ( in form of { key:foo, value:bar } ) can be given, separated by commas this.setMultipleAwaitable = function(... keyValuePairs){ return new Promise(function(success,fail){ me.setMultiple(function(results){ success(results); }, ... keyValuePairs); }); }; // push all edited slots to backing-store and reset all slots lifetime to &quot;out of date&quot; this.flush = function(callback){ function waitForReadWrite(callbackW){ // if there are in-flight cache-misses cache-write-misses or active slot locks, then wait if(mappingInFlightMiss.size &gt; 0 || bufLocked.reduce((e1,e2)=&gt;{return e1+e2;}) &gt; 0) { setTimeout(()=&gt;{ waitForReadWrite(callbackW); },10); } else callbackW(); } waitForReadWrite(async function(){ for(let i=0;i&lt;size;i++) { bufTime[i]=0; if(bufEdited[i] == 1) { // less concurrency pressure, less failure await me.setAwaitable(bufKey[i],bufData[i]); } } callback(); // flush complete }); }; }; exports.Lru = Lru; </code></pre> <p>Unit testing:</p> <pre><code>&quot;use strict&quot;; console.log(&quot;tests will take several seconds. results will be shown at end.&quot;); let Lru = require(&quot;./lrucache.js&quot;).Lru; let benchData = {hits:0, misses:0, total:0, expires:0, evict:0, evictCtr:0, access50:0, miss50:0}; let errorCheck = { &quot;cache_hit_test&quot;:&quot;failed&quot;, &quot;cache_miss_test&quot;:&quot;failed&quot;, &quot;cache_expire_test&quot;:&quot;failed&quot;, &quot;cache_eviction_test&quot;:&quot;failed&quot;, &quot;cache_50%_hit_ratio&quot;:&quot;failed&quot; }; process.on('exit',function(){ console.log(errorCheck); }); let cache = new Lru(1000, async function(key,callback){ if(key.indexOf(&quot;cache_eviction_test&quot;)===-1 &amp;&amp; key.indexOf(&quot;cache_50_hit_ratio_test&quot;)===-1) setTimeout(function(){ callback(key+&quot; processed&quot;); if(key === &quot;cache_miss_test&quot;) { errorCheck[key]=&quot;ok&quot;; } if(key === &quot;cache_hit_test&quot;) { benchData.misses++; } if(key === &quot;cache_expire_test&quot;) { benchData.expires++; if(benchData.expires===2) errorCheck[key]=&quot;ok&quot;; } },1000); else if(key === &quot;cache_eviction_test&quot;) { callback(key+&quot; processed&quot;); benchData.evict++; if(benchData.evict === 2) errorCheck[key]=&quot;ok&quot;; } else { callback(key+&quot; processed&quot;); if(key.indexOf(&quot;cache_50_hit_ratio_test&quot;)!==-1) { benchData.miss50++; } } },1000); cache.get(&quot;cache_miss_test&quot;,function(data){ }); for(let i=0;i&lt;5;i++) { cache.get(&quot;cache_hit_test&quot;,function(data){ benchData.total++; if(benchData.total - benchData.misses === 4 &amp;&amp; benchData.misses === 1) { errorCheck[&quot;cache_hit_test&quot;]=&quot;ok&quot;; } }); } cache.get(&quot;cache_expire_test&quot;,function(data){ setTimeout(function(){ cache.get(&quot;cache_expire_test&quot;,function(data){}); },1500); }); setTimeout(function(){ cache.get(&quot;cache_eviction_test&quot;,function(data){ for(let i=0;i&lt;999;i++) { cache.get(&quot;cache_eviction_test_count&quot;+i,function(data){ benchData.evictCtr++; if(benchData.evictCtr===999) cache.get(&quot;cache_eviction_test&quot;,function(data){ }); }); } }); },3000); setTimeout(function(){ let ctrMax = 100; // don't pick too low value, causes some uncertainity on 50% hit ratio function repeat(cur){ if(cur&gt;0) for(let i=0;i&lt;900;i++) { cache.get(&quot;cache_50_hit_ratio_test&quot;+parseInt(Math.random()*2000,10),function(data){ benchData.access50++; if(benchData.access50===900) { benchData.access50=0; if(benchData.miss50&gt;400*ctrMax &amp;&amp; benchData.miss50&lt; 500*ctrMax) errorCheck[&quot;cache_50%_hit_ratio&quot;]=&quot;ok&quot;; repeat(cur-1); } }); } } repeat(ctrMax); },5000); </code></pre> <p>Caching Redis For Get/Set Operations:</p> <pre><code>&quot;use strict&quot; // backing-store const Redis = require(&quot;ioredis&quot;); const redis = new Redis(); // LRU cache let Lru = require(&quot;./lrucache.js&quot;).Lru; let num_cache_elements = 1500; let element_life_time_miliseconds = 1000; let cache = new Lru(num_cache_elements, async function(key,callback){ redis.get(key, function (err, result) { callback(result); }); }, element_life_time_miliseconds, async function(key,value,callback){ redis.set(key,value, function (err, result) { callback(); }); }); const N_repeat = 20; const N_bench = 20000; const N_concurrency = 100; const N_dataset = 1000; function randomKey(){ return Math.floor(Math.random()*N_dataset); } // without LRU caching async function benchWithout(callback){ for(let i=0;i&lt;N_bench;i+=N_concurrency){ let ctr = 0; let w8 = new Promise((success,fail)=&gt;{ for(let j=0;j&lt;N_concurrency;j++) { redis.set(randomKey(),i, function (err, result) { redis.get(randomKey(), function (err, result) { ctr++; if(ctr == N_concurrency) { success(1); } }); }); } }); let result = await w8; } callback(); } // with LRU caching async function benchWith(callback){ for(let i=0;i&lt;N_bench;i+=N_concurrency){ let ctr = 0; let w8 = new Promise((success,fail)=&gt;{ for(let j=0;j&lt;N_concurrency;j++) { cache.set(randomKey(),i, function (result) { cache.get(randomKey(), function (result) { ctr++; if(ctr == N_concurrency) { success(1); } }); }); } }); let result = await w8; } callback(); } let ctr = 0; function restartWithoutLRU(callback){ let t = Date.now(); benchWithout(function(){ console.log(&quot;without LRU: &quot;+(Date.now() - t)+&quot; milliseconds&quot;); ctr++; if(ctr != N_repeat) { restartWithoutLRU(callback); } else { ctr=0; callback(); } }); } function restartWithLRU(){ let t = Date.now(); benchWith(function(){ console.log(&quot;with LRU: &quot;+(Date.now() - t)+&quot; milliseconds&quot;); ctr++; if(ctr != N_repeat) { restartWithLRU(); } }); } restartWithoutLRU(restartWithLRU); </code></pre> <p>On my low end computer (2GHz bulldozer cpu, 1 channel ddr3 1600MHz), API overhead causes a performance limitation that is around 1500 cache (read/write) hits per millisecond and about 850 cache (read/write) misses per millisecond. I couldn't find any better way to keep asynchronity and run faster. Would it be logical to shard the cache on multiple cores and have a multi-core cache or would it be better with single thread server serving to all cores?</p>
[]
[ { "body": "<h1>Overfall feedback</h1>\n<p>This review will mostly focus on the usage of JavaScript features used and not so much on the actual algorithm.</p>\n<p>The code has many repeated lines/blocks, which violates the <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</a> principle. For example, the following block appears at least five times, sometimes wrapped in a call to <code>setTimeout()</code>:</p>\n<blockquote>\n<pre><code> access(key,function(newData){\n callback(newData);\n },aType,value);\n</code></pre>\n</blockquote>\n<p>Down below there is a section about simplifying that callback function. But this repeated block could be moved to a method and called whenever needed instead of repeating that block.</p>\n<p>The function <code>access</code> is quite lengthy. It would be better if it could be broken down into smaller functions. The next section mentions the JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">Class syntax</a> - that could help simplify the code if . The <a href=\"https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch09s03.html\" rel=\"nofollow noreferrer\">revealing module pattern</a> could also be used to make &quot;private&quot; methods that are not exposed with the exported module code.</p>\n<h2>Prototype</h2>\n<p>Maybe you know this but in case not: Javascript is a <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes\" rel=\"nofollow noreferrer\">Prototype based</a> language. While it it will still work to assign methods via <code>this.[methodName] = </code> it will be more efficient to store it on the prototype<sup><a href=\"https://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript#comment77907316_34948211\">1</a></sup> though if it is typically used as a singleton then it likely wouldn't make much difference. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">Class syntax</a> could also be used .</p>\n<h2>Variable declarations</h2>\n<p>Some variables are declared with <code>let</code> but are never re-assigned and thus could be declared with <code>const</code> - e.g. <code>Lru</code>, <code>rnd</code>, etc. It is a good habit to default to using <code>const</code> and then switch to <code>let</code> when re-assignment is deemed necessary - mostly with loop counters. This can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>referencing outer function context</h2>\n<p>Instead of using <code>me = this</code> the context could be bound using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a>, or else just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a> (like used in <code>waitForReadWrite</code>) since they don't have a separate binding of <code>this</code>.</p>\n<h2>Readability</h2>\n<p>Most style guides recommend a space after operators like <code>:</code>, <code>,</code> and argument names.</p>\n<p>Idiomatic Javascript does not have brackets start on a new line - especially for <code>for</code> loops and conditional blocks.</p>\n<h2>Strict mode</h2>\n<p>It is great that <code>'use strict';</code> is used, though JavaScript modules are automatically in strict mode<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#strict_mode_for_modules\" rel=\"nofollow noreferrer\">2</a></sup> so it is superfluous to have that in the module.</p>\n<h2>Simplifications</h2>\n<h3>exporting <code>Lru</code></h3>\n<p>Instead of exporting <code>Lru</code> like this:</p>\n<blockquote>\n<pre><code>exports.Lru = Lru;\n</code></pre>\n</blockquote>\n<p>Just export <code>Lru</code> like this:</p>\n<pre><code>module.exports = Lru;\n</code></pre>\n<p>Then instead of accessing it like this:</p>\n<blockquote>\n<pre><code>let Lru = require(&quot;./lrucache.js&quot;).Lru;\n</code></pre>\n</blockquote>\n<p>it can be included like this:</p>\n<pre><code>let Lru = require(&quot;./lrucache.js&quot;)\n</code></pre>\n<h3>wrapper functions around callbacks</h3>\n<p>There are numerous places like this</p>\n<blockquote>\n<pre><code>access(key,function(newData){\n callback(newData);\n },aType,value);\n</code></pre>\n</blockquote>\n<p>Unless the function that calls the callback passes more arguments than one, those extra wrapping functions/closures can be removed:</p>\n<pre><code>access(key, callback, aType, value);\n</code></pre>\n<p>And <code>callback</code> will receive <code>newData</code>.</p>\n<h3>adding elements to an array</h3>\n<p>In the method <code>getMultiple</code> the array <code>result</code> can be declared in a simpler fashion:</p>\n<blockquote>\n<pre><code>this.getMultiple = function(callback, ... keys){\n let result = [];\n let ctr1 = keys.length;\n for(let i=0;i&lt;ctr1;i++)\n result.push(0);\n</code></pre>\n</blockquote>\n<p>This could be simplified with the Array method <code>map()</code> but that might not be as efficient. However another solution is to use the Array method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>.fill()</code></a></p>\n<pre><code>const result = Array(keys.length).fill(0);\n</code></pre>\n<h3>determining if a string includes a substring</h3>\n<p>There are three places where <code>String.indexOf()</code> is compared with -1 - e.g.</p>\n<blockquote>\n<pre><code>if(key.indexOf(&quot;cache_50_hit_ratio_test&quot;)!==-1)\n</code></pre>\n</blockquote>\n<p>This could be simplified using the ES-6 String method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\" rel=\"nofollow noreferrer\"><code>includes()</code></a>:</p>\n<pre><code>if(!key.includes(&quot;cache_50_hit_ratio_test&quot;))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T05:57:45.923", "Id": "268678", "ParentId": "268445", "Score": "2" } } ]
{ "AcceptedAnswerId": "268678", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T17:32:08.523", "Id": "268445", "Score": "2", "Tags": [ "javascript", "node.js", "ecmascript-6", "asynchronous", "cache" ], "Title": "Learning asynchronous caching by implementing one" }
268445
<p>The TEXTJOIN function has a really nice interface:</p> <pre class="lang-swift prettyprint-override"><code>=TEXTJOIN(delimiter, ignore_empty, text1, [text2], …, [text252]) </code></pre> <p>... where <code>text2</code> onwards are optional args, and each text argument can be a string (hardcoded or function return) <em>or an array of strings</em> (from a range or an array formula). This lets you call the function in a few ways:</p> <pre class="lang-swift prettyprint-override"><code>=TEXTJOIN(&quot; &quot;,TRUE, &quot;The&quot;, &quot;sun&quot;, &quot;will&quot;, &quot;come&quot;, &quot;up&quot;, &quot;tomorrow.&quot;) //comma separated values =TEXTJOIN(&quot; &quot;, TRUE, A2:A8) //A 1D array =TEXTJOIN(&quot; &quot;, TRUE, {1,2,3; 4,5,6; 7,8,9}) //2D array =TEXTJOIN(&quot; &quot;, TRUE, A2:A8, &quot;foo&quot;, A1:B3, &quot;bar&quot;) //Combo! </code></pre> <hr /> <p>Ultimately I want to create a PRINTF LAMBDA function which implements a similar interface, e.g. :</p> <pre class="lang-swift prettyprint-override"><code>=PRINTF(mask, text1, [text2], …) //mask like &quot;foo {1} bar {2}&quot; </code></pre> <p>... but LAMBDA functions have no ParamArray type like VBA does to accept a variable number of args, and no ability to loop through their arguments either. Nevertheless, the new <code>[optional]</code> syntax combined with the <code>ISOMITTED</code> function <em>can</em> be used to define LAMBDAs with variable number of arguments so with that this is what I made:</p> <h3><code>PRINTF</code>:</h3> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( mask, _0,[_1],[_2],[_3],[_4],[_5],[_6],[_7],[_8],[_9],[_10],[_11],[_12],[_13],[_14],[_15],[_16],[_17],[_18],[_19],[_20],[_21],[_22],[_23],[_24],[_25],[_26],[_27],[_28],[_29],[_30],[_31],[_32],[_33],[_34],[_35],[_36],[_37],[_38],[_39],[_40],[_41],[_42],[_43],[_44],[_45],[_46],[_47],[_48],[_49],[_50],[_51],[_52],[_53],[_54],[_55],[_56],[_57],[_58],[_59],[_60],[_61],[_62],[_63],[_64],[_65],[_66],[_67],[_68],[_69],[_70],[_71],[_72],[_73],[_74],[_75],[_76],[_77],[_78],[_79],[_80],[_81],[_82],[_83],[_84],[_85],[_86],[_87],[_88],[_89],[_90],[_91],[_92],[_93],[_94],[_95],[_96],[_97],[_98],[_99],[_100],[_101],[_102],[_103],[_104],[_105],[_106],[_107],[_108],[_109],[_110],[_111],[_112],[_113],[_114],[_115],[_116],[_117],[_118], LET( tokensArray, FLATARRAY( _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79, _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95, _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109, _110, _111, _112, _113, _114, _115, _116, _117, _118 ), escapedResult, _ReplaceRecursive( mask, tokensArray, 1, ROWS(tokensArray) ), SUBSTITUTE(escapedResult,&quot;\}&quot;,&quot;}&quot;) ) ) </code></pre> <p>Yes, some hardcoded arguments - a bit nasty but not too bad. Some points to note:</p> <ul> <li>The first argument <code>_0</code> is mandatory, this is because my <code>FLATARRAY</code> function (I'll get onto that) must return an array with at least one element. Still calling <code>PRINTF(mask)</code> with no argument would be a redundant noop anyway so I think this is an okay API.</li> <li>The number of arguments could be <a href="https://support.microsoft.com/en-gb/office/lambda-function-bd212d27-1cd1-4321-a34a-ccbf254b8b67#:%7E:text=You%20can%20enter%20up%20to%20253%20parameters" rel="nofollow noreferrer">up to 253</a>, however the name manager has a character limit of 2000 for me and some of the LAMBDAS are too long to support more args. I think 100 is more than sufficient anyway (bear in mind each arg could itself be a whole array of values, like in <code>TEXTJOIN</code>).</li> </ul> <hr /> <p>That <code>PRINTF</code> function relies on a <code>_ReplaceRecursive</code> function to do the legwork:</p> <h3><code>_ReplaceRecursive</code>:</h3> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( mask, tokens, i, tokenCount, IF( i &gt; tokenCount, mask, LET( token, INDEX(tokens,i), escapedToken, SUBSTITUTE(token,&quot;}&quot;,&quot;\}&quot;), inIndexedMode, ISERROR( FIND(&quot;{}&quot;,mask,1) ), substituted, IF( inIndexedMode, SUBSTITUTE( mask, &quot;{&quot; &amp; i &amp; &quot;}&quot;, escapedToken ), SUBSTITUTE( mask, &quot;{}&quot;, escapedToken, 1 ) ), _ReplaceRecursive( substituted, tokens, i + 1, tokenCount ) ) ) ) </code></pre> <p>Some notes:</p> <ul> <li>I've gone with an _PascalCase naming system for this private implementation LAMBDA as opposed to YELLCASE for the Excel UDF entry point.</li> <li>The function has 2 modes; &quot;{indexed}&quot; where you provide the 1-based location in the tokensArray of the string you wish to substitute, and {} positional. More explanation over on my stack overflow answer <a href="https://stackoverflow.com/a/69266041/6609896">here</a>. It has some basic escaping although it will incorrectly handle the edge case of <code>\}</code> in the mask, not sure if there's an easy fix for this, open to suggestions.</li> </ul> <hr /> <h2>Mimicking ParamArray</h2> <p>The other aspect of the PRINTF function is the argument handling, and this is where things start to get a bit messy...</p> <h3><code>FLATARRAY</code>:</h3> <p>A helper function for taking an array of arrays and flattening it into a 1D vector.</p> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( _0,[_1],[_2],[_3],[_4],[_5],[_6],[_7],[_8],[_9],[_10],[_11],[_12],[_13],[_14],[_15],[_16],[_17],[_18],[_19],[_20],[_21],[_22],[_23],[_24],[_25],[_26],[_27],[_28],[_29],[_30],[_31],[_32],[_33],[_34],[_35],[_36],[_37],[_38],[_39],[_40],[_41],[_42],[_43],[_44],[_45],[_46],[_47],[_48],[_49],[_50],[_51],[_52],[_53],[_54],[_55],[_56],[_57],[_58],[_59],[_60],[_61],[_62],[_63],[_64],[_65],[_66],[_67],[_68],[_69],[_70],[_71],[_72],[_73],[_74],[_75],[_76],[_77],[_78],[_79],[_80],[_81],[_82],[_83],[_84],[_85],[_86],[_87],[_88],[_89],[_90],[_91],[_92],[_93],[_94],[_95],[_96],[_97],[_98],[_99],[_100],[_101],[_102],[_103],[_104],[_105],[_106],[_107],[_108],[_109],[_110],[_111],[_112],[_113],[_114],[_115],[_116],[_117],[_118],[_119], LET( indexable, LAMBDA( myIndex, CHOOSE( //this will create an array with default values for omitted args myIndex, _1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63,_64,_65,_66,_67,_68,_69,_70,_71,_72,_73,_74,_75,_76,_77,_78,_79,_80,_81,_82,_83,_84,_85,_86,_87,_88,_89,_90,_91,_92,_93,_94,_95,_96,_97,_98,_99,_100,_101,_102,_103,_104,_105,_106,_107,_108,_109,_110,_111,_112,_113,_114,_115,_116,_117,_118,_119 ) ), argsSize, ARGSCOUNT( _1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63 ) + ARGSCOUNT( //have to split because of argument limits in ARGSCOUNT() _64,_65,_66,_67,_68,_69,_70,_71,_72,_73,_74,_75,_76,_77,_78,_79,_80,_81,_82,_83,_84,_85,_86,_87,_88,_89,_90,_91,_92,_93,_94,_95,_96,_97,_98,_99,_100,_101,_102,_103,_104,_105,_106,_107,_108,_109,_110,_111,_112,_113,_114,_115,_116,_117,_118,_119 ), joiner, //a function to merge all the args into a single array using an accumulator LAMBDA( runningTot, x, ARRAYJOIN( runningTot, indexable(x) ) ), base, FLATTEN(_0), //flatten the first arg so its dimensions are still consistently 1D when it's the only arg IF( argsSize = 0, base, REDUCE( base, SEQUENCE(argsSize), joiner ) ) ) </code></pre> <p>The principle here is that <code>CHOOSE(SEQUENCE(n), arg_1, arg_2 ... arg_n)</code> constructs an array with n items. However we don't know the value of <code>n</code>, so instead I use <code>CHOOSE(SEQUENCE(m), arg_1, arg_2, ... arg_n)</code> with</p> <ul> <li><code>n</code> optional arguments to my LAMBDA</li> <li><code>m</code> actually supplied (e.g. TEXTJOIN has n = 252, but I can call it passing m = 3 items to join)</li> <li><code>m&lt;=n</code></li> </ul> <p>So how do you evaluate <code>m</code> the number of arguments passed? That is the subject of a question I asked on SO: <a href="https://stackoverflow.com/q/69319638/6609896">Create dynamic array from non-contiguous cells/values without VBA</a> but what I ultimately went for was a hardcoded binary search to find the index of the first omitted argument without checking all of them (this works because if the 6th argument is omitted, I know all the arguments from 7 onwards will be as well). This is the resulting function:</p> <pre class="lang-swift prettyprint-override"><code>=LAMBDA([p_1],[p_2],[p_3],[p_4],[p_5],[p_6],[p_7],[p_8],[p_9],[p_10],[p_11],[p_12],[p_13],[p_14],[p_15],[p_16],[p_17],[p_18],[p_19],[p_20],[p_21],[p_22],[p_23],[p_24],[p_25],[p_26],[p_27],[p_28],[p_29],[p_30],[p_31],[p_32],[p_33],[p_34],[p_35],[p_36],[p_37],[p_38],[p_39],[p_40],[p_41],[p_42],[p_43],[p_44],[p_45],[p_46],[p_47],[p_48],[p_49],[p_50],[p_51],[p_52],[p_53],[p_54],[p_55],[p_56],[p_57],[p_58],[p_59],[p_60],[p_61],[p_62],[p_63],IF(ISOMITTED(p_32),IF(ISOMITTED(p_16),IF(ISOMITTED(p_8),IF(ISOMITTED(p_4),IF(ISOMITTED(p_2),IF(ISOMITTED(p_1),0,1),IF(ISOMITTED(p_3),2,3)),IF(ISOMITTED(p_6),IF(ISOMITTED(p_5),4,5),IF(ISOMITTED(p_7),6,7))),IF(ISOMITTED(p_12),IF(ISOMITTED(p_10),IF(ISOMITTED(p_9),8,9),IF(ISOMITTED(p_11),10,11)),IF(ISOMITTED(p_14),IF(ISOMITTED(p_13),12,13),IF(ISOMITTED(p_15),14,15)))),IF(ISOMITTED(p_24),IF(ISOMITTED(p_20),IF(ISOMITTED(p_18),IF(ISOMITTED(p_17),16,17),IF(ISOMITTED(p_19),18,19)),IF(ISOMITTED(p_22),IF(ISOMITTED(p_21),20,21),IF(ISOMITTED(p_23),22,23))),IF(ISOMITTED(p_28),IF(ISOMITTED(p_26),IF(ISOMITTED(p_25),24,25),IF(ISOMITTED(p_27),26,27)),IF(ISOMITTED(p_30),IF(ISOMITTED(p_29),28,29),IF(ISOMITTED(p_31),30,31))))),IF(ISOMITTED(p_48),IF(ISOMITTED(p_40),IF(ISOMITTED(p_36),IF(ISOMITTED(p_34),IF(ISOMITTED(p_33),32,33),IF(ISOMITTED(p_35),34,35)),IF(ISOMITTED(p_38),IF(ISOMITTED(p_37),36,37),IF(ISOMITTED(p_39),38,39))),IF(ISOMITTED(p_44),IF(ISOMITTED(p_42),IF(ISOMITTED(p_41),40,41),IF(ISOMITTED(p_43),42,43)),IF(ISOMITTED(p_46),IF(ISOMITTED(p_45),44,45),IF(ISOMITTED(p_47),46,47)))),IF(ISOMITTED(p_56),IF(ISOMITTED(p_52),IF(ISOMITTED(p_50),IF(ISOMITTED(p_49),48,49),IF(ISOMITTED(p_51),50,51)),IF(ISOMITTED(p_54),IF(ISOMITTED(p_53),52,53),IF(ISOMITTED(p_55),54,55))),IF(ISOMITTED(p_60),IF(ISOMITTED(p_58),IF(ISOMITTED(p_57),56,57),IF(ISOMITTED(p_59),58,59)),IF(ISOMITTED(p_62),IF(ISOMITTED(p_61),60,61),IF(ISOMITTED(p_63),62,63))))))) </code></pre> <p>... or for a more manageable number of arguments:</p> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( [_1],[_2],[_3],[_4],[_5],[_6],[_7], IF( ISOMITTED(_4), IF( ISOMITTED(_2), IF( ISOMITTED(_1), 0, 1 ), IF( ISOMITTED(_3), 2, 3 ) ), IF( ISOMITTED(_6), IF( ISOMITTED(_5), 4, 5 ), IF( ISOMITTED(_7), 6, 7 ) ) ) ) </code></pre> <p>Hopefully you can see how that decision tree cuts down on the number of arguments that have to be checked with <code>ISOMITTED()</code>. This function was hit hard by the character limit so is limited to only 63 args (it has to be a power of two - 1 for the binary tree to be symmetric, which is easier to programme)</p> <p>And finally, there are a couple of helper functions:</p> <h3><code>FLATTEN:</code></h3> <p>Convert 2D array to 1D array</p> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( array, LET( r, ROWS(array), c, COLUMNS(array), INDEX( array, ROUNDUP( SEQUENCE( r * c ) / c, 0 ), MOD( SEQUENCE( r * c, , 0 ), c ) + 1 ) ) ) </code></pre> <p><sub>(<a href="https://www.reddit.com/r/excel/comments/oo29mp/comment/h5vkupe/?utm_source=share&amp;utm_medium=web2x&amp;context=3" rel="nofollow noreferrer">source</a>)</sub></p> <h3><code>ARRAYJOIN</code></h3> <p>Merge two arrays into a single 1D array - like a <code>For...Each</code> over both ranges in a row...</p> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( a, b, LET( flatA, FLATTEN(a), flatB, FLATTEN(b), sizeA, ROWS(flatA), sizeB, ROWS(flatB), joinedIndexable, LAMBDA( x, IF( x &lt;= sizeA, INDEX( flatA, x ), INDEX( flatB, x - sizeA ) ) ), joinedIndexable( SEQUENCE( sizeA + sizeB ) ) ) ) </code></pre> <p>For contrast, the equivalent VBA (without flattening) looks like:</p> <pre class="lang-vb prettyprint-override"><code>Public Function ARRAYFROMARGS(ParamArray args()) As Variant ARRAYFROMARGS = args End Function </code></pre> <p>That looks really bad I know, but actually now I have those helper functions, implementing ParamArray in another lambda is as simple as defining n optional args and passing them to <code>FLATARRAY</code> and it can filter out the omitted ones automatically. I also have a simpler <code>ARRAY</code> function which does not flatten the args (so same as the VBA), but that doesn't match the TEXTJOIN behaviour I'm after. Code for that is <a href="https://stackoverflow.com/a/69328652/6609896">here</a>.</p>
[]
[ { "body": "<p>Very nice! It can be simplified, since you don't need <code>_ReplaceRecursive</code>. I subbed in a <code>REDUCE</code> like this and this and it seems ok, assuming we don't have to escape the tokens.</p>\n<pre><code> REDUCE(\n mask,\n SEQUENCE(ROWS(tokensArray)),\n LAMBDA(acc,i,\n SUBSTITUTE(\n acc,\n &quot;{&quot; &amp; i &amp; &quot;}&quot;,\n INDEX(tokensArray,i)\n )\n )\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T13:08:01.827", "Id": "529786", "Score": "1", "body": "Thanks:) Yeah wrote the Printf function itself before Reduce was announced but I was thinking it simplifies things a little (didn't want to modify the question though). The escaping lets you use `PRINTF(\"mask {1}, {2}\", \"foo {2}\", \"bar\")` i.e. a `{}` placeholder in a substitute token. Without escaping yo get `\"mask foo bar, bar\"` not `\"mask foo {2}, bar\"`. However with this approach you can't have `\\}` intentionally in the mask as it will become `}` which is an edge case, can't think of an easy workaround though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T13:12:26.340", "Id": "529787", "Score": "0", "body": "Ahh, I see, thanks for the clarification!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T12:40:48.233", "Id": "268616", "ParentId": "268446", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T18:34:14.863", "Id": "268446", "Score": "1", "Tags": [ "array", "vba", "excel", "reinventing-the-wheel", "lambda" ], "Title": "Fancy new LAMBDA functions with variable number of arguments to mimic native methods - no VBA" }
268446
<p><strong>Problem.</strong></p> <p>I have a directory of <code>.root</code> files (the proprietary format of CERN's <code>ROOT</code> framework). These files contain so-called <code>TTree</code>'s, essentially tables who's cells may contain virtually any <code>c++</code> object or type. In my case, these files contain tables of integers, which I wish to perform some operations on to produce a single, high precision floating-point value. I'm using <code>Boost</code>'s <code>cpp_dec_float_100</code> type (from the <code>boost::multiprecision</code> library) due to my precision requirements. I then write these to a new <code>.root</code> file.</p> <p><em>Step through my code:</em></p> <p>Firstly, I read into a <code>vector&lt;string&gt;</code> the lines of a file <code>in_path</code>, which contain the paths to my <code>.root</code> files.</p> <pre><code> ifstream stream(in_path); string tem; vector&lt;string&gt; list; while(getline(stream, tem)) list.push_back(tem); </code></pre> <p>Then, I construct an <code>RDataFrame</code> on them. The <code>RDataFrame</code>, for my purposes, essentially efficiently combines them into one large table.</p> <pre><code>ROOT::RDataFrame df(&quot;eventTree&quot;, list); </code></pre> <p>Now, a bit about my data. You can imagine the table as looking something like this:</p> <pre><code>+-----+-----+-----+ | run | A | B | +-----+-----+-----+ | 001 | 35 | 5 | | 001 | 40 | 10 | | 001 | 77 | 60 | | | | | | ... | ... | ... | | | | | | 002 | 42 | 40 | | 002 | 30 | 28 | | 002 | 50 | 1 | | ... | ... | ... | +-----+-----+-----+ </code></pre> <p><em>where the ... dots indicate continuation</em></p> <p>For each <code>run</code>, I want to determine the most common difference of <code>A</code> and <code>B</code>, element-wise. This value will factor into my later calculations. So, for example, for run 002 we have <code>42-40 = 2</code>, <code>30-28=2</code>, and <code>50 - 1=49</code>, the most common element/mode of <code>2,2, and 49</code> is <code>2</code>, so the result for <code>run 002</code> is <code>2</code>.</p> <p><em>A couple of important notes: <code>A-B</code> is guaranteed to be a positive, integer value for all entries, and there is guaranteed to be a single, unique most common difference for each run</em></p> <p>What I do is to map each <code>run</code> to another <code>map</code>, which maps difference values to frequency. In the end, I can simply get the key of the largest value (i.e. the most common difference).</p> <p>I iterate over each row, take the difference of <code>A</code> and <code>B</code>, and increment the value of the corresponding key in the map.</p> <pre><code> map&lt;int, map&lt;int, int&gt;&gt; offset; df.Foreach([&amp;](ULong64_t A, UInt_t B, Int_t run){ ++offset[run][A- B]; },{&quot;A&quot;,&quot;B&quot;,&quot;run&quot;}); </code></pre> <p>Returning to the previous example, run <code>002</code> would be mapped to a map that looks like:</p> <p><code>{{2, 2}, {49, 1}}</code></p> <p>Next, I create a new column in the <code>RDataFrame</code> using <code>.Define()</code>, which takes the name of the column (<code>eventTime</code>), and a <code>lambda</code> which returns the value for each row in the new column. It is within this <code>lambda</code> that I perform my calculation.</p> <pre><code> df.Define(&quot;eventTime&quot;, [&amp;](UInt_t timeStamp, UInt_t B, Int_t run){ // Get most common difference for run, add to B B+= max_element(offset[run].begin(), offset[run].end())-&gt;first; return Mult_t(B+ Mult_t(timeStamp) / 1E+8); },{&quot;timeStamp&quot;,&quot;B&quot;,&quot;run&quot;}).Snapshot(&quot;T&quot;, out_path, {&quot;eventTime&quot;}); </code></pre> <p>Finally, <code>.Snapshot</code> saves the new column as a new <code>TTree</code> in a new <code>.root</code> file.</p> <hr /> <p><strong>Code.</strong></p> <p><em>Dependencies:</em> <a href="https://www.boost.org/doc/libs/1_72_0/libs/multiprecision/doc/html/index.html" rel="nofollow noreferrer"><code>boost::multiprecision</code></a> library, and the <a href="https://root.cern/" rel="nofollow noreferrer"><code>ROOT</code></a> framework.</p> <pre><code>#include &lt;boost/multiprecision/cpp_dec_float.hpp&gt; using Mult_t = boost::multiprecision::cpp_dec_float_100; void writeTimes(const char* in_path, const char* out_path){ ifstream stream(in_path); string tem; vector&lt;string&gt; list; while(getline(stream, tem)) list.push_back(tem); ROOT::RDataFrame df(&quot;eventTree&quot;, list); map&lt;int, map&lt;int, int&gt;&gt; offset; df.Foreach([&amp;](ULong64_t A, UInt_t B, Int_t run){ ++offset[run][A- B]; },{&quot;A&quot;,&quot;B&quot;,&quot;run&quot;}); df.Define(&quot;eventTime&quot;, [&amp;](UInt_t timeStamp, UInt_t B, Int_t run){ B+= max_element(offset[run].begin(), offset[run].end())-&gt;first; return Mult_t(B+ Mult_t(timeStamp) / 1E+8); },{&quot;timeStamp&quot;,&quot;B&quot;,&quot;run&quot;}).Snapshot(&quot;T&quot;, out_path, {&quot;eventTime&quot;}); } </code></pre> <hr /> <p><strong>Goals.</strong></p> <ul> <li><strong>Readability</strong>: I'm always looking to improve the readability and &quot;flow&quot; of my code, which is often destined for use by others.</li> <li><strong>Reliability</strong>: I find that a second pair of eyes is often useful for pointing out (sometimes obvious) errors and potential bugs in my code. For this code in particular, reliability is vital.</li> <li><strong>Performance</strong>: A secondary goal is performance. I'm not terribly concerned about optimizing what I have now, however if there are some simple/obvious changes that can or should be made to improve performance, I'm certainly interested.</li> </ul> <blockquote> <p>Note: this code is written to be run or compiled with the <code>ROOT</code> interpreter.</p> </blockquote>
[]
[ { "body": "<h1>Let ROOT read the file for you</h1>\n<p><code>RdataFrame</code>'s constructor can take a filename or a <code>TFile*</code> as an argument, and will read the whole file in for you. This avoids first reading into the temporary vector <code>list</code> and then parsing that list again.</p>\n<h1>Choice of containers</h1>\n<p>A <code>std::map</code> is easy to use but not the best choice for performance, due to <span class=\"math-container\">\\$\\mathcal{O}(\\log N)\\$</span> complexity for insertions and lookups. If the file contains a monotonically increasing number in the run column, you can get the number of runs just by looking at the last row, and then use a <code>std::vector</code> of that size:</p>\n<pre><code>auto runs = /* get maximum run number from df */;\nstd::vector&lt;std::map&lt;int, int&gt;&gt; offset(runs + 1);\n\ndf.Foreach([&amp;](ULong64_t A, UInt_t B, Int_t run){\n ++offset[run][A - B];\n},{&quot;A&quot;, &quot;B&quot;, &quot;run&quot;});\n</code></pre>\n<p>Similarly, the remaining <code>std::map</code> could changed to a <code>std::vector</code> if you know there is an upper bound to the difference and if the set of differences is dense.</p>\n<p>If either of the two maps cannot be converted to a <code>std::vector</code>, then at least replace them with <code>std::unordered_map</code>, as this will have <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> insertions and lookups.</p>\n<h1>Too early to convert to <code>Mult_t</code>?</h1>\n<p>I think you can store the event times as an <code>ULong64_t</code> without losing any precision, just replace the last <code>return</code> statement to:</p>\n<pre><code>return B * 1'00'000'000ull + timeStamp;\n</code></pre>\n<p>Of course, you would need to do the conversion to seconds (I assume) somewhere else then. But this speeds up the function and saves some space in the output.</p>\n<h1>Missing error checking</h1>\n<p>You are not performing any error checking when opening the file and reading lines from it. You should at least check that the whole file was read in by checking that <code>stream.eof() == true</code> after the <code>while</code>-loop. If not, then print an error message and <code>throw</code> an exception or call <code>exit(EXIT_FAILURE)</code>, so you don't write out incorrect results without anyone noticing.</p>\n<p>If you use <code>ROOT::RDataFrame</code>'s constructor to read the file, then this will hopefully be taken care of already.</p>\n<h1>Is <code>max_element</code> good enough?</h1>\n<p>It almost looks like you want to get the median value, but your approach with <code>max_element()</code> will not give you that. In fact, it might not even be close to the median. Consider this histogram:</p>\n<pre><code>1: 2\n2: 1\n3: 1\n4: 1\n...\n10: 1\n</code></pre>\n<p>Here the number 1 has two occurences, the numbers 2 to 10 only one occurrence. The median is 5, but the maximum element is 1. You need to sort the histogram and find the element such that the sum of occurences before that element is equal to that after (and also handle the case of an even number of events correctly).</p>\n<p>Instead of building a histogram, you can just store all the differences <code>A - B</code> in a vector, then sort it, and then just pick the middle element (or average the two elements closest to the middle in case of an even number of elements). See <a href=\"https://stackoverflow.com/questions/1719070/what-is-the-right-approach-when-using-stl-container-for-median-calculation\">this StackOverflow question</a> for how to do that.</p>\n<p>Of course there are more sophisticated methods, like calculating the root mean square, possibly filtering out outliers first.</p>\n<h1>Reduce the number of responsibilities</h1>\n<p>Your function is responsible for opening the file, parsing the input, adding a column, and writing the result out. Consider reducing it to a function that just adds the eventTime column:</p>\n<pre><code>auto&amp; addEventTimes(ROOT::RDataFrame&amp; df) {\n map&lt;int, map&lt;int, int&gt;&gt; offset;\n\n df.Foreach([&amp;](ULong64_t A, UInt_t B, Int_t run){\n ++offset[run][A - B];\n }, {&quot;A&quot;, &quot;B&quot;, &quot;run&quot;});\n\n return df.Define(&quot;eventTime&quot;, [&amp;](UInt_t timeStamp, UInt_t B, Int_t run){\n B += max_element(offset[run].begin(), offset[run].end())-&gt;first;\n return Mult_t(B + Mult_t(timeStamp) / 1E+8);\n },{&quot;timeStamp&quot;,&quot;B&quot;,&quot;run&quot;});\n}\n</code></pre>\n<p>You can then call this from the original function:</p>\n<pre><code>void writeTimes(const char* in_path, const char* out_path) {\n ROOT::RDataFrame df(&quot;eventTree&quot;, in_path);\n addEventTimes(df).Snapshot(&quot;T&quot;, out_path, {&quot;eventTime&quot;});\n}\n</code></pre>\n<h1>About readability</h1>\n<p>Apart from splitting up the function as mentioned above, I would also choose some better variable names:</p>\n<ul>\n<li><code>tem</code> -&gt; <code>line</code></li>\n<li><code>df</code> -&gt; <code>eventData</code></li>\n<li><code>offset</code> -&gt; <code>offsetHistograms</code></li>\n</ul>\n<p>This makes it more clear what they contain. Also add some comments to those parts that are not immediately clear when reading them, like the <code>df.Foreach()</code> and <code>df.Define()</code> calls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T22:59:31.727", "Id": "529410", "Score": "0", "body": "Thanks for taking the time! It's always useful to get an outside perspective with respect to readability, and your suggestion to use `unordered_map` improved performance more than I would've expected. A couple clarifications-- I'm looking for the *mode*, not the *median*. Also, I pass a vector of strings to `RDataFrame` as I wish to merge multiple `TTrees` from multiple `TFiles` living in multiple `.root` files. I could only open a single file by passing a path or `TFile*`. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T06:10:03.627", "Id": "529420", "Score": "0", "body": "If it's the mode, great! Although you might still have to consider how to handle multiple values having the same number of occurences. Having a comment in the code saying you want the mode would have removed any doubt :) As for merging `TTree`s, perhaps [`TTree::MergeTrees()`](https://root-forum.cern.ch/t/merging-ttrees-on-the-fly/1833) can be used?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T21:25:35.410", "Id": "268453", "ParentId": "268449", "Score": "1" } } ]
{ "AcceptedAnswerId": "268453", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T19:54:20.807", "Id": "268449", "Score": "1", "Tags": [ "c++", "performance" ], "Title": "Data processing with the CERN ROOT framework" }
268449
<p>Given a dictionary including multiple X-Y pairs where X, Y are both three dimensional structure. <code>dictionaryBasedNonlocalMean</code> function return a <code>output</code> which is weighted sum of each Y in the dictionary. Each weight of Y are based on the Manhattan distance between the <code>input</code> of <code>dictionaryBasedNonlocalMean</code> function and the corresponding X in the dictionary. In mathematical form, output is calculated with the following way.</p> <p><span class="math-container">$$output = K\sum_{{i = 1}}^{{N}_{D}} \left[ G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1}) \cdot Y(i) \right] $$</span></p> <p>where N<sub>D</sub> is the count of X-Y pairs (the cardinality of set X and set Y) in the dictionary and the Gaussian function</p> <p><span class="math-container">$$G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1}) = \left.e^{\frac{-(\left\|input - X(i)\right\|_{1} - \mu)^2}{2 {\sigma}^{2}}}\right|_{\mu=0} $$</span></p> <p>Moreover, K is a normalization factor</p> <p><span class="math-container">$$K = \frac{1}{\sum_{{i = 1}}^{{N}_{D}} G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1})} $$</span></p> <p><a href="https://i.stack.imgur.com/VNbaN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VNbaN.png" alt="Illustration" /></a></p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>ManhattanDistance</code> function</p> <pre><code>function output = ManhattanDistance(X1, X2) output = sum(abs(X1 - X2), 'all'); end </code></pre> </li> <li><p><code>dictionaryBasedNonlocalMean</code> function</p> <pre><code>function [output] = dictionaryBasedNonlocalMean(Dictionary, input) gaussian_sigma = 0.1; gaussian_mean = 0; if size(Dictionary.X) ~= size(Dictionary.Y) disp(&quot;Size of data in dictionary incorrect.&quot;); output = []; return end [X, Y, Z, DataCount] = size(Dictionary.X); weightOfEach = zeros(1, DataCount); for i = 1:DataCount % Gaussian of distance between X and input weightOfEach(i) = gaussmf(ManhattanDistance(input, Dictionary.X(:, :, :, i)), [gaussian_sigma gaussian_mean]); end sumOfDist = sum(weightOfEach, 'all'); output = zeros(X, Y, Z); %%% if sumOfDist too small if (sumOfDist &lt; 1e-160) fprintf(&quot;sumOfDist = %d\n&quot;, sumOfDist); return; end for i = 1:DataCount output = output + Dictionary.Y(:, :, :, i) .* weightOfEach(i); end output = output ./ sumOfDist; end </code></pre> </li> </ul> <p><strong>Test case</strong></p> <pre><code>ND = 10; xsize = 8; ysize = 8; zsize = 1; Dictionary = CreateDictionary(ND, xsize, ysize, zsize); output = dictionaryBasedNonlocalMean(Dictionary, ones(xsize, ysize, zsize) .* 0.66) function Dictionary = CreateDictionary(ND, xsize, ysize, zsize) Dictionary.X = zeros(xsize, ysize, zsize, ND); Dictionary.Y = zeros(xsize, ysize, zsize, ND); for i = 1:ND Dictionary.X(:, :, :, i) = ones(xsize, ysize, zsize) .* (i / ND); Dictionary.Y(:, :, :, i) = ones(xsize, ysize, zsize) .* (1 + i / ND); end end </code></pre> <p>The output result of testing code above:</p> <pre><code>output = 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 1.6622 </code></pre> <p>All suggestions are welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T23:58:18.713", "Id": "268454", "Score": "1", "Tags": [ "algorithm", "array", "error-handling", "matrix", "matlab" ], "Title": "Dictionary based non-local mean implementation in Matlab" }
268454
<p>I am working on an e-commerce website. I want to display products in the search result. Here is a subset of what I am doing to display the images.</p> <p>I am using <code>flex</code> to divide the screen into 3 columns and I am using <code>flex-grow-1</code> to make all the cards the same height, here is the code:</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-css lang-css prettyprint-override"><code>.summary-cn .summary-item-col { padding-left: 15px; padding-bottom: 15px; position: relative; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .summary-cn .summary-item-col .item-cn { background-color: #fff; border: 1px solid #e5e5e5; } .summary-cn .summary-item-col .summary-image img { vertical-align: super; object-fit: cover; width: 155px; height: calc(155px / 1.33); } .summary-cn .summary-item-col .summary-text { z-index: 40; padding: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt; &lt;title&gt;Bootstrap Example&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="summary-cn d-flex flex-wrap "&gt; &lt;div class="summary-item-col d-flex"&gt; &lt;div class="item-cn flex-grow-1"&gt; &lt;div class="summary-image"&gt; &lt;img class="img-lazy img-responsive img-loaded" src="https://www.shopless.co.nz/photo-uploads/4/200722144731517-1307119763/img-0-Beautiful-Persian-pottery-hand-made-and-hand-painted-plate-Small-plate-Ceramic-200722145316497.jpg" loading="lazy" alt="Home &amp;amp; garden Home &amp;amp; living Kitchen : Beautiful Persian pottery, hand-made and hand-painted plate, Small plate, Ceramic" width="400" height="300"&gt; &lt;/div&gt; &lt;div class="summary-text"&gt; &lt;div class="title-summary"&gt; &lt;h5&gt;Beautiful Persian pottery, hand-made&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="summary-item-col d-flex"&gt; &lt;div class="item-cn flex-grow-1"&gt; &lt;div class="summary-image"&gt; &lt;img class="img-lazy img-responsive img-loaded" src="https://www.shopless.co.nz/photo-uploads/4/200722153952973-1081959946/img-0-Colourful-flower-vase-wall-mount-flower-vase-Persian-pottery-200722155407095.jpg" loading="lazy" alt="Home &amp;amp; garden Home &amp;amp; living Home decor : Colourful flower vase, wall mount flower vase, Persian pottery" width="400" height="300"&gt; &lt;/div&gt; &lt;div class="summary-text"&gt; &lt;div class="title-summary"&gt; &lt;h5&gt;Colourful flower vase, wall mount flower vase, Persian pottery&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="summary-item-col d-flex"&gt; &lt;div class="item-cn flex-grow-1"&gt; &lt;div class="summary-image"&gt; &lt;img class="img-lazy img-responsive img-loaded" src="https://www.shopless.co.nz/photo-uploads/4/200722160602788-764619588/img-0-Ceramic-Container-Butter-Keeper-Pottery-Jar-with-Lid-Pottery-Container-Brand-new-200722162058426.jpg" loading="lazy" alt="Home &amp;amp; garden Home &amp;amp; living Kitchen : Ceramic Container, Butter Keeper, Pottery Jar with Lid, Pottery Container (Brand new)" width="400" height="300"&gt; &lt;/div&gt; &lt;div class="summary-text"&gt; &lt;div class="title-summary"&gt; &lt;h5&gt;Ceramic Container, Butter Keeper, Pottery Jar with Lid, Pottery Container (Brand new)&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;body&gt;</code></pre> </div> </div> </p> <p>The only issue that I have is that sometimes I get a 1px white space on the left hand side of the image and even if I make the image wider, I can't get rid of it, as shown below:</p> <p><a href="https://i.stack.imgur.com/HGx5F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGx5F.png" alt="enter image description here" /></a></p> <p>Is there anything wrong with the way I am displaying the grid? and is there anyway that I can improve it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T00:32:37.630", "Id": "268455", "Score": "0", "Tags": [ "css", "bootstrap-4" ], "Title": "Display product summary for an e-commerce website" }
268455
<p>I just finished Problem 04 on Project Euler, and I was looking at ways to optimize my code, just started learning functions too, so I'm pretty sure it's very bad, hopefully you guys can help me.</p> <p><em><strong>Question</strong></em></p> <p><strong>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</strong></p> <p><strong>Find the largest palindrome made from the product of two 3-digit numbers.</strong></p> <pre><code>public class TestProblem10 { public static int checkPalindrome(int a, int b){ boolean palindro = false; if (a % 1000000 / 100000 == a % 10 &amp;&amp; a % 100000 / 10000 == a % 100 / 10 &amp;&amp; a % 10000 / 1000 == a % 1000 / 100) { // Checking if it's a palidrome if (a &gt; b) { // Making sure to return the largest palindrome possible. b = a; // A = MULT B = PALINDROME palindro = true; } } if (palindro){ return b; }else{ return 0; } } </code></pre> <blockquote> <p>I do not like very much the 5th and the 6th line because it took so much space, if there's one way to make it better do let me know too please.</p> </blockquote> <pre><code> public static void main(String[] args) { // var int palindrome = 0; // processing for (int i = 900; i &lt; 1000; i++) { for (int k = 900; k &lt; 1000; k++) { int mult = (i * k); if (checkPalindrome(mult, palindrome) == 0){ continue; // Won't let the result = 0 when func returns 0 }else{ palindrome = checkPalindrome(mult, palindrome); } } } // out System.out.print(&quot;Largest palindrome made from the product of two 3-digit numbers is &quot; + palindrome); } } </code></pre>
[]
[ { "body": "<h2>Arithmetic simplification</h2>\n<pre><code>if (a % 1000000 / 100000 == a % 10 &amp;&amp; a % 100000 / 10000 == a % 100 / 10 &amp;&amp;\n a % 10000 / 1000 == a % 1000 / 100) {\n</code></pre>\n<p>An expression like <code>a % 10...0 / 100</code> can be simplified to <code>a / 100 % 10</code>. So the whole condition becomes:</p>\n<pre><code>if (a / 100000 % 10 == a % 10 &amp;&amp; a / 10000 % 10 == a / 10 % 10 &amp;&amp;\n a / 1000 % 10 == a / 100 % 10) {\n</code></pre>\n<h2>Search range</h2>\n<pre><code>for (int i = 900; i &lt; 1000; i++) {\n for (int k = 900; k &lt; 1000; k++) {\n</code></pre>\n<p>How do you know you'll find a palindromic product with <code>i</code> and <code>k</code> in the range [900, 1000); did you prove that?</p>\n<p>How do you know that if you search <code>i</code> and <code>k</code> in the range [100, 1000), you won't find a bigger palindrome? (For example, pretend that 900×900=810000 is the biggest palindrome in the first case but 899×1000=899000 is the biggest palindrome in the second case.)</p>\n<p>Absent a proof, the conservatively correct thing to do is to search the entire 3-digit range given by the problem:</p>\n<pre><code>for (int i = 100; i &lt; 1000; i++) {\n for (int k = 100; k &lt; 1000; k++) {\n</code></pre>\n<h2>Extra parentheses</h2>\n<pre><code>int mult = (i * k);\n</code></pre>\n<p>For this simple expression, it's clearer to not use parentheses:</p>\n<pre><code>int mult = i * k;\n</code></pre>\n<h2>Common subexpression and control flow</h2>\n<pre><code>if (checkPalindrome(mult, palindrome) == 0){\n continue; // Won't let the result = 0 when func returns 0\n}else{\n palindrome = checkPalindrome(mult, palindrome);\n}\n</code></pre>\n<p>Store the function result to avoid calling it twice, saving time and code:</p>\n<pre><code>int temp = checkPalindrome(mult, palindrome);\nif (temp == 0){\n continue; // Won't let the result = 0 when func returns 0\n}else{\n palindrome = temp;\n}\n</code></pre>\n<p>Furthermore, change the if-continue to just a negative if:</p>\n<pre><code>int temp = checkPalindrome(mult, palindrome);\nif (temp != 0){\n palindrome = temp;\n}\n</code></pre>\n<h2>Mixed concerns</h2>\n<p>Your function <code>checkPalindrome()</code> basically behaves like:</p>\n<pre><code>if (isPalindrome(a) &amp;&amp; a &gt; b)\n return b;\nelse\n return 0;\n</code></pre>\n<p>It's a weird function because it tests palindromes, figures out a maximum, or returns the special sentinel value of 0. I would advocate for writing a pure <code>isPalindrome()</code> Boolean function, and putting the maximum check in <code>main()</code> instead.</p>\n<h2>Access modifier</h2>\n<pre><code> public static int checkPalindrome(int a, int b){\n</code></pre>\n<p>The function doesn't need to be called from outside the class, so set it to <code>private</code>.</p>\n<h2>Full revised code</h2>\n<pre><code>public class TestProblem10 {\n private static int checkPalindrome(int a, int b){\n boolean palindro = false;\n\n if (a / 100000 % 10 == a % 10 &amp;&amp; a / 10000 % 10 == a % 100 / 10 &amp;&amp;\n a / 1000 % 10 == a / 100 % 10) { // Checking if it's a palidrome\n if (a &gt; b) { // Making sure to return the largest palindrome possible.\n b = a; // A = MULT B = PALINDROME\n palindro = true;\n }\n }\n if (palindro){\n return b;\n }else{\n return 0;\n }\n }\n\n public static void main(String[] args) {\n // var\n int palindrome = 0;\n\n // processing\n for (int i = 100; i &lt; 1000; i++) {\n for (int k = 100; k &lt; 1000; k++) {\n int mult = i * k;\n int temp = checkPalindrome(mult, palindrome)\n if (temp != 0){\n palindrome = temp;\n }\n }\n }\n // out\n System.out.print(&quot;Largest palindrome made from the product of two 3-digit numbers is &quot; + palindrome);\n }\n}\n</code></pre>\n<h2>My solution</h2>\n<p>Feel free to read my <a href=\"https://github.com/nayuki/Project-Euler-solutions/blob/c5adb3ddd8f8b430d073564a7a6c2e8d117a360d/java/p004.java?ts=4#L17-L31\" rel=\"nofollow noreferrer\">p004.java</a> and <a href=\"https://github.com/nayuki/Project-Euler-solutions/blob/c5adb3ddd8f8b430d073564a7a6c2e8d117a360d/java/Library.java#L14-L29\" rel=\"nofollow noreferrer\">Library.java</a>. A preview:</p>\n<pre><code>int maxPalin = -1;\nfor (int i = 100; i &lt; 1000; i++) {\n for (int j = 100; j &lt; 1000; j++) {\n int prod = i * j;\n if (Library.isPalindrome(prod) &amp;&amp; prod &gt; maxPalin)\n maxPalin = prod;\n }\n}\nreturn Integer.toString(maxPalin);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T13:15:28.460", "Id": "529442", "Score": "0", "body": "Thank you for sharing, also, why did you used ```Integer.toString``` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:19:06.363", "Id": "529446", "Score": "0", "body": "I used `Integer.toString()` because it converts the number to a base-10 string, and it can handle any length palindrome. Your function `checkPalindrome()` only works correctly for 6-digit numbers. Actually, 100 × 100 = 10000 which is a 5-digit number, so there's a new bug in the program." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T05:46:54.830", "Id": "268460", "ParentId": "268457", "Score": "1" } } ]
{ "AcceptedAnswerId": "268460", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T02:11:08.433", "Id": "268457", "Score": "1", "Tags": [ "java", "beginner", "palindrome" ], "Title": "Optimizing Code for Project Euler Problem 04" }
268457
<p>Almost a month ago I asked for some review of my first attempt at Chess in Python, with the main goal being to start learning inheritance in Python. It can be found here: <a href="https://codereview.stackexchange.com/questions/267644/first-attempt-at-chess-in-python">First attempt at chess in Python</a></p> <p>I finally have had enough time to make a bunch of the suggested changes and have since implemented changes in my code as well as a few new features. Some changes I have made include:</p> <ul> <li>En Passant</li> <li>King's can't move into Check</li> <li>Attempting to remove magic non-constant inline string variables</li> <li>Moving some piece logic into better positions</li> <li>Replacing &quot;check collisions&quot; per piece to having each piece contain a list &quot;valid moves&quot; (the idea being it will make it significantly easier to implement full king check logic in the future)</li> <li>Other smaller feedback that can be found in the previous post</li> </ul> <p>The folder structure is as follows (if you want to run it yourself):</p> <pre><code>+ main.py + board.py / pieces + __init__.py + bishop.py + king.py + knight.py + pawn.py + piece.py + queen.py + rook.py </code></pre> <p>Any further feedback would be greatly appreciated.</p> <p><strong>main.py</strong></p> <pre class="lang-py prettyprint-override"><code>from board import Board from pieces.piece import invalid_move LETTERS = &quot;ABCDEFGH&quot; NUMBERS = &quot;12345678&quot; WHITE = &quot;white&quot; BLACK = &quot;black&quot; COLOURS = (BLACK, WHITE) EXTRA_TO = &quot; to&quot; def get_input(board: Board, turn: int, extra: str = &quot;&quot;): while True: coord = input(f&quot;What position would you like to move{extra}? (eg. A2)\n&quot;) if len(coord) == 2: if coord[0].upper() in LETTERS and coord[1] in NUMBERS: if extra != EXTRA_TO: if board.get_team(coord.upper()) not in COLOURS: print(&quot;You can't move an empty square!&quot;) continue elif board.get_team(coord.upper()) != COLOURS[turn]: print(&quot;You can only move your own piece!&quot;) continue return coord.upper() print(&quot;Please write the coordinate in the form A2 (Letter)(Number)&quot;) if __name__ == &quot;__main__&quot;: board = Board() turn = 1 while True: board.display() try: start = get_input(board, turn) end = get_input(board, turn, EXTRA_TO) board.move_piece(start, end) turn = not turn except invalid_move: pass </code></pre> <p><strong>board.py</strong></p> <pre class="lang-py prettyprint-override"><code>import pieces import numpy as np ROOK = &quot;R&quot; KNIGHT = &quot;N&quot; BISHOP = &quot;B&quot; QUEEN = &quot;Q&quot; BLACK = &quot;black&quot; WHITE = &quot;white&quot; COLOURS = (BLACK, WHITE) class Board(): def __init__(self): self.board = np.full((8, 8), pieces.Piece(&quot;&quot;, -1, -1), dtype=pieces.Piece) self.valid_moves = {BLACK: [], WHITE: []} self.kings = {BLACK: None, WHITE: None} self.__setBoard() self.__update_valid_moves() def __setBoard(self): &quot;&quot;&quot;&quot;Initialise the board by creating and placing all pieces for both colours&quot;&quot;&quot; for i in range(8): self.board[1][i] = pieces.Pawn(BLACK, i, 1) self.board[6][i] = pieces.Pawn(WHITE, i, 6) for j, colour in enumerate(COLOURS): pos = j * 7 for i in (0, 7): self.board[pos][i] = pieces.Rook(colour, i, pos) for i in (1, 6): self.board[pos][i] = pieces.Knight(colour, i, pos) for i in (2, 5): self.board[pos][i] = pieces.Bishop(colour, i, pos) self.board[pos][3] = pieces.Queen(colour, 3, pos) self.kings[colour] = pieces.King(colour, 4, pos) self.board[pos][4] = self.kings[colour] for i, row in enumerate(self.board): for j, square in enumerate(row): if not square.initialised: self.board[i][j] = pieces.Piece(&quot;&quot;, j, i) def __convert_to_coords(self, position: str) -&gt; pieces.Coordinate: &quot;&quot;&quot;Convert coordinates from the Chess Syntax (ie. A2) to usable array coordinates&quot;&quot;&quot; letters = &quot;ABCDEFGH&quot; return pieces.Coordinate(letters.find(position[0]), abs(int(position[1]) - 8)) def __convert_to_alpha_coords(self, coord: pieces.Coordinate) -&gt; str: &quot;&quot;&quot;Convert coordinates from usable array coordinates to the Chess Syntax coordinates (ie. A2)&quot;&quot;&quot; letters = &quot;ABCDEFGH&quot; return letters[coord.x] + str(abs(coord.y - 8)) def __choosePromotion(self) -&gt; pieces.Piece: &quot;&quot;&quot;Logic for choosing what to promote a pawn to&quot;&quot;&quot; while True: choice = input(f&quot;What would you like to promote the Pawn to? ({ROOK}, {KNIGHT}, {BISHOP}, {QUEEN}) &quot;).upper() if choice == ROOK: return pieces.Rook elif choice == KNIGHT: return pieces.Knight elif choice == BISHOP: return pieces.Bishop elif choice == QUEEN: return pieces.Queen def __update_valid_moves(self): &quot;&quot;&quot;Updates the dictionary containing all valid moves of both sides&quot;&quot;&quot; all_valid_moves = {BLACK: [], WHITE: []} for row in self.board: for square in row: if square.team in COLOURS: square.set_valid_moves(self.board) all_valid_moves[square.team] += square.valid_moves self.valid_moves = all_valid_moves def display(self): &quot;&quot;&quot;Print the board with borders&quot;&quot;&quot; print(&quot;-&quot; * len(self.board) * 3) for i in range(len(self.board)): print('|' + '|'.join(map(str, self.board[i])) + '|') print(&quot;-&quot; * len(self.board) * 3 + '-') def get_team(self, pos: str): &quot;&quot;&quot;Returns the team of a piece at a given position (in the form A2)&quot;&quot;&quot; coord = self.__convert_to_coords(pos) return self.board[coord.y][coord.x].team def move_piece(self, start: str, end: str): &quot;&quot;&quot;Move a piece. It takes a starting position and an ending position, checks if the move is valid and then moves the piece&quot;&quot;&quot; start = self.__convert_to_coords(start) end = self.__convert_to_coords(end) piece = self.board[start.y][start.x] try: opponent_team = [team for team in COLOURS if team != piece.team][0] opponent_moves = self.valid_moves[opponent_team] piece.move(end, self.__convert_to_alpha_coords, opponent_moves) if isinstance(self.board[end.y][end.x], pieces.King): print(f&quot;{piece.team} wins!&quot;) exit() if isinstance(piece, pieces.Pawn): if end.y == 7 or end.y == 0: piece = piece.promote(self.__choosePromotion()) if end.x != start.x and self.board[end.y][end.x].initialised is False: self.board[start.y][end.x] = pieces.Piece(&quot;&quot;, start.x, start.y) print(&quot;En Passant!!&quot;) self.board[end.y][end.x] = piece self.board[start.y][start.x] = pieces.Piece(&quot;&quot;, start.x, start.y) self.__update_valid_moves() except pieces.invalid_move as e: print(e.message) raise pieces.invalid_move() </code></pre> <p><strong>__init__.py (hasn't changed)</strong></p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Taken from https://stackoverflow.com/a/49776782/12115915&quot;&quot;&quot; import os import sys dir_path = os.path.dirname(os.path.abspath(__file__)) files_in_dir = [f[:-3] for f in os.listdir(dir_path) if f.endswith('.py') and f != '__init__.py'] for f in files_in_dir: mod = __import__('.'.join([__name__, f]), fromlist=[f]) to_import = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)] # if you need classes only for i in to_import: try: setattr(sys.modules[__name__], i.__name__, i) except AttributeError: pass </code></pre> <p><strong>piece.py</strong></p> <pre class="lang-py prettyprint-override"><code>from typing import NamedTuple class Coordinate(NamedTuple): x: int y: int class Piece(): def __init__(self, team: str, x: int, y: int, initisalised: bool = False): self.team = team self.x = x self.y = y self.initialised = initisalised self.moved = False self.valid_moves = [] def __str__(self) -&gt; str: return &quot; &quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: return [] def move(self, coord: Coordinate, convert_to_alpha_coords, other_team_valid_moves=[]): if coord not in self.valid_moves: block = convert_to_alpha_coords(coord) raise invalid_move(f&quot;{block} is an invalid move!&quot;) self.x = coord.x self.y = coord.y self.moved = True class invalid_move(Exception): def __init__(self, message=&quot;&quot;): self.message = message super().__init__(message) def __str__(self) -&gt; str: return self.message </code></pre> <p><strong>bishop.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .piece import Piece from .piece import Coordinate WHITE = &quot;white&quot; class Bishop(Piece): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Piece.__init__(self, team, x, y, initisalised) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wB&quot; return &quot;bB&quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: valid = super().update_valid_moves(board=board) directions = [(1, 1), (-1, 1), (1, -1), (-1, -1)] complete_directions = [] for i in range(1, 8): for direction in directions: if direction not in complete_directions: x_val = self.x + i * direction[0] y_val = self.y + i * direction[1] if 0 &lt;= x_val &lt;= 7 and 0 &lt;= y_val &lt;= 7: if board[y_val][x_val].initialised: if board[y_val][x_val].team != self.team: valid.append(Coordinate(x_val, y_val)) complete_directions.append(direction) continue valid.append(Coordinate(x_val, y_val)) else: complete_directions.append(direction) return valid </code></pre> <p><strong>king.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .piece import Piece, invalid_move from .piece import Coordinate WHITE = &quot;white&quot; class King(Piece): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Piece.__init__(self, team, x, y, initisalised) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wK&quot; return &quot;bK&quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def move(self, coord: Coordinate, convert_to_alpha_coords, other_team_valid_moves): if coord in other_team_valid_moves: raise invalid_move(&quot;The King cannot move into check&quot;) super().move(coord, convert_to_alpha_coords, []) def update_valid_moves(self, board) -&gt; list: valid = super().update_valid_moves(board=board) directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)] for direction in directions: x_val = self.x + direction[0] y_val = self.y + direction[1] if 0 &lt;= x_val &lt;= 7 and 0 &lt;= y_val &lt;= 7: if not board[y_val][x_val].initialised or (board[y_val][x_val].initialised and board[y_val][x_val].team != self.team): valid.append(Coordinate(x_val, y_val)) return valid </code></pre> <p><strong>knight.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .piece import Piece from .piece import Coordinate from itertools import product WHITE = &quot;white&quot; class Knight(Piece): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Piece.__init__(self, team, x, y, initisalised) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wN&quot; return &quot;bN&quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: # Simple Knight logic found here: https://stackoverflow.com/a/19372692/12115915 # Much nicer looking that my alternative if elif... elif else but functionally the same moves = list(product([self.x - 1, self.x + 1], [self.y - 2, self.y + 2])) + list(product([self.x - 2, self.x + 2], [self.y - 1, self.y + 1])) valid_moves = [Coordinate(x, y) for x, y in moves if x &gt;= 0 and y &gt;= 0 and x &lt; 8 and y &lt; 8 and board[y][x].team != self.team] return valid_moves </code></pre> <p><strong>pawn.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .piece import Piece from .piece import Coordinate WHITE = &quot;white&quot; class Pawn(Piece): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Piece.__init__(self, team, x, y, initisalised) self.last_move = Coordinate(self.x, self.y) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wP&quot; return &quot;bP&quot; def move(self, coord: Coordinate, convert_to_alpha_coords, other_team_valid_moves=[]): self.last_move = Coordinate(self.x, self.y) super().move(coord, convert_to_alpha_coords) def promote(self, piece: Piece) -&gt; Piece: return piece(self.team, self.x, self.y) def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: valid = super().update_valid_moves(board) vertical_direction = 1 if self.team == WHITE: vertical_direction = -1 y_val = self.y + vertical_direction y_movements = [y_val] if not self.moved: y_movements.append(y_val + vertical_direction) for y in y_movements: if 0 &lt;= y &lt;= 7: for i in (-1, 1): xval = self.x + i if 0 &lt;= xval &lt;= 7: if board[y][xval].initialised and board[y][xval].team != self.team: valid.append(Coordinate(xval, y)) # En Passant logic if 3 &lt;= self.y &lt;= 4 and board[self.y][xval].team != self.team: if isinstance(board[self.y][xval], Pawn): if board[self.y][xval].last_move.y == self.y + vertical_direction * 2: valid.append(Coordinate(xval, y)) if not board[y][self.x].initialised: valid.append(Coordinate(self.x, y)) else: break return valid </code></pre> <p><strong>queen.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .rook import Rook from .bishop import Bishop WHITE = &quot;white&quot; class Queen(Bishop, Rook): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Bishop.__init__(self, team, x, y, initisalised) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wQ&quot; return &quot;bQ&quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: valid = super(Queen, self).update_valid_moves(board) return valid </code></pre> <p><strong>rook.py</strong></p> <pre class="lang-py prettyprint-override"><code>from .piece import Piece from .piece import Coordinate WHITE = &quot;white&quot; class Rook(Piece): def __init__(self, team: str, x: int, y: int, initisalised: bool = True): Piece.__init__(self, team, x, y, initisalised) def __str__(self) -&gt; str: if self.team == WHITE: return &quot;wR&quot; return &quot;bR&quot; def set_valid_moves(self, board): self.valid_moves = self.update_valid_moves(board) def update_valid_moves(self, board) -&gt; list: valid = super().update_valid_moves(board) directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] complete_directions = [] for i in range(1, 8): for direction in directions: if direction not in complete_directions: x_val = self.x + i * direction[0] y_val = self.y + i * direction[1] if 0 &lt;= x_val &lt;= 7 and 0 &lt;= y_val &lt;= 7: if board[y_val][x_val].initialised: if board[y_val][x_val].team != self.team: valid.append(Coordinate(x_val, y_val)) complete_directions.append(direction) continue valid.append(Coordinate(x_val, y_val)) else: complete_directions.append(direction) return valid <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T04:11:02.030", "Id": "268458", "Score": "1", "Tags": [ "python", "python-3.x", "chess" ], "Title": "First attempt at chess in Python #2" }
268458
<p>I'm an intermediate-level C++ programmer aiming to write reference-quality code. I hope to learn about any mistakes in this piece of code and blind spots in my understanding of concepts. Notes:</p> <ul> <li><p>The stylistic use of <code>public:</code>/<code>private:</code> on every member is subject of a <a href="//softwareengineering.stackexchange.com/q/346836/">question on Software Engineering</a>.</p> </li> <li><p>I'm not totally sure if I made the best choice by having the assignment operator take an object by value, instead of defining two separate assignment operators for copy-by-reference and move-by-rvalue-reference.</p> </li> <li><p>I intend to avoid all undefined behavior on all platforms. I care very much about things like integer bit width guarantees, integer type conversion rules, signed integer overflows, etc.</p> </li> <li><p>If a feature like <code>struct</code>/<code>class</code> has a C flavor and C++ flavor, I generally prefer the C++ flavor. (An exception is that I prefer value construction with <code>=</code> instead of <code>()</code> or <code>{}</code>.)</p> </li> </ul> <hr /> <h2>Sample usage:</h2> <pre class="lang-cpp prettyprint-override"><code>DisjointSet&lt;std::uint16_t&gt; ds(4); ds.mergeSets(2, 0); std::cout &lt;&lt; ds.getNumberOfSets() &lt;&lt; std::endl; // 3 std::cout &lt;&lt; ds.areInSameSet(0, 2)) &lt;&lt; std::endl; // true </code></pre> <p>(For further examples, see the accompanying <a href="https://www.nayuki.io/res/disjoint-set-data-structure/DisjointSetTest.cpp" rel="nofollow noreferrer">test program</a>.)</p> <h2>Library:</h2> <p><sub><a href="https://www.nayuki.io/res/disjoint-set-data-structure/DisjointSet.hpp" rel="nofollow noreferrer">download</a></sub></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;cstddef&gt; #include &lt;cstdint&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;vector&gt; /* * Represents a set of disjoint sets. Also known as the union-find data structure. * Main operations are querying if two elements are in the same set, and merging two sets together. * Useful for testing graph connectivity, and is used in Kruskal's algorithm. * The parameter S can be any integer type, such as size_t. For any given S, the maximum number * of sets is S_MAX. Using a smaller type like int8_t can help save memory compared to uint64_t. */ template &lt;typename S&gt; class DisjointSet final { /*---- Helper structure ----*/ private: struct Node final { // The index of the parent element. An element is a representative // iff its parent is itself. Mutable due to path compression. mutable S parent; // Always in the range [0, floor(log2(numElems))]. For practical computers, this has a maximum value of 64. // Note that signed char is guaranteed to cover at least the range [0, 127]. signed char rank; // Positive number if the element is a representative, otherwise zero. S size; }; /*---- Fields ----*/ private: std::vector&lt;Node&gt; nodes; private: S numSets; /*---- Constructors ----*/ // Constructs a new set containing the given number of singleton sets. // For example, DisjointSet(3) --&gt; {{0}, {1}, {2}}. // Even if S has a wider range than size_t, it is required that 1 &lt;= numElems &lt;= SIZE_MAX. public: explicit DisjointSet(S numElems) : numSets(numElems) { if (numElems &lt; 0) throw std::domain_error(&quot;Number of elements must be non-negative&quot;); if (!safeLessEquals(numElems, SIZE_MAX)) throw std::length_error(&quot;Number of elements too large&quot;); nodes.reserve(static_cast&lt;std::size_t&gt;(numElems)); for (S i = 0; i &lt; numElems; i++) nodes.push_back(Node{i, 0, 1}); } public: explicit DisjointSet(const DisjointSet &amp;other) = default; public: DisjointSet(DisjointSet &amp;&amp;other) = default; public: DisjointSet &amp;operator=(DisjointSet other) { std::swap(nodes , other.nodes ); std::swap(numSets, other.numSets); return *this; } /*---- Methods ----*/ // Returns the number of elements among the set of disjoint sets; this was the number passed // into the constructor and is constant for the lifetime of the object. All the other methods // require the argument elemIndex to satisfy 0 &lt;= elemIndex &lt; getNumberOfElements(). public: S getNumberOfElements() const { return static_cast&lt;S&gt;(nodes.size()); } // Returns the number of disjoint sets overall. This number decreases monotonically as time progresses; // each call to mergeSets() either decrements the number by one or leaves it unchanged. 0 &lt;= result &lt;= getNumberOfElements(). public: S getNumberOfSets() const { return numSets; } // Returns the size of the set that the given element is a member of. 1 &lt;= result &lt;= getNumberOfElements(). public: S getSizeOfSet(S elemIndex) const { return nodes.at(getRepr(elemIndex)).size; } // Tests whether the given two elements are members of the same set. Note that the arguments are orderless. public: bool areInSameSet(S elemIndex0, S elemIndex1) const { return getRepr(elemIndex0) == getRepr(elemIndex1); } // Merges together the sets that the given two elements belong to. This method is also known as &quot;union&quot; in the literature. // If the two elements belong to different sets, then the two sets are merged and the method returns true. // Otherwise they belong in the same set, nothing is changed and the method returns false. Note that the arguments are orderless. public: bool mergeSets(S elemIndex0, S elemIndex1) { // Get representatives std::size_t repr0 = getRepr(elemIndex0); std::size_t repr1 = getRepr(elemIndex1); if (repr0 == repr1) return false; // Compare ranks int cmp = nodes.at(repr0).rank - nodes.at(repr1).rank; // Note: The computation of cmp does not overflow. 0 &lt;= ranks[i] &lt;= SCHAR_MAX, // so SCHAR_MIN &lt;= -SCHAR_MAX &lt;= ranks[i] - ranks[j] &lt;= SCHAR_MAX. // The result actually fits in a signed char, and with sizeof(char) &lt;= sizeof(int), // the promotion to int still guarantees the result fits. if (cmp == 0) // Increment repr0's rank if both nodes have same rank nodes.at(repr0).rank++; else if (cmp &lt; 0) // Swap to ensure that repr0's rank &gt;= repr1's rank std::swap(repr0, repr1); // Graft repr1's subtree onto node repr0 nodes.at(repr1).parent = repr0; nodes.at(repr0).size += nodes.at(repr1).size; nodes.at(repr1).size = 0; numSets--; return true; } // For unit tests. This detects many but not all invalid data structures, throwing an exception // if a structural invariant is known to be violated. This always returns silently on a valid object. public: void checkStructure() const { S numRepr = 0; S i = 0; for (const Node &amp;node : nodes) { bool isRepr = node.parent == i; if (isRepr) numRepr++; bool ok = true; ok &amp;= 0 &lt;= node.parent &amp;&amp; safeLessThan(node.parent, nodes.size()); ok &amp;= 0 &lt;= node.rank &amp;&amp; (isRepr || node.rank &lt; nodes.at(node.parent).rank); ok &amp;= 0 &lt;= node.size &amp;&amp; safeLessEquals(node.size, nodes.size()); ok &amp;= (!isRepr &amp;&amp; node.size == 0) || (isRepr &amp;&amp; node.size &gt;= (static_cast&lt;S&gt;(1) &lt;&lt; node.rank)); if (!ok) throw std::logic_error(&quot;Assertion error&quot;); i++; } if (!(0 &lt;= numSets &amp;&amp; numSets == numRepr &amp;&amp; safeLessEquals(numSets, nodes.size()))) throw std::logic_error(&quot;Assertion error&quot;); } // (Private) Returns the representative element for the set containing the given element. This method is also // known as &quot;find&quot; in the literature. Also performs path compression, which alters the internal state to // improve the speed of future queries, but has no externally visible effect on the values returned. private: S getRepr(S elemIndex) const { // Follow parent pointers until we reach a representative S parent = nodes.at(elemIndex).parent; while (true) { S grandparent = nodes.at(static_cast&lt;std::size_t&gt;(parent)).parent; if (grandparent == parent) return static_cast&lt;std::size_t&gt;(parent); nodes.at(static_cast&lt;std::size_t&gt;(elemIndex)).parent = grandparent; // Partial path compression elemIndex = parent; parent = grandparent; } } private: static bool safeLessThan(S x, std::size_t y) { return (std::is_signed&lt;S&gt;::value &amp;&amp; x &lt; 0) || static_cast&lt;typename std::make_unsigned&lt;S&gt;::type&gt;(x) &lt; y; } private: static bool safeLessEquals(S x, std::size_t y) { return (std::is_signed&lt;S&gt;::value &amp;&amp; x &lt; 0) || static_cast&lt;typename std::make_unsigned&lt;S&gt;::type&gt;(x) &lt;= y; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:00:33.327", "Id": "529429", "Score": "1", "body": "Given that you asked for advice on the `public:`/`private:` style, why have you _ignored all the answers_ (which unanimously advised against the unusual style you have used)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:21:07.033", "Id": "529448", "Score": "0", "body": "@TobySpeight I found this style to be easier to read and maintain for me. I did initially learn C++ on the old style, and found myself often anxiously scanning upward to figure out what the most recent access modifier was." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:39:00.700", "Id": "529457", "Score": "0", "body": "I guess the question then becomes, \"_Why did you even ask?_\" I for one certainly find it harder to read than normal code. And you wouldn't need it so much if you hadn't written all the function definitions inline." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:11:20.183", "Id": "529464", "Score": "0", "body": "\"found myself often anxiously scanning upward to figure out what the most recent access modifier was\" that begs the real question: why do you ever even need to do that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:24:25.770", "Id": "529467", "Score": "0", "body": "@JDługosz 0) When reading code to bring it into human memory. 1) When reordering or adding members/methods/fields." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:27:58.350", "Id": "529468", "Score": "0", "body": "The \"section\" of document API vs that of internal implementation details is so fundamental that I'm never confused as to which I'm reading, or which group I should add something to. When reading the code it doesn't matter... that only makes a difference _outside_ that class, calling in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T10:38:03.603", "Id": "529510", "Score": "0", "body": "Do you use `rank` for anything? Also, is there any other reason you prefer one node over the other as the representative? If no to both, choose the smaller as representative and there is a 2-pass algorithm to ensure all paths are fully compressed, regardless their length before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T16:45:59.400", "Id": "529533", "Score": "0", "body": "@Deduplicator I compare ranks when merging, which guarantees O(log n) tree height. While this is correct, now that I think more, I can just get rid of the rank field, and merge by size instead. It will still guarantee O(log n) height." } ]
[ { "body": "<p>Why do you use <code>S</code> for size type? You can just use <code>std::size_t</code></p>\n<p>nondefault assignment operator with default copy constructor is unidiomatic, just let your assignment operator as <code>DisjointSet&amp; operator=(const DisjointSet&amp; other) = default;</code></p>\n<p>Setting <code>getRepr</code> as <code>const</code> but mutating <code>parent</code> inside looks very awkward, just make <code>getRepr</code> as non-const (and give a better function name)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:04:19.207", "Id": "529430", "Score": "2", "body": "I guess the reason for the awkward assignment operator is to force the use of the `explicit` copy-constructor. Not sure it's the best solution to the problem, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:13:01.497", "Id": "529444", "Score": "0", "body": "@frozenca The comment at the top of the class says, \"The parameter `S` can be any integer type, such as `size_t`. For any given `S`, the maximum number of sets is `S_MAX`. Using a smaller type like `int8_t` can help save memory compared to `uint64_t`.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:16:16.190", "Id": "529445", "Score": "0", "body": "@TobySpeight Correct. I want to make copies explicit (kind of like Rust) because copying a big vector is considered expensive. I want to avoid what happened with this [thread](https://codereview.stackexchange.com/questions/162877/disjoint-set-data-structure/162935#162935)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:03:05.153", "Id": "529463", "Score": "1", "body": "But normal C++ programmers don't make that mistake. Passing by const reference is such a basic thing and a code review issue for newbes. You're not writing a library to hand-hold inexperienced C++ programmers who aren't used to value semantics, but a normal production library, right?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T07:13:07.667", "Id": "268463", "ParentId": "268461", "Score": "0" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Use <code>include</code> guards instead of <code>#pragma once</code></h2>\n<p>The use of <code>#pragma once</code>, while common, is not standard C++. Use include guards instead as:</p>\n<pre><code>#ifndef DISJOINT_SET_HPP\n#define DISJOINT_SET_HPP\n// your header here\n#endif // DISJOINT_SET_HPP\n</code></pre>\n<p>See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf8-use-include-guards-for-all-h-files\" rel=\"noreferrer\">SF.8</a> for details.</p>\n<h2>Don't mark every data member with <code>public</code> or <code>private</code></h2>\n<p>If you are uniquely writing in this style, then almost by definition, everyone else who uses your code will find it that much more difficult to read and understand your code. Inserting unnecessary keywords adds visual clutter rather than clarity.</p>\n<h2>Avoid unneeded casts</h2>\n<p>The <code>getRepr()</code> function is declared as returning type <code>S</code>, but the return statement within it is this:</p>\n<pre><code>return static_cast&lt;std::size_t&gt;(parent);\n</code></pre>\n<p>That makes no sense at all because <code>parent</code> is already declared to be of type <code>S</code>.</p>\n<h2>Give better messages in exceptions</h2>\n<p>In the <code>checkStructure()</code> function, the code checks to verify a large number of predicates, collapsing them all into a single <code>bool</code>. If any of the conditions fails, the caller gets only the vague &quot;Assertion error&quot; message. At this point, the structure is somehow corrupted and no longer usable, which represents a rather catastrophic failure of the structure. For that reason, I'd suggest either writing each clause as a separate <code>throw</code> with a clear message or using old-fashioned <code>assert</code> which is likely to be the better choice in this case.</p>\n<h2>Move error checking to compile time where practical</h2>\n<p>The constructor currently looks like this:</p>\n<pre><code>public: explicit DisjointSet(S numElems) :\n numSets(numElems) {\n if (numElems &lt; 0)\n throw std::domain_error(&quot;Number of elements must be non-negative&quot;);\n if (!safeLessEquals(numElems, SIZE_MAX))\n throw std::length_error(&quot;Number of elements too large&quot;);\n nodes.reserve(static_cast&lt;std::size_t&gt;(numElems));\n for (S i = 0; i &lt; numElems; i++)\n nodes.push_back(Node{i, 0, 1});\n}\n</code></pre>\n<p>However, if we look carefully at this, both of the checks could actually be done at compile-time instead. That suggests that the use of C++20 <code>requires</code> or C++11 <code>enable_if</code>. Here I'm using the C++14 <code>enable_if_t</code> which is just a convenience function:</p>\n<pre><code>template &lt;typename S, \n typename = std::enable_if_t&lt;std::is_integral&lt;S&gt;::value&gt;,\n typename = std::enable_if_t&lt;std::is_unsigned&lt;S&gt;::value&gt; \n&gt;\nclass DisjointSet final {\n</code></pre>\n<p>Now if we attempt to create something invalid like <code>DisjoinSet&lt;float&gt; ds(3);</code> we get a much clearer error versus a relatively obscure and unhelpful error pointing to <code>safeLessEquals</code> or <code>checkStructure</code>.</p>\n<h2>Provide sensible default values where practical</h2>\n<p>The <code>Node</code> structure is only used internally to the <code>DisjointSet</code> class and is only created in the constructor of <code>DisjointSet</code>. For that reason, I'd suggest declaring it like this:</p>\n<pre><code>struct Node final {\n mutable S parent;\n signed char rank = 0;\n S size = 1;\n Node&amp; operator++() { ++parent; return *this; }\n};\n</code></pre>\n<p>If you're wondering about the operator, that's part of the next suggestion.</p>\n<h2>Use standard library functions where practical</h2>\n<p>I would suggest rewriting the constructor for <code>DisjointSet</code> like this:</p>\n<pre><code>explicit DisjointSet(S numElems) \n : numSets(numElems) \n , nodes(numElems) \n{\n std::iota(nodes.begin(), nodes.end(), Node{0});\n}\n</code></pre>\n<p>Note that this also assumes that we declare <code>numSets</code> before <code>nodes</code> so as not to confuse the reader. (Elements are initialized in declaration order.) In C++20, one could likely use a <code>range</code> and make this even more efficient.</p>\n<h2>Don't hide a loop return condition</h2>\n<p>The <code>getRepr()</code> function has a <code>while(true)</code>, but actually returns when the parent and grandparent are the same. I'd suggest rewriting that so that the looping exit condition is part of the loop rather than hidden within the body. For example, one way to rewrite would be this:</p>\n<pre><code>S getRepr(S elemIndex) const {\n while (nodes.at(elemIndex).parent != nodes.at(nodes.at(elemIndex).parent).parent) {\n auto parent = nodes.at(elemIndex).parent;\n // set parent = grandparent\n nodes.at(elemIndex).parent = nodes.at(parent).parent;\n elemIndex = parent;\n }\n return nodes.at(elemIndex).parent;\n}\n</code></pre>\n<h2>Define helper functions to improve readability</h2>\n<p>All of the parent and grandparent code gives the function above, even in its rewritten version, some clutter. We can greatly improve readability with the use of two helper functions:</p>\n<pre><code>S parentOf(S elemIndex) const {\n return nodes.at(elemIndex).parent;\n}\n// sets new parent and returns previous value\nS setParent(S elemIndex, S newparent) const { \n auto oldparent{parentOf(elemIndex)};\n nodes.at(elemIndex).parent = newparent;\n return oldparent;\n}\n</code></pre>\n<p>Now we can rewrite <code>getRepr</code> like this:</p>\n<pre><code>S getRepr(S elemIndex) const {\n // Follow parent pointers until we reach a representative\n for (const auto curr = parentOf(elemIndex); curr != parentOf(curr); ) {\n // set parent = grandparent\n elemIndex = setParent(elemIndex, parentOf(curr));\n }\n return parentOf(elemIndex);\n}\n</code></pre>\n<p>I find that easier to read and reason about and it's shorter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:00:03.610", "Id": "529462", "Score": "3", "body": "I disagree about `#pragma once`. All compilers support it, and if I ever do come across one that doesn't, I want to use an automated tool to put in the include guards *properly*. So many people do it wrong, using reserved names or names that are laughably non-unique. I made that decision in 1997 and never needed to. I think we'll see headers go away before we see `#pragma once` not work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T21:09:38.703", "Id": "529479", "Score": "1", "body": "I do a lot of embedded systems work and have used compilers which do not support `#pragma once`. It's an [old issue](https://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard?noredirect=1&lq=1) but the fact remains that it is non-standard and implementation defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:58:49.110", "Id": "529524", "Score": "2", "body": "Well, if you do use an include guard, don't use a simple name that _might_ clash in a system with multiple libraries used. Or even multiple copies of different versions of the _same_ library (like Boost.Serialization)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:40:06.200", "Id": "268474", "ParentId": "268461", "Score": "7" } }, { "body": "<h1>Prefer using <code>operator[]</code> instead of <code>at()</code></h1>\n<p>The member function <code>at()</code> performs bounds checking, and this comes at the cost of performance. Most of the time, you already know the indices you are using are valid. The exception is when someone can pass arbitrary values to public member functions such as <code>areInSameSet()</code>, so ideally you do the bounds checking at the top of such functions, if at all. Consider that the user of this class already knows the number of elements of the set, so it's unlikely they would ever call member functions with incorrect indices.</p>\n<h1>Use <code>uint8_t</code> for <code>rank</code></h1>\n<p>In the comments you say that <code>rank</code> is never negative, but then you explicitly declare it to be <code>signed</code>. I would make it an <code>uint8_t</code>, as this tells you it's never going to be negative, and it's being used to hold an integer, not a character.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T19:20:15.993", "Id": "268487", "ParentId": "268461", "Score": "2" } }, { "body": "<h3>High-level design:</h3>\n<p>All the other answers went over the minutiae quite sufficiently, but this is where about 66% savings are easily achieved.</p>\n<p>There are some questionable design-decisions, which complicate the code and might just bite you hard:</p>\n<ol>\n<li><p>Any query of nodes will always try to compress the path.</p>\n<p>While it is a good idea not to redo the work needlessly, this means that the constant interface is neither reentrancy nor, as there is no internal locking, concurrency safe.</p>\n<p>Why not have a read-only interface and a mutable interface, letting the caller decide on his requirements? Also, add a function optimizing the set for querying.</p>\n</li>\n<li><p><code>rank</code> is useless, as there is a better way to limit the depth of trees.</p>\n<ul>\n<li>It bloats a <code>Node</code> by half.</li>\n<li>The rank of an interior-node is irrelevant, as it is never exposed nor acted on.</li>\n<li>The rank of a root node is a simple function of the count of its descendants: <span class=\"math-container\">\\$rank = \\lceil ld(size)\\rceil\\$</span></li>\n<li>Still, no need to calculate it, as only relative rank is needed for limiting depth, which is easily done directly comparing <code>size</code>.</li>\n</ul>\n</li>\n<li><p>Any <code>Node</code> always uses either <code>size</code> or <code>parent</code>. Combine them for saving half the space, if more nodes are needed let them choose a bigger type.</p>\n<p>Half the range for ids, half for sizes (without zero).</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T00:59:50.780", "Id": "529560", "Score": "0", "body": "I essentially agree with you. 1) The fast path where a node's parent is a representative is quite reasonable. Always-compressing is necessary to achieve amortized O(log* n) time instead of O(log n) time. It is true that it throws a wrench into concurrency, and a strict const method has a valid use-case. 2) You are right and I realized this independently today; I already effected the changes on my website version. 3) I realized this too and effected the changes in the [Rust version](https://www.nayuki.io/res/disjoint-set-data-structure/disjointset.rs) today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T01:22:08.943", "Id": "529561", "Score": "0", "body": "@Nayuki Yes, the constant interface would have worse time unless the structure was prepared. Still, there is a reason I also hinted at providing a function to optimize the whole thing. Needs just one slightly worse than linear pass (because of the code limiting depth) and a linear pass. An interesting alternative would be the option of copying or moving to a frozen type, with the optimization running automatically just before. And that one could also be paired with a structure optimized for merging without queries, and then fixing it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T19:45:08.297", "Id": "268516", "ParentId": "268461", "Score": "2" } } ]
{ "AcceptedAnswerId": "268474", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T06:42:59.333", "Id": "268461", "Score": "5", "Tags": [ "c++", "algorithm", "union-find" ], "Title": "Disjoint-set data structure (C++)" }
268461
<p>I have the below data and am obtaining the expected output column for it.</p> <pre class="lang-none prettyprint-override"><code>DATA EXPECTED_OUTPUT EXPLANATION ---------------------------------------------------------------------------------------------- 123 0000000123 7 leading 0s to get to 10 characters. nan None If data is not numeric, then null/None output. 123a None If data is not numeric, then null/None output. 1111111111119 1111111119 If data length &gt;10, truncate to right 10 characters. 0 0000000000 9 leading 0s to get to 10 characters. 123.0 0000000123 Remove decimal part and leading 0s to get to 10 characters. </code></pre> <p>I have 3 ways currently of doing so, but I'm unsure whether they are the optimal solution to handle all data possibilities.</p> <pre><code># Option 1 df['DATA'] =pd.to_numeric(df['DATA'], errors='coerce').fillna(0).\ astype(np.int64).apply(str).str.zfill(10) </code></pre> <pre><code># Option 2 df['DATA'] = df['DATA'].map('{:0&gt;10}'.format).astype(str).\ str.slice(0, 10) </code></pre> <pre><code># Option 3 df['DATA'] = df['DATA'].astype(str).str.split('.', expand=True)[0].str\ .zfill(10).apply(lambda x_trunc: x_trunc[:10]) </code></pre> <p>Any help on how to improve the way of doing this will be truly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:33:52.073", "Id": "529433", "Score": "1", "body": "You might want to look through the answers to [Padding a hexadecimal string with zeros](/q/67611/75307), as it's a very similar problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T00:39:39.537", "Id": "529485", "Score": "1", "body": "@TobySpeight Sadly, I don't think that's going to buy OP a lot, since the pandas vectorized approach doesn't support the typical native approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T06:55:15.563", "Id": "529494", "Score": "0", "body": "@Reinderien, fair enough - I've never worked with pandas, so I'm speaking from a relatively ignorant position." } ]
[ { "body": "<p>Are you sure you want the non-numeric case to result in <code>None</code>? Pandas more commonly uses <code>NaN</code>. Anyway.</p>\n<p>You're missing an important test case: what do you want to happen for values with a non-zero post-decimal half?</p>\n<p>Option 1 is broken because you're just substituting 0 for non-numeric cases.</p>\n<p>Option 2 is non-vectorized due to the <code>map</code>, and will not catch <code>123a</code>; so it's broken too. As a bonus, your <code>slice(0, 10)</code> is slicing from the wrong end of the string.</p>\n<p>Option 3 is non-vectorized due to the <code>apply</code>, and does manual parsing of the decimal which is slightly awkward; it's also not going to catch non-numerics so it's broken.</p>\n<p>So I mean... if I were to be picky, none of your code is functioning as intended so closure would be justified; but what the heck:</p>\n<p>One approach that does not break vectorization and meets all of the edge cases would be</p>\n<ul>\n<li>Call <code>to_numeric(errors='coerce')</code> as you do in #1</li>\n<li>For valid numerals only, maintaining the original index:\n<ul>\n<li>cast to <code>int</code> to drop the decimal</li>\n<li>cast to <code>str</code></li>\n<li><code>zfill</code> and <code>slice</code> (from the end, not the beginning)</li>\n</ul>\n</li>\n<li>Save back to the data frame on valid indices only</li>\n<li>Fill the invalid indices with <code>None</code> (<code>fillna</code> is not sufficient for this purpose)</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\ndf = pd.DataFrame(\n [\n 123,\n float('nan'),\n '123a',\n 1111111111119,\n 0,\n 123.0,\n 123.4,\n ],\n columns=('DATA',)\n)\nas_floats = pd.to_numeric(df.DATA, errors='coerce')\nas_strings = (\n as_floats[pd.notna(as_floats)]\n .astype(int)\n .astype(str)\n .str.zfill(10)\n .str.slice(-10)\n)\ndf['out'] = as_strings\ndf.loc[pd.isna(as_floats), 'out'] = None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T00:56:42.703", "Id": "268491", "ParentId": "268462", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T07:01:16.050", "Id": "268462", "Score": "0", "Tags": [ "python", "python-3.x", "comparative-review" ], "Title": "Convert string to 10 character string with leading zeros if necessary" }
268462
<p>I have written a fully functional simple command line multi-connection downloader, written in Python 3, using just <code>threading</code>, <code>requests</code> and <code>pathlib</code> for its core functionality, plus 19 other libraries for some extra features.</p> <p>I have added resume support and it automatically resumes interrupted downloads when downloading the same URL to the same file path where a partially downloaded file is, and I fixed all the bugs contained in the code.</p> <p>The core code is extremely simple, it uses <code>requests.get</code> with <code>stream</code> enabled to download the file, it uses the <code>range</code> HTTP header to download the file in 32 segments, using one <code>Thread</code> to download each.</p> <p>However the script is extremely complex, with many additional features and poorly formatted code, making it a headache trying to extend it.</p> <p>I have added many features to the code, for example, it will validate the Windows file path, the URL format, the ping latency of the URL, and accessibility of target resource, and whether or not the server supports the <code>range</code> header, and it shows download speed, progress bar, time elapsed and ETA...</p> <p>All the features are necessary, but making the code convoluted and hard to extend.</p> <p>I plan to add GUI functionalities to the script, and I mainly intend to use it as a library inside other scripts, and add <code>argsparse</code> to it, and I also intend to make it behave differently depending on whether it is launched in a command shell or not (it should have a GUI if it is launched via <code>explorer.exe</code> while it shouldn't if it is launched via <code>pwsh.exe</code>), I am able to do these but I don't know exactly where to start...</p> <p>Here is the code:</p> <pre><code>import json import keyboard import os import psutil import random import re import requests import sys import time import validators from collections import deque from datetime import datetime from math import inf from pathlib import Path from ping3 import ping from reprint import output from requests.sessions import Session from requests.adapters import HTTPAdapter from threading import Thread from urllib3.poolmanager import PoolManager from win32gui import GetForegroundWindow from win32process import GetWindowThreadProcessId def is_active(): active = GetWindowThreadProcessId(GetForegroundWindow())[1] parents = psutil.Process().parents() for p in parents: if p.pid == active: return True return False def timestring(sec): sec = int(sec) m, s = divmod(sec, 60) h, m = divmod(m, 60) return f'{h:02d}:{m:02d}:{s:02d}' class Port_Getter: @staticmethod def busyports(): return set(i.laddr.port for i in psutil.net_connections()) def __init__(self): self.assigned = set() def randomport(self): port = random.randint(1, 65535) while port in Port_Getter.busyports() or port in self.assigned: port = random.randint(1, 65535) self.assigned.add(port) return port class Adapter(HTTPAdapter): def __init__(self, port, *args, **kwargs): self._source_port = port super(Adapter, self).__init__(*args, **kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, source_address=('', self._source_port)) class USession(Session): portassigner = Port_Getter() def __init__(self, *args, **kwargs): super(USession, self).__init__(*args, **kwargs) self.headers.update( {'connection': 'close', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'}) self.setport() def setport(self): port = USession.portassigner.randomport() self.mount('http://', Adapter(port)) self.mount('https://', Adapter(port)) class Multidown: def __init__(self, dic, id): self.count = 0 self.completed = False self.id = id self.dic = dic self.position = self.getval('position') def getval(self, key): return self.dic[self.id][key] def setval(self, key, val): self.dic[self.id][key] = val def worker(self): interrupted = True filepath = self.getval('filepath') path = Path(filepath) end = self.getval('end') if not path.exists(): start = self.getval('start') else: self.count = path.stat().st_size start = self.getval('start') + self.count url = self.getval('url') self.position = start f = path.open(mode='ab+') if self.count != self.getval('length'): interrupted = False s = USession() r = s.get( url, headers={'range': 'bytes={0}-{1}'.format(start, end)}, stream=True) while True: if self.dic['paused']: r.connection.close() r.close() s.close() interrupted = True break if (chunk := next(r.iter_content(131072), None)): f.write(chunk) self.count += len(chunk) self.position += len(chunk) self.setval('count', self.count) self.setval('position', self.position) else: break f.close() if not interrupted: r.close() s.close() if self.count == self.getval('length'): self.completed = 1 self.setval('completed', 1) class Singledown: def __init__(self): self.count = 0 def worker(self, url, path): with requests.get(url, stream=True) as r: with path.open('wb') as file: for chunk in r.iter_content(1048576): if chunk: self.count += len(chunk) file.write(chunk) class Verifier: @staticmethod def validate_filepath(path): path = path.replace('\\', '/') if (not re.match('^[a-zA-Z]:/(((?![&lt;&gt;:&quot;/|?*]).)+((?&lt;![ .])/)?)*$', path) or not Path(path[:3]).exists()): print('Invalid windows file path has been inputted, process will now stop.') return False return True @staticmethod def validate_url(url): if not validators.url(url): print('Invalid url been inputted, process will now stop.') return False if url.lower().startswith('ftp://'): print( &quot;`requests` module doesn't suport File Transfer Protocol, process will now stop&quot;) return False return True @staticmethod def confirm_overwrite(path, overwrite): filepath = str(path) if not path.exists(): return True if path.is_file(): if overwrite: return True while True: answer = input( f'`{filepath}` already exists, do you want to overwrite it? \n(Yes, No):').lower() if answer in ['y', 'yes', 'n', 'no']: if answer.startswith('y'): os.remove(filepath) return True print('Invalid input detected, retaking input.') print(f'Overwritting {filepath} has been aborted, process will now stop.') return False @staticmethod def test_connection(url): server = url.split('/')[2] ok = ping(server, timeout=2) if ok == False: print( 'The server of the inputted url is non-existent, process will now stop.') return False if ok: return True if not ok: print('Connection has timed out, will reattempt to ping server 5 times.') for i in range(5): print( f'Reattempting to ping server, retrying {i + 1} out of 5') ok = ping(server, timeout=2) if ok: print( f'Connection successful on retry {i + 1}, process will now continue.') return True print(f'Retry {i + 1} out of 5 timed out' + (i != 4) * ', reattempting in 1 second.' + (i == 4) * '.') time.sleep(1) print('Failed to connect server, connection timed out, process will now stop') return False @staticmethod def validate_accessible(url): head = requests.head(url) if head.status_code == 200: return True for i in range(5): print(f'Server responce is invalid, retrying {i + 1} out of 5') head = requests.head(url) if head.status_code == 200: print( f'Connection successful on retry {i + 1}, process will now continue.') return True print(f'Retry {i + 1} out of 5 failed to access data' + (i != 4) * ', reattempting in 1 second.' + (i == 4) * '.') time.sleep(1) print(&quot;Can't establish a connection with access to data, can't download target file, process will now stop.&quot;) return False class Downloader: def __init__(self): self.recent = deque([0] * 12, maxlen=12) self.recentspeeds = deque([0] * 200, maxlen=200) self.dic = dict() self.workers = [] def download(self, url, filepath, num_connections=32, overwrite=False): bcontinue = Path(filepath + '.progress.json').exists() singlethread = False threads = [] path = Path(filepath) if not Verifier.validate_filepath(filepath): raise ValueError() if not Verifier.validate_url(url): raise ValueError() if not bcontinue: if not Verifier.confirm_overwrite(path, overwrite): raise InterruptedError() if not Verifier.test_connection(url): raise TimeoutError() if not Verifier.validate_accessible(url): raise PermissionError() head = requests.head(url) folder = '/'.join(filepath.split('/')[:-1]) Path(folder).mkdir(parents=True, exist_ok=True) headers = head.headers total = headers.get('content-length') if not total: print( f'Cannot find the total length of the content of {url}, the file will be downloaded using a single thread.') started = datetime.now() print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S')) sd = Singledown() th = Thread(target=sd.worker, args=(url, path)) self.workers.append(sd) th.start() total = inf singlethread = True else: total = int(total) if not headers.get('accept-ranges'): print( 'Server does not support the `range` parameter, the file will be downloaded using a single thread.') started = datetime.now() print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S')) sd = self.Singledown() th = Thread(target=sd.singledown, args=(url, path)) self.workers.append(sd) th.start() singlethread = True else: if bcontinue: progress = json.loads(Path(filepath + '.progress.json').read_text(), object_hook=lambda d: {int(k) if k.isdigit() else k: v for k, v in d.items()}) segment = total / num_connections started = datetime.now() lastpressed = started print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S')) self.dic['total'] = total self.dic['connections'] = num_connections self.dic['paused'] = False for i in range(num_connections): if not bcontinue: start = int(segment * i) end = int(segment * (i + 1)) - (i != num_connections - 1) position = start length = end - start + (i != num_connections - 1) else: start = progress[i]['start'] end = progress[i]['end'] position = progress[i]['position'] length = progress[i]['length'] self.dic[i] = { 'start': start, 'position': position, 'end': end, 'filepath': filepath + '.' + str(i).zfill(2) + '.part', 'count': 0, 'length': length, 'url': url, 'completed': False } for i in range(num_connections): md = Multidown(self.dic, i) th = Thread(target=md.worker) threads.append(th) th.start() self.workers.append(md) Path(filepath + '.progress.json').write_text(json.dumps(self.dic, indent=4)) downloaded = 0 totalMiB = total / 1048576 speeds = [] interval = 0.04 with output(initial_len=5, interval=0) as dynamic_print: while True: Path(filepath + '.progress.json').write_text(json.dumps(self.dic, indent=4)) status = sum([i.completed for i in self.workers]) downloaded = sum(i.count for i in self.workers) self.recent.append(downloaded) done = int(100 * downloaded / total) doneMiB = downloaded / 1048576 gt0 = len([i for i in self.recent if i]) if not gt0: speed = 0 else: recent = list(self.recent)[12 - gt0:] if len(recent) == 1: speed = recent[0] / 1048576 / interval else: diff = [b - a for a, b in zip(recent, recent[1:])] speed = sum(diff) / len(diff) / 1048576 / interval speeds.append(speed) self.recentspeeds.append(speed) nzspeeds = [i for i in speeds if i] if nzspeeds: minspeed = min(nzspeeds) else: minspeed = 0 maxspeed = max(speeds) now = datetime.now() elapsed = (now - started).total_seconds() meanspeed = downloaded / elapsed / 1048576 remaining = totalMiB - doneMiB dynamic_print[0] = '[{0}{1}] {2}'.format( '\u2588' * done, '\u00b7' * (100-done), str(done)) + '% completed' + (not singlethread) * ', paused: {0}'.format(self.dic['paused']) dynamic_print[1] = 'Download mode: ' + singlethread * \ 'Single-thread' + (not singlethread) * 'Multi-thread (press Space to pause/resume, press Escape to stop)' dynamic_print[2] = '{0:.2f} MiB downloaded, {1:.2f} MiB total, {2:.2f} MiB remaining, download speed: {3:.2f} MiB/s'.format( doneMiB, totalMiB, remaining, speed) if speed and total != inf: eta = timestring(remaining / speed) else: eta = '99:59:59' dynamic_print[3] = 'Minimum speed: {0:.2f} MiB/s, average speed: {1:.2f} MiB/s, maximum speed: {2:.2f} MiB/s'.format( minspeed, meanspeed, maxspeed) dynamic_print[4] = 'Task started on {0}, {1} elapsed, ETA: {2}'.format( started.strftime('%Y-%m-%d %H:%M:%S'), timestring(elapsed), eta) if keyboard.is_pressed('space') and is_active(): if not singlethread: pressed = datetime.now() if (pressed - lastpressed).total_seconds() &gt; 0.5: lastpressed = pressed if self.dic['paused']: for md in self.workers: if not md.completed: th = Thread(target=md.worker) th.start() threads.append(th) self.dic['paused'] = not self.dic['paused'] if self.dic['paused']: time.sleep(0.1) while threads: th = threads.pop(0) th.join() if keyboard.is_pressed('esc'): if not singlethread: ended = datetime.now() self.dic['paused'] = True break if status == len(self.workers): if not singlethread: BLOCKSIZE = 4096 BLOCKS = 1024 CHUNKSIZE = BLOCKSIZE * BLOCKS with path.open('wb') as dest: for i in range(32): file = filepath + '.' + str(i).zfill(2) + '.part' with Path(file).open('rb') as f: while (chunk := f.read(CHUNKSIZE)): dest.write(chunk) Path(file).unlink() ended = datetime.now() break time.sleep(interval) time_spent = (ended - started).total_seconds() meanspeed = total / time_spent / 1048576 status = sum([i.completed for i in self.workers]) if status == len(self.workers): print('Task completed on {0}, total time elapsed: {1}, average speed: {2:.2f} MiB/s'.format( ended.strftime('%Y-%m-%d %H:%M:%S'), timestring(time_spent), meanspeed)) Path(filepath + '.progress.json').unlink() else: print('Task interrupted on {0}, total time elapsed: {1}, average speed: {2:.2f} MiB/s'.format( ended.strftime('%Y-%m-%d %H:%M:%S'), timestring(time_spent), meanspeed)) if __name__ == '__main__': d = Downloader() d.download(*sys.argv[1:]) </code></pre> <p>Example:</p> <pre><code>downloader.py 'http://ipv4.download.thinkbroadband.com/1GB.zip' 'D:/Downloads/1GB.zip' </code></pre> <p>The downloaded file's SHA-256 hash should be: <code>5674e59283d95efe8c88770515a9bbc80cbb77cb67602389fd91def26d26aed2</code>.</p> <p>How should I format my code?</p> <p>In particular, what to do with the text prompts? What to do with the if conditions? And how should the &quot;main loop&quot; be correctly realized? Should I split my code into multiple files? If I should, then what should they be like?</p>
[]
[ { "body": "<p>Too bad I can't run it because of the Windows parts, but otherwise from\nthe first look of it, it's pretty nice.</p>\n<blockquote>\n<p>How should I format my code?</p>\n</blockquote>\n<p>I'd consider using <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><code>black</code></a> for\nauto-formatting, respectively running a PEP8 linter every so often.</p>\n<blockquote>\n<p>In particular, what to do with the text prompts?</p>\n</blockquote>\n<p>You mean with a GUI? You'd have to do (modal) GUI prompts. The whole\narchitecture will be pretty different and it's generally not going to be\nthe case that each method can drive user input like you're doing here. Or at least it would be detrimental to the overall design since you'd always be locked into this mode of operation (prompting the user).</p>\n<blockquote>\n<p>What to do with the if conditions?</p>\n</blockquote>\n<p>I don't know exactly what you're referring to here.</p>\n<blockquote>\n<p>And how should the &quot;main loop&quot; be correctly realized?</p>\n</blockquote>\n<p>The main loop is, depending on which framework you'll use (not raw\nwin32 windows, right? I'd really suggest avoiding going that\nlow-level), simply going to be a framework method that you'll call and\nwhich only returns when the application shuts down. Everything else\nwill be events and callbacks.</p>\n<p>For anything that needs to be processed concurrently you'll have to add\na thread - that's probably what you'll have to do for the actual\ndownloads, that, or fully event-driven, which'd mean, that the event\nloop will have to listen to data being available on the sockets and\nreact appropriately.</p>\n<p>That is btw. also how you could already restructure the main loop here,\ninstead of busy looping, check for input from standard input / wherever\nthe keyboard comes from, then use the same thing for events from each\nworker thread, something like an event queue.</p>\n<blockquote>\n<p>Should I split my code into multiple files? If I should, then what\nshould they be like?</p>\n</blockquote>\n<p>There's arguments for it, mostly just related to being able to put\nrelated things together and the ability to navigate. If it works for\nyou, it's not a necessity to have multiple files.</p>\n<p>That being said, the <code>Downloader.download</code> method is huge. I need\nroughly four screens to go through it, that's impossible to keep all in\nmy head! So, I'd suggest splitting that up into more manageable chunks.</p>\n<hr />\n<ul>\n<li><p><code>is_active</code> consider <code>any</code> like\n<code>return any(p.pid == active for p in parents)</code> instead of a manual\nloop.</p>\n</li>\n<li><p><code>Port_Getter</code> should be <code>PortGetter</code>.</p>\n</li>\n<li><p><code>USession</code> could do with a better name, maybe <code>UserAgentSession</code> or\njust <code>UserSession</code>.</p>\n</li>\n<li><p><code>Verifier.validate_filepath</code>'s regular expression is interesting, I\nwouldn't know whether it's too strict or too loose.</p>\n</li>\n<li><p><code>Verifier.test_connection</code> three checks for <code>ok</code>, that's at least one\ntoo many. And as you did correctly later, <code>ok == False</code> is better\nwritten as <code>not ok</code>.</p>\n</li>\n<li><p>I'd let the validate methods immediately throw exceptions. That'd\nconvey more information than a <code>True</code>/<code>False</code> can, anyway. Also\nconsider adding some useful information for the reader into those\nexceptions too, like what's currently in the <code>print</code> statements! This\nwould also go a long way to making the change to a GUI version -\n<code>print</code> you can't catch that easily, but exceptions you can.</p>\n</li>\n<li><p><code>test_connection</code> and <code>validate_accessible</code> does ... two HTTP\nrequests? On top of the one to actually download things? That feels\nexcessive to me.</p>\n</li>\n<li><p><code>self.dic</code> - anti-pattern, if you need that for dumping/reading\nto/from JSON make <code>to_json</code>/<code>from_json</code> methods and implement\nserialisation there. That way you're not restricted to any particular\nshape of that data and things like IDEs can make a more educated\nguess. Even typing the values might be possible.=</p>\n<p>If you decide to stick with it, consider implementing dictionary\naccess on the <code>Multidown</code> class, so that <code>self.count</code> would directly\naccess the dictionary, or <code>self[&quot;count&quot;]</code> would be possible too.</p>\n</li>\n<li><p>I see a lot of <code>close</code> calls - consider implementing <code>with</code> support\nand generally be aware of exception safety.</p>\n</li>\n<li><p><code>131072</code> is a magic constant, make it one; since it's <code>128 * 1024</code> aka\n128kb, mention that, or at least write it <code>CHUNK_SIZE = 128 * 1024</code>\n(maybe even something like\n<code>KILO_BYTE = 1024; CHUNK_SIZE = 128 * KILO_BYTE</code>, but that's a bit\nexcessive too, most people know what 1024 means). Oh I see you did\nthat later - then reuse that, I doubt there need to be multiple\ndiffering chunk sizes.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:35:44.180", "Id": "268566", "ParentId": "268465", "Score": "2" } }, { "body": "<p>Just a few remarks from me. Not a comprehensive review. I appreciate your effort, I have not tested your code and I am on Linux anyway.</p>\n<p>But the thing that surprised me the most was the lack of <strong>comments</strong>. Also the lack of line spacing in the functions. I know that the code is long already, but that cannot be an excuse.</p>\n<p>I think you should split the project by putting all your classes in a separate file, then you import it. Then you can concentrate on the core functionality of your project.</p>\n<p>There are some minor improvements you can make, for example use <code>context managers</code> with files like you did on line 142:</p>\n<pre><code>with path.open('wb') as file:\n</code></pre>\n<p>Do the same line for 107 and elsewhere:</p>\n<pre><code>f = path.open(mode='ab+')\n</code></pre>\n<p>An alternative is to enclose the snippet in a try/finally block - the catch clause is optional (but it's good to have a generic exception handler in place). Then put the cleanup code in the finally section.</p>\n<p>Using pathlib for handling file paths/names was a sound decision, even though your application is not cross-platform.</p>\n<p>As mentioned already, the naming conventions can be improved a bit. For example at line 24 there is a function called <code>is_active</code> but it's not immediately obvious if we are talking about a download, a process, a requests session or something else. The function names should therefore be more intuitive and instantly convey the intended purpose.</p>\n<p>In class <code>USession</code> the <strong>user agent</strong> is hard-coded. Providing a default value makes sense but it may be useful to override the value for specific needs. Also provide additional headers if needed.</p>\n<p>I would replace the prints with the <strong>logging</strong> module and send output to both console and a log file. Then you can more easily review the execution of your script, especially if it's going to run unattended or if you miss output due to limited screen buffer size. A decent tutorial: <a href=\"https://realpython.com/python-logging/\" rel=\"nofollow noreferrer\">Logging in Python</a></p>\n<p>Some of your tests may fail, for example in function <code>test_connection</code>: a web server may be running fine but not reply to a ping because of a firewall. I would ditch that test. You could run a DNS query instead, to verify that the domain name can be resolved. Does not mean reachable though. But this is a rough test that doesn't cost much, and the result should be cached by your DNS resolver for the next request. It will have to do a DNS query anyway, unless your download URL contains an IP address instead of a domain name.</p>\n<p>In that ping function you can simplify this:</p>\n<pre><code>if ok == False:\n print(\n 'The server of the inputted url is non-existent, process will now stop.')\n return False\nif ok:\n return True\n</code></pre>\n<p>If ok is a boolean value, then it can be directly returned as such regardless of whether it is true or false:</p>\n<pre><code>return ok\n</code></pre>\n<p>or:</p>\n<pre><code>if not ok:\n print('The server of the inputted url is non-existent, process will now stop.')\n\nreturn ok\n</code></pre>\n<p>The thing is, do you really need to do all those tests that are slowing you down ? You could just cut to the chase and attempt the download right away after a minimum of validation.</p>\n<p>And in that function, instead of doing this:</p>\n<pre><code>server = url.split('/')[2]\n</code></pre>\n<p>you could use the <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\">URL parser module</a> instead to extract the URL components.</p>\n<p>In function <code>validate_accessible</code> you first try to determine if the resource if available by performing a HEAD request. I don't have any stats to back up this statement, but I think a good number of web applications do not implement the method in their pages. For example I often see Django/Flask applications that only respond to GET and POST requests, because these are the only valid methods defined for their routes.</p>\n<p>The problem with HEAD nowadays, is that a lot of content is generated dynamically, so the CPU cost of handling a HEAD request server-side may be pretty much the same as a regular GET request. HEAD is useful for static content, when the web server can determine the content length for a file right away, and also provides the information in the returned headers.\nWhat you are doing makes sense but is probably not so useful in this age. I would discard that test probably.</p>\n<p>A web server could return a content length of zero, then you'll have a <strong>division by zero</strong> exception at line 344:</p>\n<pre><code> done = int(100 * downloaded / total)\n</code></pre>\n<p>It would be interesting to measure the <strong>execution time</strong> of individual bits of code. Another link for you: <a href=\"https://realpython.com/python-timer/\" rel=\"nofollow noreferrer\">Python Timer Functions: Three Ways to Monitor Your Code</a>. You could use their codetiming class to measure download time too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T23:01:19.793", "Id": "268582", "ParentId": "268465", "Score": "2" } }, { "body": "<h2><code>Port_Getter</code></h2>\n<p>Since <code>randomport</code> both checks whether a port it listed in <code>busyports</code> and whether this getter has already been assigned that port, I'm led to assume it's possible for one to be true but not the other. Which would seem to imply that a port that has been assigned to one getter and is not currently busy might end up assigned to another getter. Is that intentional?</p>\n<p>By convention, short-lived connections tend to get assigned port numbers above 49152, so as to not conflict with applications and protocols that expect to be able to operate on specific port numbers that are known in advance. It might be good to respect that</p>\n<p>The repeated-random-selection approach to picking a random available port works, but feels a bit ugly. Granted, the only alternative I can think of would be to maintain a set of all available ports and sample from that, which might not be ideal</p>\n<p>Conventionally, this'd be called <code>PortGetter</code> instead. The methods <code>busyports</code> and <code>randomport</code> would be called <code>busy_ports</code> and <code>random_port</code></p>\n<p>65535 is a magic number, and should probably be given a named constant. 49152 would need one as well</p>\n<h2><code>Adapter</code></h2>\n<p><code>init_poolmanager</code> doesn't seem to ever get called. Does it?</p>\n<p>I believe <code>super(Adapter, self)</code> can be simplified to just <code>super()</code></p>\n<h2><code>USession</code></h2>\n<p>The name is a bit unclear - what does the U stand for? Also, <code>setport</code> would conventionally be <code>set_port</code></p>\n<p>What's with the Firefox user agent? I mean, user agents are fairly meaningless so you aren't <em>wrong</em> to send it, but do you need to?</p>\n<h2><code>Multidown</code></h2>\n<p>Using a shared dictionary for <code>Multidown</code>s to communicate back with their creator feels a bit strange to me. Having that data stored on the <code>Multidown</code> itself could offer more control, might make it clearer what data is actually available, and would prevent one thread from accidentally changing another thread's data (which would probably have weird consequences). <code>self.dic[self.id]['start']</code> does look a lot messier than <code>self.start</code></p>\n<p><code>worker</code> could maybe use some breaking up - at least a blank line or two, if not actually breaking it into multiple pieces. It's a bit on the long side</p>\n<p>Side note, this exists only to be a context for the <code>worker</code> function to run in - so in terms of name, might it be more useful to refer to this object as a <code>Worker</code> or <code>DownloadWorker</code> or something? Or maybe something like <code>ParallelWorker</code> to distinguish it from <code>Singledown</code>?</p>\n<h2><code>Singledown</code></h2>\n<p>This feels like just a special case of <code>Multidown</code> - is it even necessary to have this?</p>\n<p>If it is, I'm not a huge fan of how this, unlike <code>Multidown</code>, does not seem to allow itself to be interrupted ahead of time. Keep in mind that this'll also probably be slower than a pile of <code>Multidown</code>s, so a user would probably be <em>more</em> likely to need to interrupt it ahead of time</p>\n<p>Like <code>Multidown</code>, this is also a type of worker, and could maybe be renamed accordingly.</p>\n<p>1048576 is a magic number</p>\n<h2><code>Verifier</code></h2>\n<p>This is just a bag of static methods that don't even interact with eachothers. Why is this a class instead of just standalone functions? When would you want a <code>Verifier</code> object? How would two <code>Verifier</code> objects be different? If the answers are &quot;you wouldn't&quot; and &quot;they wouldn't&quot;, and it looks like they are, the class isn't really doing anything by being a class, is it?</p>\n<p>I'm not sure the validation functions should be responsible for printing the error messages - you may want to use them in other ways. It'd be more flexible to let (or, ideally, force) the caller to decide what to do, ideally by raising an exception</p>\n<p>What's with the <code>Path(path[:3].exists())</code> check? I assume it's to check for device files, but it seems to have both false positives (<code>CONNECTION.txt</code> starts with <code>CON</code> but is a legal file name) and false negatives (I believe <code>LPT1</code> is a device file but I don't think <code>LPT</code> is). I think <code>Path(path).is_file()</code> may be closer to what you're looking for?</p>\n<p><code>validate_url</code> will accept any protocol not specifically rejected. I think the opposite would make more sense, since there number of supported protocols is finite.</p>\n<p><code>confirm_overwrite</code> feels like it has two jobs - prompting a user for input until they provide a yes/no answer is a nicely defined task that could probably be separated out into its own function.</p>\n<h2><code>Downloader</code></h2>\n<p><code>download</code> is very long, and could almost certainly be divided into more manageable pieces - it's directly responsible for all of the following things:</p>\n<ul>\n<li>Creating the folder to download into</li>\n<li>Check whether the server reports a content-length and accepts ranges, and decide which download method to use</li>\n<li>Creating the worker threads</li>\n<li>Figuring out whether to resume a previous download</li>\n<li>Calculating download speed</li>\n<li>Combining pieces of a multi-part download into a single file</li>\n<li>Providing feedback to the user</li>\n<li>Managing keyboard input from the user</li>\n</ul>\n<p>That's a lot of different responsibilities. They're pretty interweaved right now, but I think untangling and separating them (where possible) could go a long way to making this code easier to read and modify</p>\n<p>I'm pretty sure <code>Singledown</code> is not part of the <code>Downloader</code> class, so I doubt creating a &quot;<code>self.Singledown</code>&quot; will work</p>\n<p><code>&quot;99:59:59&quot;</code> is not a very good ETA for cases when you might not even know how much stuff you're downloading. If you don't know the ETA, just say you don't know</p>\n<p>You only combine data from the first 32 parts, even if you have more than 32 workers</p>\n<p>You also assume the chunks are all in order and all equal size, which seems like it might not be the case if you start a download, cancel it, and then later resume it with a different number of workers - your program <em>as a whole</em> will never do that, but <code>download</code> doesn't know that and probably shouldn't assume</p>\n<p>You keep constructing <code>filepath + '.progress.json'</code> by hand in like seven different places. If you do it once and pass it around, any future changes to how that data is stored become much easier to make</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T18:50:35.060", "Id": "268601", "ParentId": "268465", "Score": "1" } } ]
{ "AcceptedAnswerId": "268566", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:18:46.087", "Id": "268465", "Score": "4", "Tags": [ "python", "python-3.x", "multithreading" ], "Title": "Python 3 Multi-connection downloader" }
268465
<p>I am required to code (as part of a 3-question assignment) a variable-size connect 4 board with a standard size of 6x7, with a minimum size of 2x2 and a maximum of 20x20. The professor said that he could do it in 20 lines, and the maximum one can write is 3 times that. My code sits uncomfortably close to it at 58 lines. What can I do to cut it down without using user-defined functions?</p> <pre class="lang-py prettyprint-override"><code>r, c, p, a, std, b = 0, 0, 0, '', input('Standard game? (y/n): '), ' ' if std == 'y': r, c = 6, 7 else: r, c = int(input('r? (2 - 20): ')), int(input('c? (2 - 20): ')) if r &lt; 11 and c &lt; 11: for i in range (r-1, -1, -1): a = str(i) for j in range (c): a = a + str(' ·') #repeats the dot for j times print(a + ' ') for j in range (c): b = b + ' ' + str(j) #adds successive nos. to the bottom row, ie the index print(b + ' ') elif r &lt; 11 and c &gt;= 11: a, b = ' ', ' ' for i in range (r-1, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + ' ' + str('· ') print(a) for j in range (10): b = b + ' ' + str(j) for j in range (10, c): b = b + ' ' + str(j) print(b + ' ') elif r &gt;= 11 and c &lt; 11: b = ' ' for i in range (r-1, 9, -1): a = str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &gt;= 10 (i.e. no space) for i in range (9, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &lt; 10 (space) for j in range (c): b = b + ' ' + str(j) print(b + ' ') else: a, b = ' ', ' ' for i in range (r-1, 9, -1): a = str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &gt;= 10 (i.e. no space) for i in range (9, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) for j in range (10): b = b + ' ' + str(j) for j in range (10, c): b = b + ' ' + str(j) print(b + ' ') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:55:03.320", "Id": "529435", "Score": "1", "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": "2021-09-28T18:29:38.683", "Id": "529470", "Score": "1", "body": "Are you not allowed to use user-defined functions? What kind of class is this?" } ]
[ { "body": "<p>I was able to do it in just <em>3 lines</em>!</p>\n<p>Here is the code:</p>\n<pre><code>if input('Standard game? (y/n): ') == 'y': r, c = 6, 7\nelse: r, c = int(input('r? (2 - 20): ')), int(input('c? (2 - 20): '))\nprint('\\n'.join([*[str(i).ljust(2) + ' .' + ' .' * (c - 1) for i in range(r)], *[' '+''.join([str(i).rjust(3) for i in range(c)])]]))\n</code></pre>\n<p>I will explain it step by step</p>\n<ul>\n<li><p><code>if input('Standard game? (y/n): ') == 'y': r, c = 6, 7</code>\nThis line is rather simple, it takes input and checks if it is equal to <code>'y'</code>, if so then <code>r, c = 6, 7</code>.</p>\n</li>\n<li><p><code>else: r, c = int(input('r? (2 - 20): ')), int(input('c? (2 - 20): '))</code>\nElse we take input for <code>r, c</code>.</p>\n</li>\n<li><p>Now the main line, I will split it in multiple lines to explain.</p>\n</li>\n</ul>\n<p>You can refer about <a href=\"https://www.programiz.com/python-programming/methods/string/join\" rel=\"nofollow noreferrer\"><code>.join()</code></a>, <a href=\"https://www.programiz.com/python-programming/methods/string/ljust\" rel=\"nofollow noreferrer\"><code>.ljust()</code></a> and <a href=\"https://www.programiz.com/python-programming/methods/string/rjust\" rel=\"nofollow noreferrer\"><code>.rjust()</code></a>.</p>\n<p><code>*[str(i).ljust(2) + ' .' + ' .' * (c - 1) for i in range(r)]</code></p>\n<p>This will just get the string representation of the row indexes and the rows and unpack it.</p>\n<p><code>*[' '+''.join([str(i).rjust(3) for i in range(c)])</code></p>\n<p>This will get the string representation for the column indexes and unpack it.</p>\n<p>Finally, we join them with a <code>'\\n'</code> and print it.</p>\n<p>Thats it!</p>\n<p>Happy Coding!</p>\n<h2>Edit</h2>\n<p>I was able to do it in <em>2 lines</em> using a tenary operator.</p>\n<pre><code>r, c = (6, 7) if input('Standard game? (y/n): ') == 'y' else (int(input('r? (2 - 20): ')), int(input('c? (2 - 20): ')))\nprint('\\n'.join([*[str(i).ljust(2) + ' .' + ' .' * (c - 1) for i in range(r - 1, -1, -1)], *[' '+''.join([str(i).rjust(3) for i in range(c)])]]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T07:24:00.210", "Id": "529496", "Score": "0", "body": "Your 2-line solution numbers the y-axis the wrong way round, you'll need to change `range(r)` to `range(r - 1, -1, -1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T15:39:43.250", "Id": "529844", "Score": "1", "body": "You are correct. Updated my answer accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:53:01.973", "Id": "268480", "ParentId": "268466", "Score": "1" } }, { "body": "<p>I will focus on creating a readable, maintainable and scalable implementation. Even without sacrificing readbaility (by avoiding things like multiple variable assignments per line), this implementation comes in at only 15 lines. This number could be reduced further by inlining some variables, etc. but I don't think that's worth doing here.</p>\n<p>Please note that this does not include proper validation of user input, which is generally a good idea.</p>\n<hr />\n<p><strong>Complete code</strong></p>\n<p>I added some blank lines for the sake of readability:</p>\n<pre><code>standard_game = input('Standard game? (y/n): ').lower() == &quot;y&quot;\n\nif standard_game:\n ROWS = 6\n COLUMNS = 7\nelse:\n ROWS = int(input('ROWS? (2 - 20): '))\n COLUMNS = int(input('COLUMNS? (2 - 20): '))\n \nwidth_y_axis_elements = len(str(ROWS - 1))\nwidth_x_axis_elements = len(str(COLUMNS - 1)) + 1\n\ndots = '·'.rjust(width_x_axis_elements) * COLUMNS\n\nfor i in range(ROWS - 1, -1, -1):\n label = str(i).rjust(width_y_axis_elements)\n print(f&quot;{label}{dots}&quot;)\n \nx_axis = ''.join(map(lambda s: s.rjust(width_x_axis_elements), map(str, range(COLUMNS))))\nprint(f&quot;{' ' * width_y_axis_elements}{x_axis}&quot;)\n</code></pre>\n<p>The key to simplifying this implementation is realizing that <code>ROWS</code> and <code>COLUMNS</code> being below or above 10 aren't actually special cases. You only need to consider the length of the highest number on each axis and then pad everything accordingly. For this we use <a href=\"https://www.w3schools.com/python/ref_string_rjust.asp\" rel=\"nofollow noreferrer\"><code>str.rjust</code></a>. Once you understand this conceptually, the implementation is rather straightforward. Don't hesitate to ask for clarifiction if necessary!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:44:08.577", "Id": "529529", "Score": "0", "body": "Thanks for your input! My class hasn't introduced str.rjust or f threads yet, so I'm not sure if I'm allowed to use this, but I'll take that idea in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T22:55:16.103", "Id": "529556", "Score": "0", "body": "You can easily replace f-strings with string concatenation, so `f\"{label}{dots}\"` becomes `label + dots`. You could also implement `str.rjust` on your own by checking the length of your input string, comparing it to the desired length and adding spaces to the front of the string until the desired length is reached." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T18:14:53.150", "Id": "268482", "ParentId": "268466", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:42:02.990", "Id": "268466", "Score": "2", "Tags": [ "python", "homework", "connect-four" ], "Title": "Print a Connect 4 board" }
268466
<p>This is my code for a simple used car sales platform, with flex used for the DIVs: <a href="https://jsfiddle.net/m56npe32/" rel="nofollow noreferrer">https://jsfiddle.net/m56npe32/</a></p> <p>I am looking for constructive criticism on how to improve the design, as the entire code works well at a basic level.</p> <p>Embedded within is:</p> <pre><code>&lt;div class=&quot;row&quot;&gt; &lt;article class=&quot;col-lg-3&quot;&gt; &lt;div class=&quot;img&quot;&gt; &lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/2001_Ford_Mustang_Premium.jpg/1024px-2001_Ford_Mustang_Premium.jpg&quot;&gt; &lt;/div&gt; &lt;p&gt;&lt;b&gt;1995 FORD Mustang 4.0 V6 COUPE 2dr&lt;/b&gt; black &lt;b&gt;$3995&lt;/b&gt;&lt;/p&gt; &lt;/article&gt; &lt;article class=&quot;col-lg-3&quot;&gt; &lt;div class=&quot;img&quot;&gt; &lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Oldsmobile_Cutlass_Ciera_S_%284132352802%29.jpg/800px-Oldsmobile_Cutlass_Ciera_S_%284132352802%29.jpg&quot;&gt; &lt;/div&gt; &lt;p&gt;&lt;b&gt;1995 CHEVROLET Oldsmobile Cutlass 3.1 V6 4dr Auto&lt;/b&gt; white, 107,000 miles, import from Baja California &lt;b&gt;$990&lt;/b&gt;&lt;/p&gt; &lt;/article&gt; &lt;article class=&quot;col-lg-3&quot;&gt; &lt;div class=&quot;img&quot;&gt; &lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/f/f1/%2793-%2795_Toyota_Supra.jpg&quot;&gt; &lt;/div&gt; &lt;p&gt;&lt;b&gt;1993 TOYOTA Supra 3.0i 2dr Coupe&lt;/b&gt; bright red, originally from Grande Prairie, TX, titled here in NH, U.S. spec, not an import &lt;b&gt;$7990&lt;/b&gt;&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; </code></pre> <p>That works well, but what if I wanted to do it so that the text was next to the image and ensure it fits the DIV and to make this compatible with modern browsers or mobile, as I've got a User Agent Switcher add-on on Firefox for OS X?</p> <p>As a HTML page, it works fine, although I should add the CSS link won't work in the JSFiddle, but that's in the code.</p> <p>I'm looking at trying to improve this to modernize it a bit, and perhaps improve it esthetically if need be.</p> <p>It's intended as the view for an MVC in PHP, or as a HTML template as its other main usage.</p> <p>I'm concentrating on the HTML for now.</p> <p>Any advice is welcomed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:55:55.257", "Id": "529459", "Score": "0", "body": "If you want more code than that snippet of HTML reviewed then please expand the code here. [Please embed the code to be reviewed directly in the question](https://codereview.meta.stackexchange.com/a/3653/120114). Links to code hosted on third-party sites are permissible, but the most relevant excerpts must be embedded in the question itself. A [stack snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) could also be used to embed the code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T11:47:50.850", "Id": "268467", "Score": "0", "Tags": [ "html", "css", "html5" ], "Title": "Simple flex-based design for automotive sales platform in HTML5" }
268467
<p>So I've made a dashboard, and I have alot of colors / icons on this page. One of the things I wanted to get some others view on was the design I've choosen.</p> <p>I use bootstrap background colors: <code>primary, success, danger, warning, dark</code>, so all icons can appear with this background.</p> <p>To change the colors on the clouds/sun ect, just change the CSS colors, maybe add more colors to the animated svg?</p> <p>It can look like this on the website: <a href="https://i.stack.imgur.com/uhdyZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uhdyZ.png" alt="enter image description here" /></a></p> <p>I would like to get some response on my design, or even ideas to changes.</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-css lang-css prettyprint-override"><code>/* Weather icon on dashboard*/ .element_weather { height: 30px !important; width: 30px !important; } .container_weather { display: flex; justify-content: center; flex-direction: column; align-items: center; } .elements_weather { display: flex; justify-content: center; flex-wrap: wrap; } .white { fill: #edf8ff } .gray { fill: #cecece } .yellow { fill: #fabb33 } .overflow-hidden { display: flex; justify-content: left; /* this 2 properties is used to center vertically and horizontally */ align-items: center; } .overflow-hidden span { order: 1; align-items: left; /* this change order of elements */ } #svg_dashboard_weather { position: relative; width: 25px; height: 25px; order: 2; /* this change order of elements */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"&gt; &lt;script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;li id="272_3824" class="list-group-item list-group-item-success"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=272,2521,3824" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="5/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44.9 44.9" style="enable-background:new 0 0 44.9 44.9;" xml:space="preserve" height="25px" width="25px"&gt; &lt;g id="Sun"&gt; &lt;circle id="XMLID_61_" class="yellow" cx="22.4" cy="22.6" r="11"&gt;&lt;/circle&gt; &lt;g&gt; &lt;path id="XMLID_60_" class="yellow" d="M22.6,8.1h-0.3c-0.3,0-0.6-0.3-0.6-0.6v-7c0-0.3,0.3-0.6,0.6-0.6l0.3,0c0.3,0,0.6,0.3,0.6,0.6 v7C23.2,7.8,22.9,8.1,22.6,8.1z"&gt;&lt;/path&gt; &lt;path id="XMLID_59_" class="yellow" d="M22.6,36.8h-0.3c-0.3,0-0.6,0.3-0.6,0.6v7c0,0.3,0.3,0.6,0.6,0.6h0.3c0.3,0,0.6-0.3,0.6-0.6v-7 C23.2,37,22.9,36.8,22.6,36.8z"&gt;&lt;/path&gt; &lt;path id="XMLID_58_" class="yellow" d="M8.1,22.3v0.3c0,0.3-0.3,0.6-0.6,0.6h-7c-0.3,0-0.6-0.3-0.6-0.6l0-0.3c0-0.3,0.3-0.6,0.6-0.6h7 C7.8,21.7,8.1,21.9,8.1,22.3z"&gt;&lt;/path&gt; &lt;path id="XMLID_57_" class="yellow" d="M36.8,22.3v0.3c0,0.3,0.3,0.6,0.6,0.6h7c0.3,0,0.6-0.3,0.6-0.6v-0.3c0-0.3-0.3-0.6-0.6-0.6h-7 C37,21.7,36.8,21.9,36.8,22.3z"&gt;&lt;/path&gt; &lt;path id="XMLID_56_" class="yellow" d="M11.4,31.6l0.2,0.3c0.2,0.2,0.2,0.6-0.1,0.8l-5.3,4.5c-0.2,0.2-0.6,0.2-0.8-0.1l-0.2-0.3 c-0.2-0.2-0.2-0.6,0.1-0.8l5.3-4.5C10.9,31.4,11.2,31.4,11.4,31.6z"&gt;&lt;/path&gt; &lt;path id="XMLID_55_" class="yellow" d="M33.2,13l0.2,0.3c0.2,0.2,0.6,0.3,0.8,0.1l5.3-4.5c0.2-0.2,0.3-0.6,0.1-0.8l-0.2-0.3 c-0.2-0.2-0.6-0.3-0.8-0.1l-5.3,4.5C33,12.4,33,12.7,33.2,13z"&gt;&lt;/path&gt; &lt;path id="XMLID_54_" class="yellow" d="M11.4,13.2l0.2-0.3c0.2-0.2,0.2-0.6-0.1-0.8L6.3,7.6C6.1,7.4,5.7,7.5,5.5,7.7L5.3,7.9 C5.1,8.2,5.1,8.5,5.4,8.7l5.3,4.5C10.9,13.5,11.2,13.5,11.4,13.2z"&gt;&lt;/path&gt; &lt;path id="XMLID_53_" class="yellow" d="M33.2,31.9l0.2-0.3c0.2-0.2,0.6-0.3,0.8-0.1l5.3,4.5c0.2,0.2,0.3,0.6,0.1,0.8l-0.2,0.3 c-0.2,0.2-0.6,0.3-0.8,0.1l-5.3-4.5C33,32.5,33,32.1,33.2,31.9z"&gt;&lt;/path&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="0.5s" keyTimes="0;0.5;1" repeatCount="indefinite" values="1;0.6;1" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;3824 - FirmwareUpdateOfElements&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li id="277_6359" class="list-group-item list-group-item-primary"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=277,5789,6359" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="4/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 61.7 42.8" style="enable-background:new 0 0 61.7 42.8;" xml:space="preserve"&gt; &lt;g id="Cloud_3"&gt; &lt;g id="White_cloud_3"&gt; &lt;path id="XMLID_24_" class="white" d="M47.2,42.8H7.9c-4.3,0-7.9-3.5-7.9-7.9l0,0C0,30.5,3.5,27,7.9,27h39.4c4.3,0,7.9,3.5,7.9,7.9 v0C55.1,39.2,51.6,42.8,47.2,42.8z"&gt;&lt;/path&gt; &lt;circle id="XMLID_23_" class="white" cx="17.4" cy="25.5" r="9.3"&gt;&lt;/circle&gt; &lt;circle id="XMLID_22_" class="white" cx="34.5" cy="23.9" r="15.6"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;5;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Sun_3"&gt; &lt;circle id="XMLID_30_" class="yellow" cx="31.4" cy="18.5" r="9"&gt;&lt;/circle&gt; &lt;g&gt; &lt;path id="XMLID_31_" class="yellow" d="M31.4,6.6L31.4,6.6c-0.4,0-0.6-0.3-0.6-0.6V0.6C30.8,0.3,31,0,31.3,0l0.1,0 C31.7,0,32,0.3,32,0.6v5.5C32,6.4,31.7,6.6,31.4,6.6z"&gt;&lt;/path&gt; &lt;path id="XMLID_34_" class="yellow" d="M31.4,30.1L31.4,30.1c-0.4,0-0.6,0.3-0.6,0.6v5.5c0,0.3,0.3,0.6,0.6,0.6h0.1 c0.3,0,0.6-0.3,0.6-0.6v-5.5C32,30.4,31.7,30.1,31.4,30.1z"&gt;&lt;/path&gt; &lt;path id="XMLID_35_" class="yellow" d="M19.6,18.3L19.6,18.3c0,0.4-0.3,0.6-0.6,0.6h-5.5c-0.3,0-0.6-0.3-0.6-0.6v-0.1 c0-0.3,0.3-0.6,0.6-0.6H19C19.3,17.8,19.6,18,19.6,18.3z"&gt;&lt;/path&gt; &lt;path id="XMLID_33_" class="yellow" d="M43.1,18.3L43.1,18.3c0,0.4,0.3,0.6,0.6,0.6h5.5c0.3,0,0.6-0.3,0.6-0.6v-0.1 c0-0.3-0.3-0.6-0.6-0.6h-5.5C43.4,17.8,43.1,18,43.1,18.3z"&gt;&lt;/path&gt; &lt;path id="XMLID_37_" class="yellow" d="M22.4,26L22.4,26c0.3,0.3,0.2,0.7,0,0.9l-4.2,3.6c-0.2,0.2-0.6,0.2-0.8-0.1l-0.1-0.1 c-0.2-0.2-0.2-0.6,0.1-0.8l4.2-3.6C21.9,25.8,22.2,25.8,22.4,26z"&gt;&lt;/path&gt; &lt;path id="XMLID_36_" class="yellow" d="M40.3,10.7L40.3,10.7c0.3,0.3,0.6,0.3,0.8,0.1l4.2-3.6c0.2-0.2,0.3-0.6,0.1-0.8l-0.1-0.1 c-0.2-0.2-0.6-0.3-0.8-0.1l-4.2,3.6C40.1,10.1,40,10.5,40.3,10.7z"&gt;&lt;/path&gt; &lt;path id="XMLID_39_" class="yellow" d="M22.4,10.8L22.4,10.8c0.3-0.3,0.2-0.7,0-0.9l-4.2-3.6c-0.2-0.2-0.6-0.2-0.8,0.1l-0.1,0.1 c-0.2,0.2-0.2,0.6,0.1,0.8l4.2,3.6C21.9,11,22.2,11,22.4,10.8z"&gt;&lt;/path&gt; &lt;path id="XMLID_38_" class="yellow" d="M40.3,26.1L40.3,26.1c0.3-0.3,0.6-0.3,0.8-0.1l4.2,3.6c0.2,0.2,0.3,0.6,0.1,0.8l-0.1,0.1 c-0.2,0.2-0.6,0.3-0.8,0.1l-4.2-3.6C40.1,26.7,40,26.3,40.3,26.1z"&gt;&lt;/path&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="0.5s" keyTimes="0;0.5;1" repeatCount="indefinite" values="1;0.6;1" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;/g&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="2s" keyTimes="0;1" repeatCount="indefinite" type="scale" values="1;1" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Gray_cloud_3"&gt; &lt;path id="XMLID_20_" class="gray" d="M55.7,25.1H34.4c-3.3,0-6-2.7-6-6v0c0-3.3,2.7-6,6-6h21.3c3.3,0,6,2.7,6,6v0 C61.7,22.4,59,25.1,55.7,25.1z"&gt;&lt;/path&gt; &lt;circle id="XMLID_19_" class="gray" cx="46.7" cy="13.4" r="10.7"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;-3;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;6359 - EXT24V_Relay&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li id="420_3775" class="list-group-item list-group-item-danger"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=420,2423,3775" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="3/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 60.7 40" style="enable-background:new 0 0 60.7 40;" xml:space="preserve"&gt; &lt;g id="Cloud_1"&gt; &lt;g id="White_cloud_1"&gt; &lt;path id="XMLID_2_" class="white" d="M47.2,40H7.9C3.5,40,0,36.5,0,32.1l0,0c0-4.3,3.5-7.9,7.9-7.9h39.4c4.3,0,7.9,3.5,7.9,7.9v0 C55.1,36.5,51.6,40,47.2,40z"&gt;&lt;/path&gt; &lt;circle id="XMLID_3_" class="white" cx="17.4" cy="22.8" r="9.3"&gt;&lt;/circle&gt; &lt;circle id="XMLID_4_" class="white" cx="34.5" cy="21.1" r="15.6"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;5;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Gray_cloud_1"&gt; &lt;path id="XMLID_6_" class="gray" d="M54.7,22.3H33.4c-3.3,0-6-2.7-6-6v0c0-3.3,2.7-6,6-6h21.3c3.3,0,6,2.7,6,6v0 C60.7,19.6,58,22.3,54.7,22.3z"&gt;&lt;/path&gt; &lt;circle id="XMLID_7_" class="gray" cx="45.7" cy="10.7" r="10.7"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;-3;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;3775 - WaterHammerMonitoring_VTU&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li id="272_2472" class="list-group-item list-group-item-primary"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=272,667,2472" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="2/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 55.1 60" style="enable-background:new 0 0 55.1 49.5;" xml:space="preserve"&gt; &lt;g id="Cloud_2"&gt; &lt;g id="Rain_2"&gt; &lt;path id="rain_2_left" class="white" d="M20.7,46.4c0,1.7-1.4,3.1-3.1,3.1s-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S20.7,44.7,20.7,46.4z"&gt;&lt;/path&gt; &lt;path id="rain_2_mid" class="white" d="M31.4,46.4c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S31.4,44.7,31.4,46.4z"&gt;&lt;/path&gt; &lt;path id="rain_2_right" class="white" d="M41.3,46.4c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S41.3,44.7,41.3,46.4z"&gt;&lt;/path&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="1s" keyTimes="0;1" repeatCount="indefinite" type="translate" values="0 0;0 10" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="1s" keyTimes="0;1" repeatCount="indefinite" values="1;0" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;g id="White_cloud_2"&gt; &lt;path id="XMLID_14_" class="white" d="M47.2,34.5H7.9c-4.3,0-7.9-3.5-7.9-7.9l0,0c0-4.3,3.5-7.9,7.9-7.9h39.4c4.3,0,7.9,3.5,7.9,7.9 v0C55.1,30.9,51.6,34.5,47.2,34.5z"&gt;&lt;/path&gt; &lt;circle id="XMLID_13_" class="white" cx="17.4" cy="17.3" r="9.3"&gt;&lt;/circle&gt; &lt;circle id="XMLID_10_" class="white" cx="34.5" cy="15.6" r="15.6"&gt;&lt;/circle&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;2472 - GBPVersion&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li id="422_2472" class="list-group-item list-group-item-warning"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=422,667,2472" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="1/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 60.7 48.7" style="enable-background:new 0 0 60.7 48.7;" xml:space="preserve"&gt; &lt;g id="Cloud_4"&gt; &lt;g id="White_cloud_4"&gt; &lt;path id="XMLID_69_" class="white" d="M47.2,40H7.9C3.5,40,0,36.5,0,32.1l0,0c0-4.3,3.5-7.9,7.9-7.9h39.4c4.3,0,7.9,3.5,7.9,7.9v0 C55.1,36.5,51.6,40,47.2,40z"&gt;&lt;/path&gt; &lt;circle id="XMLID_68_" class="white" cx="17.4" cy="22.8" r="9.3"&gt;&lt;/circle&gt; &lt;circle id="XMLID_67_" class="white" cx="34.5" cy="21.1" r="15.6"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;5;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Gray_cloud_4"&gt; &lt;path id="XMLID_65_" class="gray" d="M54.7,22.3H33.4c-3.3,0-6-2.7-6-6v0c0-3.3,2.7-6,6-6h21.3c3.3,0,6,2.7,6,6v0 C60.7,19.6,58,22.3,54.7,22.3z"&gt;&lt;/path&gt; &lt;circle id="XMLID_64_" class="gray" cx="45.7" cy="10.7" r="10.7"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;-3;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Lightning_4"&gt; &lt;path id="XMLID_79_" class="yellow" d="M43.6,22.7c-0.2,0.6-0.4,1.3-0.6,1.9c-0.2,0.6-0.4,1.2-0.7,1.8c-0.4,1.2-0.9,2.4-1.5,3.5 c-1,2.3-2.2,4.6-3.4,6.8l-1.7-2.9c3.2-0.1,6.3-0.1,9.5,0l3,0.1l-1.3,2.5c-1.1,2.1-2.2,4.2-3.5,6.2c-0.6,1-1.3,2-2,3 c-0.7,1-1.4,2-2.2,2.9c0.2-1.2,0.5-2.4,0.8-3.5c0.3-1.2,0.6-2.3,1-3.4c0.7-2.3,1.5-4.5,2.4-6.7l1.7,2.7c-3.2,0.1-6.3,0.2-9.5,0 l-3.4-0.1l1.8-2.8c1.4-2.1,2.8-4.2,4.3-6.2c0.8-1,1.6-2,2.4-3c0.4-0.5,0.8-1,1.3-1.5C42.7,23.7,43.1,23.2,43.6,22.7z"&gt;&lt;/path&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="1.5s" keyTimes="0;0.5;1" repeatCount="indefinite" values="1;0;1" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;2472 - GBPVersion&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li id="272_3232" class="list-group-item list-group-item-dark"&gt; &lt;a class="text-dark" href="testresults?dashboardIds=272,1914,3232" target="_blank"&gt; &lt;div class="overflow-hidden justify-content-between"&gt; &lt;div id="svg_dashboard_weather" class="element_weather justify-content-between" title="0/5"&gt; &lt;svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 60.7 80" style="enable-background:new 0 0 60.7 55;" xml:space="preserve"&gt; &lt;g id="Cloud_6"&gt; &lt;g id="White_cloud_6"&gt; &lt;path id="XMLID_81_" class="white" d="M47.2,40H7.9C3.5,40,0,36.5,0,32.1l0,0c0-4.3,3.5-7.9,7.9-7.9h39.4c4.3,0,7.9,3.5,7.9,7.9v0 C55.1,36.5,51.6,40,47.2,40z"&gt;&lt;/path&gt; &lt;circle id="XMLID_80_" class="white" cx="17.4" cy="22.8" r="9.3"&gt;&lt;/circle&gt; &lt;circle id="XMLID_77_" class="white" cx="34.5" cy="21.1" r="15.6"&gt;&lt;/circle&gt; &lt;/g&gt; &lt;g id="Gray_cloud_6"&gt; &lt;path id="XMLID_75_" class="gray" d="M54.7,22.3H33.4c-3.3,0-6-2.7-6-6v0c0-3.3,2.7-6,6-6h21.3c3.3,0,6,2.7,6,6v0 C60.7,19.6,58,22.3,54.7,22.3z"&gt;&lt;/path&gt; &lt;circle id="XMLID_74_" class="gray" cx="45.7" cy="10.7" r="10.7"&gt;&lt;/circle&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="6s" keyTimes="0;0.5;1" repeatCount="indefinite" type="translate" values="0;-3;0" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;/g&gt; &lt;g id="Lightning_6"&gt; &lt;path id="XMLID_94_" class="yellow" d="M43.6,22.7c-0.2,0.6-0.4,1.3-0.6,1.9c-0.2,0.6-0.4,1.2-0.7,1.8c-0.4,1.2-0.9,2.4-1.5,3.5 c-1,2.3-2.2,4.6-3.4,6.8l-1.7-2.9c3.2-0.1,6.3-0.1,9.5,0l3,0.1l-1.3,2.5c-1.1,2.1-2.2,4.2-3.5,6.2c-0.6,1-1.3,2-2,3 c-0.7,1-1.4,2-2.2,2.9c0.2-1.2,0.5-2.4,0.8-3.5c0.3-1.2,0.6-2.3,1-3.4c0.7-2.3,1.5-4.5,2.4-6.7l1.7,2.7c-3.2,0.1-6.3,0.2-9.5,0 l-3.4-0.1l1.8-2.8c1.4-2.1,2.8-4.2,4.3-6.2c0.8-1,1.6-2,2.4-3c0.4-0.5,0.8-1,1.3-1.5C42.7,23.7,43.1,23.2,43.6,22.7z"&gt;&lt;/path&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="1.5s" keyTimes="0;0.5;1" repeatCount="indefinite" values="1;0;1" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;g id="Rain_6"&gt; &lt;path id="Rain_6_right" class="white" d="M36.3,51.9c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S36.3,50.2,36.3,51.9z"&gt;&lt;/path&gt; &lt;path id="Rain_6_mid" class="white" d="M26.4,51.9c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S26.4,50.2,26.4,51.9z"&gt;&lt;/path&gt; &lt;path id="Rain_6_left" class="white" d="M15.7,51.9c0,1.7-1.4,3.1-3.1,3.1s-3.1-1.4-3.1-3.1c0-1.7,3.1-7.8,3.1-7.8 S15.7,50.2,15.7,51.9z"&gt;&lt;/path&gt; &lt;animateTransform attributeName="transform" attributeType="XML" dur="1s" keyTimes="0;1" repeatCount="indefinite" type="translate" values="0 0;0 10" calcMode="linear"&gt; &lt;/animateTransform&gt; &lt;animate attributeType="CSS" attributeName="opacity" dur="1s" keyTimes="0;1" repeatCount="indefinite" values="1;0" calcMode="linear"&gt;&lt;/animate&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; &lt;span class="mr-2"&gt;3232 - UltrasonicBasedDryRunDetection&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt;</code></pre> </div> </div> </p> <p>Made a change to the icons, so the rain drops are blue. <a href="https://i.stack.imgur.com/cfSJE.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfSJE.gif" alt="enter image description here" /></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T12:14:53.940", "Id": "268468", "Score": "0", "Tags": [ "html", "css", "svg", "bootstrap-4" ], "Title": "Weather status on dashboard design" }
268468
<pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; int main() { vector&lt;int&gt; primes; int n = 100; // amount of numbers - 1 vector&lt;bool&gt; sieve; for (int i = 0; i &lt;= n; i++) { // creating vector with all true values sieve.push_back(true); } // let's set 0 and 1 to false because well we know they're not prime already. sieve[0] = false; sieve[1] = false; // we'll make it so all elements that are set to true are prime numbers. int p = 2; // setting p to first prime number. while (p != 11) { int i = 2 * p; for (int j = 1; j &lt;= (n / p) - 1; j++) { // sets all p's multiples to false. sieve[i] = false; i = i + p; } for (int i = 2; i &lt;= 100; i++) { // checking for first number greater than p // that is prime and setting p equal to it if (sieve[i] == true &amp;&amp; i &gt; p) { p = i; break; } } } for (int i = 0; i &lt; sieve.size(); i++) { if (sieve[i] == true) { // if the number is prime: primes.push_back(i); // put it into the primes vector. } } for (int x: primes) { cout &lt;&lt; x &lt;&lt; endl; } cin &gt;&gt; n; } </code></pre> <p>First question: Is this like a terrible way to implement the algorithm? I had trouble doing this and finally came up with this solution but I don't know if it's terrible and a very bad way.</p> <p>Second question: do you know how I can possibly change the <code>while</code> condition to make it more flexible? In my case I made it <code>p!=11</code> because in the range 1-100 there's no point in checking for primes after 7; the program will find the next prime after 7 to be 11 but I'll stop it from continuing. If I want to make it keep going I'll have to change the <code>while</code> loop condition or find some solution to make it stop running after it's found all primes in the range; how can I do this?</p>
[]
[ { "body": "<ol>\n<li><p>You are missing <code>std::</code> on some of the elements; it should be:</p>\n<pre><code>std::vector&lt;int&gt; primes;\n</code></pre>\n</li>\n<li><p>Instead of using a <code>for</code> loop to push the values into the <code>vector</code> one at a time, you can use the 'fill' constructor:</p>\n<pre><code>std::vector&lt;bool&gt; sieve(n + 1, true);\n</code></pre>\n</li>\n<li><p>Create a function that is reusable:</p>\n<pre><code>std::vector&lt;int&gt; calcPrimes(int n) {\n std::vector&lt;int&gt; primes;\n ...\n return primes;\n}\n\nint main()\n{\n std::vector&lt;int&gt; primes = calcPrimes(100);\n for (int x : primes) \n std::cout &lt;&lt; x &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n</li>\n<li><p>Magic Numbers - what is the significance of <code>11</code> here? If <code>n</code> was less than 11, this would have resulted in an endless loop.</p>\n<pre><code> while (p != 11) {\n</code></pre>\n<p>Consider replacing it with:</p>\n<pre><code> int minRoot = std::sqrt(n);\n while (p &lt;= minRoot) {\n ...\n</code></pre>\n</li>\n<li><p>I'm assuming that the following line:</p>\n<pre><code> for (int i = 2; i &lt;= 100; i++) {\n</code></pre>\n<p>should have been:</p>\n<pre><code> for (int i = 2; i &lt;= n; i++) {\n</code></pre>\n<p>You may also consider using <code>std::find()</code> instead of this loop.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:08:06.307", "Id": "268470", "ParentId": "268469", "Score": "1" } }, { "body": "<p><code>std::vector&lt;bool&gt;</code> isn't a great idea. It doesn't work like a standard container (despite the very similar name). <code>std::vector&lt;char&gt;</code> will be faster, and we can almost certainly afford the space when <code>n</code> is 100. Alternatively, change to <code>constexpr n</code>, and we can use a fixed-size container such as <code>std::array&lt;bool,n&gt;</code> (which <em>is</em> a standard container) or <code>std::bitset&lt;n&gt;</code>.</p>\n<p>If we're using <code>std::vector</code>, we should avoid it reallocating. We could do this with a <code>sieve.reserve()</code> before the <code>push_back()</code> loop, or we could populate the sieve like this:</p>\n<pre><code>vector&lt;bool&gt; sieve(n, true);\n\n// 0 and 1 non-prime\nsieve[0] = false;\nsieve[1] = false;\n</code></pre>\n<p>Inverting the sense (so <code>true</code> in the sieve means &quot;composite&quot; rather than &quot;prime&quot;) simplifies the initialization, because default-initialisation is to <code>false</code>.</p>\n<p>The test <code>while (p != 11)</code> is tightly tied to the size of the sieve. A better test would be <code>while (p &lt;= sieve.size() / p)</code> - though we'll want an unsigned type for <code>p</code> to avoid problems with mixed-signedness arithmetic (<code>std::size_t</code> is an unsigned type).</p>\n<p>The &quot;marking&quot; phase can be simplified:</p>\n<blockquote>\n<pre><code> int i = 2 * p;\n for (int j = 1; j &lt;= (n / p) - 1; j++) { // sets all p's multiples to false.\n sieve[i] = false;\n i = i + p;\n }\n</code></pre>\n</blockquote>\n<p>Instead of introducing the new variable <code>j</code>, why not use <code>i</code> as the control? Like this:</p>\n<pre><code> for (unsigned int i = 2 * p; i &lt; n; i += p) {\n sieve[i] = false;\n }\n</code></pre>\n<p>And we don't need to start at <code>2 * p</code> because we know that every multiple less than <code>p</code>² has already been crossed off - so replace that with <code>p * p</code>.</p>\n<p>The following loop doesn't need to start at the beginning every time:</p>\n<blockquote>\n<pre><code> for (int i = 2; i &lt;= 100; i++) { // checking for first number greater than p\n // that is prime and setting p equal to it\n if (sieve[i] == true &amp;&amp; i &gt; p) {\n p = i;\n break;\n }\n }\n</code></pre>\n</blockquote>\n<p>We can replace with <code>for (i = p + 1; i &lt; n; ++i)</code> to search beginning just after <code>p</code>. Or since we're using this to find the next <code>p</code>, just</p>\n<pre><code> // increase p to next prime\n while (!sieve[++p])\n ;\n</code></pre>\n<p>We could even just put that test at the start of the main loop:</p>\n<pre><code>while (p &lt;= sieve.size() / p) {\n if (!sieve[p]) {\n continue;\n }\n for (unsigned int i = p * p; i &lt; n; i += p) {\n sieve[i] = false;\n }\n}\n</code></pre>\n<p>There seems no need for the <code>primes</code> variable. All we do is push the primes into it, then read them back to print them. We could just print as we go:</p>\n<pre><code>for (unsigned i = 0; i &lt; sieve.size(); ++i) {\n if (sieve[i]) {\n std::cout &lt;&lt; i &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<p>Or even just within the main <code>p</code> loop - though we'll need to make that continue up to the end rather than stopping at √n. (That's not such a big overhead once we've changed the striking off to begin at p², of course).</p>\n<p>Note there's no need to flush every line with <code>std::endl</code> - plain newline is less wasteful.</p>\n<p>Why do we attempt to read a value into <code>n</code>? That is utterly pointless, as it's never used.</p>\n<p>We can halve the number of loops executed by first marking all even numbers (apart from 2), and then incrementing by twice what we were.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Simpler and more efficient:</p>\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n constexpr std::size_t n = 100;\n std::array&lt;bool,n&gt; sieve{}; // true means composite\n\n // mark all even numbers\n for (std::size_t i = 4; i &lt; n; i += 2) {\n sieve[i] = true;\n }\n std::cout &lt;&lt; &quot;2\\n&quot;;\n\n for (std::size_t p = 3; p &lt; n; p += 2) {\n if (sieve[p]) {\n // composite\n continue;\n }\n // it's prime!\n std::cout &lt;&lt; p &lt;&lt; '\\n';\n // remove its multiples\n for (std::size_t i = p * p; i &lt; n; i += p * 2) {\n sieve[i] = true;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T17:17:58.867", "Id": "529465", "Score": "0", "body": "I suspect that he used `cin >> n;` to keep the program from closing before showing the results in the IDE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T07:04:27.257", "Id": "529495", "Score": "0", "body": "@Johan, what do you mean by \"closing\"? Are you saying that some runtime environments hide the output when the process finishes? That sounds very unhelpful, and we'd have to recommend finding a better shell/debugger/whatever." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T08:46:33.850", "Id": "529501", "Score": "0", "body": "I'm not suggesting that it's a good practice. see this [question](https://stackoverflow.com/questions/21257544/c-wait-for-user-input)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:24:59.603", "Id": "268473", "ParentId": "268469", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T13:02:23.520", "Id": "268469", "Score": "2", "Tags": [ "c++", "sieve-of-eratosthenes" ], "Title": "Sieve of Eratosthenes for primes up to 100" }
268469
<p>I'm creating a few macros that open specific Outlook templates an allow you to replace specific tokens before sending the email. It seems to work, but I'm admittedly doing full loops when I probably don't <em>need to</em>. So I'm just wondering if anyone sees a better way to approach this.</p> <p>As you can see below, <code>loop through entire dictionary</code> is a common enough theme</p> <p>Basic synopsis:</p> <ol> <li>Define a regex, in my case anything in square brackets get replaced</li> <li>Loop through the Subject and the Body looking for tokens</li> <li>Add each token to a dictionary so that I have unique tokens and only need to provide a replacement string once</li> <li>Loop through the entire dictionary and get replacement strings</li> <li>Loop through the entire dictionary and replace each token in the Subject</li> <li>Loop through the entire dictionary and replace each token in the Body</li> </ol> <pre class="lang-vb prettyprint-override"><code>Sub FindAndReplaceTokens(TemplatePath As String) Dim regexObject As Object 'RegEx to find and capture the tokens Dim Matches As Object 'Collection of matches Dim dict As Object 'Dictionary to keep unique tokens and their replacement values Dim NewMail As Outlook.MailItem 'The email itself Dim oString As String 'Original strings to be replaced Dim newString As String 'Replacement strings Dim i As Integer 'counter for looping through Matches Dim key As Variant 'counter for looping through dictionary Dim SubjectReplace As Boolean 'True if the subject has a token to replace Dim BodyReplace As Boolean 'True if body has a token to replace 'Create the email earlier in case there are issues with this, at least we'll know first thing 'TemplatePath should be the full path ending in .oft identifying the template we're using Set NewMail = CreateItemFromTemplate(TemplatePath) Set regexObject = CreateObject(&quot;VBScript.RegExp&quot;) With regexObject .Pattern = &quot;(\[[^\]]+\])&quot; .Global = True End With Set dict = CreateObject(&quot;Scripting.Dictionary&quot;) 'Check for replacements in the subject If regexObject.test(NewMail.Subject) Then SubjectReplace = True Set Matches = regexObject.Execute(NewMail.Subject) For i = 0 To (Matches.Count - 1) 'Debug.Print Matches(i).SubMatches(0) oString = Matches(i).SubMatches(0) dict(oString) = dict(oString) + 1 Next i End If 'Check for replacements in the body If regexObject.test(NewMail.Body) Then BodyReplace = True Set Matches = regexObject.Execute(NewMail.Body) For i = 0 To (Matches.Count - 1) 'Debug.Print Matches(i).SubMatches(0) oString = Matches(i).SubMatches(0) dict(oString) = dict(oString) + 1 Next i End If If SubjectReplace Or BodyReplace Then For Each key In dict.keys 'Debug.Print key, dict(key) newString = InputBox(&quot;What should be used in place of &quot; &amp; key &amp; &quot;?&quot;, &quot;Replacement for &quot; &amp; dict(key) &amp; &quot; of &quot; &amp; key) If newString = &quot;&quot; Then newString = key dict(key) = newString 'Debug.Print key, dict(key) Next key With NewMail If SubjectReplace Then For Each key In dict.keys .Subject = Replace(.Subject, key, dict(key)) Next key End If If BodyReplace Then If .BodyFormat = olFormatPlain Then For Each key In dict.keys .Body = Replace(.Body, key, dict(key)) Next key ElseIf .BodyFormat = olFormatHTML Then For Each key In dict.keys .HTMLBody = Replace(.HTMLBody, key, dict(key)) Next key End If End If End With End If 'Display the message NewMail.Display End Sub <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:49:26.373", "Id": "529449", "Score": "1", "body": "The fact that you have to have a comment to describe each variable you're declaring tells me that your variable names aren't very good. For example, `SubjectReplace` could be named `replacementInSubject`, then your statement later reads `If replacementInSubject or replaementInBody Then`. Makes it read a bit more English-like and eliminates the need for the comment. Lather, rinse, repeat on other variable names." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T14:30:23.820", "Id": "268471", "Score": "1", "Tags": [ "vba", "outlook" ], "Title": "Outlook VBA to Replace Tokens from an email template" }
268471
<p>I recently started studying C++ programming; while attending the course I'm writing a program on the side as a personal project to familiarize with what I'm learning. It is still very basic and I'm sure that as I begin learning OOP there will be a lot of room for improving it. But for now I would like your feedback / suggestion to understand if the logic / coding I wrote is correct and where I could have done it better. Thanks a lot!</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; const char* choose_race(); const char* choose_character_class(); bool define_strength(int&amp; strength, int&amp; unassigned_points); bool define_dexterity(int&amp; dexterity, int&amp; unassigned_points); bool define_constitution(int&amp; constitution, int&amp; unassigned_points); bool define_intellect(int&amp; intellect, int&amp; unassigned_points); bool define_wisdom(int&amp; wisdom, int&amp; unassigned_points); bool define_charisma(int&amp; charisma, int&amp; unassigned_points); bool race_stats_mod(int race, int&amp; strength, int&amp; dexterity, int&amp; constitution, int&amp; intellect, int&amp; wisdom, int&amp; charisma); int main() { cout &lt;&lt; &quot;***** Fantasy Character Creation Tool *****&quot; &lt;&lt; endl; cout &lt;&lt; endl; // ABILITY SCORE MODIFIERS TABLE INITIALIZATION vector&lt;vector&lt;int&gt;&gt; ability_score_modifier(45, vector&lt;int&gt;(2)); ability_score_modifier.at(0).at(0) = 1; ability_score_modifier.at(0).at(1) = -5; int counter{ 2 }; int modifier{ -4 }; do { for (int i = 0; i &lt; 2; i++) { ability_score_modifier.at(counter - 1).at(0) = counter; ability_score_modifier.at(counter - 1).at(1) = modifier; counter++; } modifier++; } while (counter&lt;=45); // GENERAL VARIABLE INIZIALIZATION int level{ 1 }; int experience{ 0 }; int strength{ 10 }, dexterity{ 10 }, constitution{ 10 }, intellect{ 10 }, wisdom{ 10 }, charisma{ 10 }; // CHOOSE RACE string race; race = choose_race(); system(&quot;cls&quot;); // CHOOSE CLASS string character_class; character_class = choose_character_class(); system(&quot;cls&quot;); // CHOOSE NAME string name; cout &lt;&lt; &quot;Enter your character name: &quot;; cin &gt;&gt; name; system(&quot;cls&quot;); // MODIFY ATTRIBUTES VALUES BASED ON CHOOSEN RACE int race_to_integer{}; if (race == &quot;Human&quot;) { race_to_integer = 1; } else { if (race == &quot;Dwarf&quot;) { race_to_integer = 2; } else { if (race == &quot;Elf&quot;) { race_to_integer = 3; } } } bool check_if_selection_success{ false }; do { check_if_selection_success = race_stats_mod(race_to_integer, strength, dexterity, constitution, intellect, wisdom, charisma); } while (check_if_selection_success == false); system(&quot;cls&quot;); // ASSIGN ATTRIBUTE STATS cout &lt;&lt; &quot;SELECT YOUR CHARACTER ATTRIBUTES&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Current stats:&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;STRENGTH: &quot; &lt;&lt; strength &lt;&lt; endl; cout &lt;&lt; &quot;DEXTERITY: &quot; &lt;&lt; dexterity &lt;&lt; endl; cout &lt;&lt; &quot;CONSTITUTION: &quot; &lt;&lt; constitution &lt;&lt; endl; cout &lt;&lt; &quot;INTELLECT: &quot; &lt;&lt; intellect &lt;&lt; endl; cout &lt;&lt; &quot;WISDOM: &quot; &lt;&lt; wisdom &lt;&lt; endl; cout &lt;&lt; &quot;CHARISMA: &quot; &lt;&lt; charisma &lt;&lt; endl; cout &lt;&lt; endl; int unassigned_points{ 15 }; cout &lt;&lt; &quot;Available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Points gained or spent based on attribute values:&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;7 / gain 4 point&quot; &lt;&lt; endl; cout &lt;&lt; &quot;8 / gain 2 point&quot; &lt;&lt; endl; cout &lt;&lt; &quot;9 / gain 1 point&quot; &lt;&lt; endl; cout &lt;&lt; &quot;11 --&gt; 13 / 1 point each&quot; &lt;&lt; endl; cout &lt;&lt; &quot;14 --&gt; 15 / 2 points each&quot; &lt;&lt; endl; cout &lt;&lt; &quot;16 --&gt; 17 / 3 points each&quot; &lt;&lt; endl; cout &lt;&lt; &quot;18 / 4 points&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; do { check_if_selection_success = define_strength(strength, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; check_if_selection_success = false; do { check_if_selection_success = define_dexterity(dexterity, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; check_if_selection_success = false; do { check_if_selection_success = define_constitution(constitution, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; check_if_selection_success = false; do { check_if_selection_success = define_intellect(intellect, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; check_if_selection_success = false; do { check_if_selection_success = define_wisdom(wisdom, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;------------------------------------------&quot; &lt;&lt; endl; cout &lt;&lt; endl; check_if_selection_success = false; do { check_if_selection_success = define_charisma(charisma, unassigned_points); } while (check_if_selection_success == false); // CHECK IF ALL ATTRIBUTE POINTS HAVE BEEN ASSIGNED OR NOT // IN CASE THERE ARE REMAINING POINTS IT WILL PROMPT THE USER TO RECONSIDER THE PREVIOUS SELECTION if (unassigned_points&gt;0) { cout &lt;&lt; &quot;You did not assign all available points.&quot; &lt;&lt; endl; cout &lt;&lt; endl; while (unassigned_points&gt;0) { cout &lt;&lt; &quot;Remaining available points: &quot; &lt;&lt; unassigned_points &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Witch attribute would you like to change:&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;[1] Strength = &quot; &lt;&lt; strength &lt;&lt; endl; cout &lt;&lt; &quot;[2] Dexterity = &quot; &lt;&lt; dexterity &lt;&lt; endl; cout &lt;&lt; &quot;[3] Constitution = &quot; &lt;&lt; constitution &lt;&lt; endl; cout &lt;&lt; &quot;[4] Intellect = &quot; &lt;&lt; intellect &lt;&lt; endl; cout &lt;&lt; &quot;[5] Wisdom = &quot; &lt;&lt; wisdom &lt;&lt; endl; cout &lt;&lt; &quot;[6] Charisma = &quot; &lt;&lt; charisma &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Selection: &quot;; int change_attribute{}; cin &gt;&gt; change_attribute; switch (change_attribute) { case 1: check_if_selection_success = false; do { check_if_selection_success = define_strength(strength, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; case 2: check_if_selection_success = false; do { check_if_selection_success = define_dexterity(dexterity, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; case 3: check_if_selection_success = false; do { check_if_selection_success = define_constitution(constitution, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; case 4: check_if_selection_success = false; do { check_if_selection_success = define_intellect(intellect, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; case 5: check_if_selection_success = false; do { check_if_selection_success = define_wisdom(wisdom, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; case 6: check_if_selection_success = false; do { check_if_selection_success = define_charisma(charisma, unassigned_points); } while (check_if_selection_success == false); cout &lt;&lt; endl; break; default: cout &lt;&lt; &quot;Wrong selection. Try again.&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; } } } // DEFINE THE ATTRIBUTES MOD VALUES BASED ON FINAL ATTRIBUTES AND ABILITY SCORES VECTOR int strength_mod{}, dexterity_mod{}, constitution_mod{}, intellect_mod{}, wisdom_mod{}, charisma_mod{}; for (int i = 0; i &lt; 45; i++) { if (strength == ability_score_modifier.at(i).at(0)) { strength_mod = ability_score_modifier.at(i).at(1); } } for (int i = 0; i &lt; 45; i++) { if (dexterity == ability_score_modifier.at(i).at(0)) { dexterity_mod = ability_score_modifier.at(i).at(1); } } for (int i = 0; i &lt; 45; i++) { if (constitution == ability_score_modifier.at(i).at(0)) { constitution_mod = ability_score_modifier.at(i).at(1); } } for (int i = 0; i &lt; 45; i++) { if (intellect == ability_score_modifier.at(i).at(0)) { intellect_mod = ability_score_modifier.at(i).at(1); } } for (int i = 0; i &lt; 45; i++) { if (wisdom == ability_score_modifier.at(i).at(0)) { wisdom_mod = ability_score_modifier.at(i).at(1); } } for (int i = 0; i &lt; 45; i++) { if (charisma == ability_score_modifier.at(i).at(0)) { charisma_mod = ability_score_modifier.at(i).at(1); } } system(&quot;cls&quot;); // PRINT OUT THE CHARACTER SHEET cout &lt;&lt; &quot;***** YOUR CHARACTER *****&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; name &lt;&lt; &quot; - LVL &quot; &lt;&lt; level &lt;&lt; endl; cout &lt;&lt; race &lt;&lt; &quot; &quot; &lt;&lt; character_class &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;PRIMARY STATS: &quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;STRENGTH: &quot; &lt;&lt; strength &lt;&lt; &quot; - mod: &quot; &lt;&lt; strength_mod &lt;&lt; endl; cout &lt;&lt; &quot;DEXTERITY: &quot; &lt;&lt; dexterity &lt;&lt; &quot; - mod: &quot; &lt;&lt; dexterity_mod &lt;&lt; endl; cout &lt;&lt; &quot;CONSTITUTION: &quot; &lt;&lt; constitution &lt;&lt; &quot; - mod: &quot; &lt;&lt; constitution_mod &lt;&lt; endl; cout &lt;&lt; &quot;INTELLECT: &quot; &lt;&lt; intellect &lt;&lt; &quot; - mod: &quot; &lt;&lt; intellect_mod &lt;&lt; endl; cout &lt;&lt; &quot;WISDOM: &quot; &lt;&lt; wisdom &lt;&lt; &quot; - mod: &quot; &lt;&lt; wisdom_mod &lt;&lt; endl; cout &lt;&lt; &quot;CHARISMA: &quot; &lt;&lt; charisma &lt;&lt; &quot; - mod: &quot; &lt;&lt; charisma_mod &lt;&lt; endl; return 0; } const char* choose_race() { int race{}; char confirm_choice{ 'n' }; cout &lt;&lt; &quot;Select your character race: &quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;[1] Human&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[2] Dwarf&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[3] Elf&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Selection: &quot;; cin &gt;&gt; race; switch (race) { case 1: cout &lt;&lt; endl; cout &lt;&lt; &quot;In the reckonings of most worlds, humans are the youngest of the common races,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;late to arrive on the world sceneand short - lived in comparison to dwarves,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;elves, and dragons. Perhaps it is because of their shorter lives that they strive&quot; &lt;&lt; endl; cout &lt;&lt; &quot;to achieve as much as they can in the years they are given. Or maybe they feel&quot; &lt;&lt; endl; cout &lt;&lt; &quot;they have something to prove to the elder races, and that’s why they build their&quot; &lt;&lt; endl; cout &lt;&lt; &quot;mighty empires on the foundation of conquestand trade. Whatever drives them,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;humans are the innovators, the achievers, and the pioneers of the worlds.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_race(); } else { return &quot;Human&quot;; } break; case 2: cout &lt;&lt; endl; cout &lt;&lt; &quot;Kingdoms rich in ancient grandeur, halls carved into the roots of mountains,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;the echoing of picks and hammers in deep mines and blazing forges, a commitment&quot; &lt;&lt; endl; cout &lt;&lt; &quot;to clan and tradition, and a burning hatred of goblins and orcs — these common&quot; &lt;&lt; endl; cout &lt;&lt; &quot;threads unite all dwarves.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Bold and hardy, dwarves are known as skilled warriors, miners, and workers&quot; &lt;&lt; endl; cout &lt;&lt; &quot;of stone and metal. Though they stand well under 5 feet tall, dwarves are so broad&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and compact that they can weigh as much as a human standing nearly two feet taller.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Their courage and endurance are also easily a match for any of the larger folk.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_race(); } else { return &quot;Dwarf&quot;; } break; case 3: cout &lt;&lt; endl; cout &lt;&lt; &quot;Elves are a magical people of otherworldly grace, living in the world but not entirely&quot; &lt;&lt; endl; cout &lt;&lt; &quot;part of it. They live in places of ethereal beauty, in the midst of ancient forests&quot; &lt;&lt; endl; cout &lt;&lt; &quot;or in silvery spires glittering with faerie light, where soft music drifts through&quot; &lt;&lt; endl; cout &lt;&lt; &quot;the air and gentle fragrances waft on the breeze. Elves love nature and magic, art&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and artistry, music and poetry, and the good things of the world.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;With their unearthly grace and fine features, elves appear hauntingly beautiful to&quot; &lt;&lt; endl; cout &lt;&lt; &quot;humans and members of many other races. They are slightly shorter than humans on average,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;ranging from well under 5 feet tall to just over 6 feet. They are more slender than humans,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;weighing only 100 to 145 pounds. Males and females are about the same height, and males&quot; &lt;&lt; endl; cout &lt;&lt; &quot;are only marginally heavier than females.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_race(); } else { return &quot;Elf&quot;; } break; default: cout &lt;&lt; &quot;Wrong input. Try again!&quot; &lt;&lt; endl; system(&quot;cls&quot;); choose_race(); } } const char* choose_character_class() { int character_class{}; char confirm_choice{ 'n' }; cout &lt;&lt; &quot;Select your character class: &quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;[1] Fighter&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[2] Mage&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[3] Rogue&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Selection: &quot;; cin &gt;&gt; character_class; switch (character_class) { case 1: cout &lt;&lt; endl; cout &lt;&lt; &quot;Some take up arms for glory, wealth, or revenge. Others do battle to prove themselves, to&quot; &lt;&lt; endl; cout &lt;&lt; &quot;protect others, or because they know nothing else. Still others learn the ways of weaponcraft to&quot; &lt;&lt; endl; cout &lt;&lt; &quot;hone their bodies in battle and prove their mettle in the forge of war. Lords of the battlefield,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;fighters are a disparate lot, training with many weapons or just one, perfecting the uses of&quot; &lt;&lt; endl; cout &lt;&lt; &quot;armor, learning the fighting techniques of exotic masters, and studying the art of combat, all to&quot; &lt;&lt; endl; cout &lt;&lt; &quot;shape themselves into living weapons. Far more than mere thugs, these skilled warriors reveal&quot; &lt;&lt; endl; cout &lt;&lt; &quot;the true deadliness of their weapons, turning hunks of metal into arms capable of taming&quot; &lt;&lt; endl; cout &lt;&lt; &quot;kingdoms, slaughtering monsters, and rousing the hearts of armies. Soldiers, knights, hunters,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and artists of war, fighters are unparalleled champions, and woe to those who dare stand&quot; &lt;&lt; endl; cout &lt;&lt; &quot;against them.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;ROLE: Fighters excel at combat—defeating their enemies, controlling the flow of battle, and&quot; &lt;&lt; endl; cout &lt;&lt; &quot;surviving such sorties themselves. While their specific weapons and methods grant them a wide&quot; &lt;&lt; endl; cout &lt;&lt; &quot;variety of tactics, few can match fighters for sheer battle prowess.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;PREFERRED ATTRIBUTES: Strength / Constitution&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_character_class(); } else { return &quot;Fighter&quot;; } break; case 2: cout &lt;&lt; endl; cout &lt;&lt; &quot;Beyond the veil of the mundane hide the secrets of absolute power. The works of beings beyond&quot; &lt;&lt; endl; cout &lt;&lt; &quot;mortals, the legends of realms where gods and spirits tread, the lore of creations both wondrous&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and terrible—such mysteries call to those with the ambition and the intellect to rise above the&quot; &lt;&lt; endl; cout &lt;&lt; &quot;common folk to grasp true might. Such is the path of the wizard. These shrewd magic-users&quot; &lt;&lt; endl; cout &lt;&lt; &quot;seek, collect, and covet esoteric knowledge, drawing on cultic arts to work wonders beyond the&quot; &lt;&lt; endl; cout &lt;&lt; &quot;abilities of mere mortals. While some might choose a particular field of magical study and&quot; &lt;&lt; endl; cout &lt;&lt; &quot;become masters of such powers, others embrace versatility, reveling in the unbounded wonders&quot; &lt;&lt; endl; cout &lt;&lt; &quot;of all magic. In either case, wizards prove a cunning and potent lot, capable of smiting their foes,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;empowering their allies, and shaping the world to their every desire.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;ROLE: While universalist wizards might study to prepare themselves for any manner of danger,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;specialist wizards research schools of magic that make them exceptionally skilled within a&quot; &lt;&lt; endl; cout &lt;&lt; &quot;specific focus. Yet no matter their specialty, all wizards are masters of the impossible and can aid&quot; &lt;&lt; endl; cout &lt;&lt; &quot;their allies in overcoming any danger.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;PREFERRED ATTRIBUTES: Intellect&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_character_class(); } else { return &quot;Mage&quot;; } break; case 3: cout &lt;&lt; endl; cout &lt;&lt; &quot;Life is an endless adventure for those who live by their wits. Ever just one step ahead of danger,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;rogues bank on their cunning, skill, and charm to bend fate to their favor. Never knowing what to&quot; &lt;&lt; endl; cout &lt;&lt; &quot;expect, they prepare for everything, becoming masters of a wide variety of skills, training&quot; &lt;&lt; endl; cout &lt;&lt; &quot;themselves to be adept manipulators, agile acrobats, shadowy stalkers, or masters of any of&quot; &lt;&lt; endl; cout &lt;&lt; &quot;dozens of other professions or talents. Thieves and gamblers, fast talkers and diplomats, bandits&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and bounty hunters, and explorers and investigators all might be considered rogues, as well as&quot; &lt;&lt; endl; cout &lt;&lt; &quot;countless other professions that rely upon wits, prowess, or luck. Although many rogues favor&quot; &lt;&lt; endl; cout &lt;&lt; &quot;cities and the innumerable opportunities of civilization, some embrace lives on the road,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;journeying far, meeting exotic people, and facing fantastic danger in pursuit of equally fantastic&quot; &lt;&lt; endl; cout &lt;&lt; &quot;riches. In the end, any who desire to shape their fates and live life on their own terms might&quot; &lt;&lt; endl; cout &lt;&lt; &quot;come to be called rogues.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;ROLE: Rogues excel at moving about unseen and catching foes unaware, and tend to avoid head-&quot; &lt;&lt; endl; cout &lt;&lt; &quot;to-head combat. Their varied skills and abilities allow them to be highly versatile, with great&quot; &lt;&lt; endl; cout &lt;&lt; &quot;variations in expertise existing between different rogues. Most, however, excel in overcoming&quot; &lt;&lt; endl; cout &lt;&lt; &quot;hindrances of all types, from unlocking doors and disarming traps to outwitting magical hazards&quot; &lt;&lt; endl; cout &lt;&lt; &quot;and conning dull-witted opponents.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;PREFERRED ATTRIBUTES: Dexterity / Wisdom&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Do you confirm your choice? (y/n) --&gt; &quot;; cin &gt;&gt; confirm_choice; if (confirm_choice == 'n') { system(&quot;cls&quot;); choose_character_class(); } else { return &quot;Rogue&quot;; } break; default: cout &lt;&lt; &quot;Wrong input. Try again!&quot; &lt;&lt; endl; system(&quot;cls&quot;); choose_character_class(); } } bool define_strength(int&amp; strength, int&amp; unassigned_points) { int temp_strength{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target strength (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_strength; cout &lt;&lt; endl; if (temp_strength &lt; 7 || temp_strength &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_strength &gt; strength) { for (int i = strength; i &lt; temp_strength; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_strength &lt; strength) { for (int i = strength; i &gt; temp_strength; i--) { if (i==18) { required_points -= 4; } else { if (i&lt;18 &amp;&amp; i&gt;=16) { required_points -= 3; } else { if (i&lt;16 &amp;&amp; i&gt;=14) { required_points -= 2; } else { if (i&lt;14 &amp;&amp; i&gt;10) { required_points--; } else { if (i==10) { required_points--; } else { if (i==9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; strength = temp_strength; return true; case 'y': unassigned_points -= required_points; strength = temp_strength; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool define_dexterity(int&amp; dexterity, int&amp; unassigned_points) { int temp_dexterity{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target dexterity (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_dexterity; cout &lt;&lt; endl; if (temp_dexterity &lt; 7 || temp_dexterity &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_dexterity &gt; dexterity) { for (int i = dexterity; i &lt; temp_dexterity; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_dexterity &lt; dexterity) { for (int i = dexterity; i &gt; temp_dexterity; i--) { if (i == 18) { required_points -= 4; } else { if (i &lt; 18 &amp;&amp; i &gt;= 16) { required_points -= 3; } else { if (i &lt; 16 &amp;&amp; i &gt;= 14) { required_points -= 2; } else { if (i &lt; 14 &amp;&amp; i&gt;10) { required_points--; } else { if (i == 10) { required_points--; } else { if (i == 9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; dexterity = temp_dexterity; return true; case 'y': unassigned_points -= required_points; dexterity = temp_dexterity; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool define_constitution(int&amp; constitution, int&amp; unassigned_points) { int temp_constitution{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target constitution (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_constitution; cout &lt;&lt; endl; if (temp_constitution &lt; 7 || temp_constitution &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_constitution &gt; constitution) { for (int i = constitution; i &lt; temp_constitution; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_constitution &lt; constitution) { for (int i = constitution; i &gt; temp_constitution; i--) { if (i == 18) { required_points -= 4; } else { if (i &lt; 18 &amp;&amp; i &gt;= 16) { required_points -= 3; } else { if (i &lt; 16 &amp;&amp; i &gt;= 14) { required_points -= 2; } else { if (i &lt; 14 &amp;&amp; i&gt;10) { required_points--; } else { if (i == 10) { required_points--; } else { if (i == 9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; constitution = temp_constitution; return true; case 'y': unassigned_points -= required_points; constitution = temp_constitution; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool define_intellect(int&amp; intellect, int&amp; unassigned_points) { int temp_intellect{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target intellect (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_intellect; cout &lt;&lt; endl; if (temp_intellect &lt; 7 || temp_intellect &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_intellect &gt; intellect) { for (int i = intellect; i &lt; temp_intellect; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_intellect &lt; intellect) { for (int i = intellect; i &gt; temp_intellect; i--) { if (i == 18) { required_points -= 4; } else { if (i &lt; 18 &amp;&amp; i &gt;= 16) { required_points -= 3; } else { if (i &lt; 16 &amp;&amp; i &gt;= 14) { required_points -= 2; } else { if (i &lt; 14 &amp;&amp; i&gt;10) { required_points--; } else { if (i == 10) { required_points--; } else { if (i == 9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; intellect = temp_intellect; return true; case 'y': unassigned_points -= required_points; intellect = temp_intellect; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool define_wisdom(int&amp; wisdom, int&amp; unassigned_points) { int temp_wisdom{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target wisdom (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_wisdom; cout &lt;&lt; endl; if (temp_wisdom &lt; 7 || temp_wisdom &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_wisdom &gt; wisdom) { for (int i = wisdom; i &lt; temp_wisdom; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_wisdom &lt; wisdom) { for (int i = wisdom; i &gt; temp_wisdom; i--) { if (i == 18) { required_points -= 4; } else { if (i &lt; 18 &amp;&amp; i &gt;= 16) { required_points -= 3; } else { if (i &lt; 16 &amp;&amp; i &gt;= 14) { required_points -= 2; } else { if (i &lt; 14 &amp;&amp; i&gt;10) { required_points--; } else { if (i == 10) { required_points--; } else { if (i == 9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; wisdom = temp_wisdom; return true; case 'y': unassigned_points -= required_points; wisdom = temp_wisdom; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool define_charisma(int&amp; charisma, int&amp; unassigned_points) { int temp_charisma{}; char confirm_new_value{}; int required_points{ 0 }; cout &lt;&lt; &quot;Target charisma (Min value is 7 / Max value is 18): &quot;; cin &gt;&gt; temp_charisma; cout &lt;&lt; endl; if (temp_charisma &lt; 7 || temp_charisma &gt; 18) { return false; } while (confirm_new_value == 0) { if (temp_charisma &gt; charisma) { for (int i = charisma; i &lt; temp_charisma; i++) { if (i &lt; 13) { required_points++; } else { if (i &gt;= 13 &amp;&amp; i &lt; 15) { required_points += 2; } else { if (i &gt;= 15 &amp;&amp; i &lt; 17) { required_points += 3; } else { required_points += 4; } } } } } else { if (temp_charisma &lt; charisma) { for (int i = charisma; i &gt; temp_charisma; i--) { if (i == 18) { required_points -= 4; } else { if (i &lt; 18 &amp;&amp; i &gt;= 16) { required_points -= 3; } else { if (i &lt; 16 &amp;&amp; i &gt;= 14) { required_points -= 2; } else { if (i &lt; 14 &amp;&amp; i&gt;10) { required_points--; } else { if (i == 10) { required_points--; } else { if (i == 9) { required_points -= 2; } else { required_points -= 4; } } } } } } } } else { return true; } } if (required_points &gt; unassigned_points) { cout &lt;&lt; &quot;Not enough free points. Try again.&quot; &lt;&lt; endl; return false; } else { cout &lt;&lt; &quot;Assigning this value requires &quot; &lt;&lt; required_points &lt;&lt; &quot; points.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you want to proceed? Y/N --&gt; &quot;; cin &gt;&gt; confirm_new_value; cout &lt;&lt; endl; switch (confirm_new_value) { case 'Y': unassigned_points -= required_points; charisma = temp_charisma; return true; case 'y': unassigned_points -= required_points; charisma = temp_charisma; return true; case 'N': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; case 'n': cout &lt;&lt; &quot;Try again.&quot; &lt;&lt; endl; return false; default: cout &lt;&lt; &quot;Wrong input. Try again.&quot; &lt;&lt; endl; return false; break; } } } } bool race_stats_mod(int race, int&amp; strength, int&amp; dexterity, int&amp; constitution, int&amp; intellect, int&amp; wisdom, int&amp; charisma) { int selection{}; switch (race) { case 1: cout &lt;&lt; &quot;As a human you can choose witch attribute will benefit from a +2 bonus.&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Select witch attribute you want to improve:&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;[1] Strength&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[2] Dexterity&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[3] Constitution&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[4] Intellect&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[5] Wisdom&quot; &lt;&lt; endl; cout &lt;&lt; &quot;[6] Charisma&quot; &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; &quot;Selection: &quot;; cin &gt;&gt; selection; switch (selection) { case 1: strength += 2; return true; case 2: dexterity += 2; return true; case 3: constitution += 2; return true; case 4: intellect += 2; return true; case 5: wisdom += 2; return true; case 6: charisma += 2; return true; default: cout &lt;&lt; &quot;Wrong selection. Try again.&quot; &lt;&lt; endl; cout &lt;&lt; endl; return false; } case 2: constitution = wisdom += 2; charisma -= 2; return true; case 3: dexterity = intellect += 2; constitution -= 2; return true; default: cout &lt;&lt; &quot;Wrong selection. Try again.&quot; &lt;&lt; endl; cout &lt;&lt; endl; return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:16:19.620", "Id": "529454", "Score": "0", "body": "Welcome to Code Review! To the best of your knowledge- does the code function as expected? And it would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:26:21.850", "Id": "529455", "Score": "0", "body": "Hi Sam, thanks for your reply :) Yes up to now the code works as intended, at least this is what I can say based on many different case testing I did" } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"noreferrer\">SF.7</a>.)</p>\n<hr />\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<hr />\n<p>My first impression is that you have a bunch of free functions, not a class. And those parameters are all primitive types, and passed by non-const reference. I'm guessing those similarly-named parameters should be data members instead of in/out parameters.</p>\n<pre><code>// GENERAL VARIABLE INIZIALIZATION\n\n int level{ 1 };\n int experience{ 0 };\n int strength{ 10 }, dexterity{ 10 }, constitution{ 10 }, intellect{ 10 }, wisdom{ 10 }, charisma{ 10 };\n</code></pre>\n<p>Those should probably be the various <strong>data members</strong> of your class.</p>\n<p>Don't put more than one variable (or class data member) declaration in a statement.</p>\n<p>So, put a <code>class</code> around this, making these the data members. Then remove all the similarly-named parameters from the functions, as they will all be able to access the members of the class directly. This is basic Object Oriented principles.</p>\n<hr />\n<p><code>vector&lt;vector&lt;int&gt;&gt; ability_score_modifier(45, vector&lt;int&gt;(2));</code><br />\nYou never call <code>push_back</code> but simply pre-define the vector of vectors to a fixed size, and then access those elements. This is inefficient and is not making use of the main feature of <code>vector</code>, but you suffer additional indirection and heap memory allocation.</p>\n<p>Normally you have objects or complex types and don't have empty elements ready to be changed; rather, an element doesn't exist at all until you add it. Here you just have <code>int</code> values so that is not important. So, just use a 2D primitive built-in array.</p>\n<p><code>ability_score_modifier.at(0).at(0) = 1;</code><br />\nIt's strange that you are using <code>at</code> rather than the more usual <code>[]</code> notation. Since you are using fixed bounds, even constant subscripts in this example, the difference in error checking is not a reason for it.</p>\n<hr />\n<pre><code>string race;\nrace = choose_race();\n</code></pre>\n<p>You almost had it! You didn't declare <code>race</code> until you were ready to use it, but then you broke it up into two statements. <strong>initialize</strong> your variables when you declare them. And, use <code>const</code> whenever you can. Try:</p>\n<p><code>const string race = choose_race();</code></p>\n<hr />\n<p><code>system(&quot;cls&quot;);</code><br />\nThis is non-portable and slow since it launches another program to clear the screen! Generally, don't do that as part of a TTY-style program; the user can clear the screen before launching the program if/when he wants.</p>\n<hr />\n<pre><code> int race_to_integer{};\n if (race == &quot;Human&quot;)\n {\n race_to_integer = 1;\n }\n else\n {\n if (race == &quot;Dwarf&quot;)\n {\n race_to_integer = 2;\n }\n else\n {\n if (race == &quot;Elf&quot;)\n {\n race_to_integer = 3;\n }\n }\n }\n</code></pre>\n<p>This block should be in its own function at the very least.<br />\nIt should be part of the get-race stuff, not farther down in the main code.<br />\nThe races should be an <strong>enumeration type</strong>, not an <code>int</code>.</p>\n<p>Something like:</p>\n<pre><code>enum race_type { Human, Dwarf, Elf };\n ⋮\nrace_type parse_race (string_view in)\n{\n if (in==&quot;Human&quot;) return Human;\n if (in==&quot;Dwarf&quot;) return Dwarf;\n if (in==&quot;Elf&quot;) return Elf;\n throw /* something */ ... ;\n}\n ⋮\n /* in another function */\n const string race_name= choose_race();\n const auto race = parse_race(race_name);\n</code></pre>\n<p>Note that the actual code doesn't have nested nested nested comparisons. It is flat: <strong>code to the left</strong>.</p>\n<p>Learn to recognise a <strong>cohesive</strong> block of code that should be put into its own function. You can draw a circle around this and it doesn't interact with anything else.</p>\n<hr />\n<pre><code>case 1:\n check_if_selection_success = false;\n do\n {\n check_if_selection_success = define_strength(strength, unassigned_points);\n } while (check_if_selection_success == false);\n cout &lt;&lt; endl;\n break;\n</code></pre>\n<p>These cases are almost all the same. Hoist the looping out to a higher level, and have the menu <em>only</em> call one of the functions.</p>\n<p>Since the functions, as previously mentioned, should be member functions, you don't need to pass parameters and the menu code becomes simple and compact.</p>\n<hr />\n<pre><code>for (int i = 0; i &lt; 45; i++)\n {\n if (strength == ability_score_modifier.at(i).at(0))\n {\n strength_mod = ability_score_modifier.at(i).at(1);\n }\n }\n</code></pre>\n<p>You have this nearly identical block 6 times in a row! <strong>Don't Repeat Yourself</strong>.</p>\n<p>You are also indexing the same place twice, which is wasteful and hard to read. In a generic sense, you have:</p>\n<pre><code>for (const auto&amp; row : ability_score_modifier) {\n if (THING == row[0]) THING_mod= row[1];\n}\n</code></pre>\n<p>This can be put into a function with the marked placeholders (the only part that changes) becoming parameters. This is the <em>real</em> purpose of parameters in functions: you have a one-to-one correspondence between the final home of the data and the function parameters, which is not very useful.</p>\n<p>But in this case, I think you can just put all 6 THINGs inside the same loop.</p>\n<p>I'm really not understanding what your data structure is all about here. There might be a better way to represent it, based on an understanding of the problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T16:15:30.477", "Id": "268476", "ParentId": "268472", "Score": "5" } }, { "body": "<p>There is really just too much to go through here. I would suggest you first create classes for the basics. Consider the following code:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Race\n{\npublic:\n Race(std::string name, std::string message)\n : name{ name }, \n message{ message }\n {\n }\n\npublic:\n std::string name;\n std::string message;\n};\n\nclass Game\n{\nprivate:\n std::vector&lt;Race&gt; races;\n\npublic:\n Game() {\n races.emplace_back(\"Human\", \"In the reckonings of most worlds, humans...\");\n races.emplace_back(\"Dwarf\", \"Kingdoms rich in ancient grandeur, halls carved...\");\n races.emplace_back(\"Elf\", \"Elves are a magical people of otherworldly...\");\n }\n\n int chooseRace() {\n std::string errorMessage;\n int raceNumber = -1;\n while (raceNumber == -1)\n {\n if (errorMessage.empty() == false) {\n std::cout &lt;&lt; errorMessage &lt;&lt; \"\\n\\n\";\n errorMessage.clear();\n }\n\n std::cout &lt;&lt; \"Select your character race: \\n\\n\";\n int index = 0;\n for (auto race : races)\n std::cout &lt;&lt; \"[\" &lt;&lt; ++index &lt;&lt; \"] \" &lt;&lt; race.name &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"\\n\";\n\n int number;\n std::cin &gt;&gt; number;\n --number;\n if (number &lt; 0 || number &gt;= races.size())\n {\n errorMessage = \"Invalid number\";\n continue;\n }\n Race&amp; race = races[number];\n std::cout &lt;&lt; race.message &lt;&lt; \"\\n\\n\";\n\n std::cout &lt;&lt; \"Do you confirm your choice? (y/n) --&gt; \";\n char confirm_choice;\n std::cin &gt;&gt; confirm_choice;\n if (confirm_choice == 'y' || confirm_choice == 'Y') {\n raceNumber = number;\n }\n else {\n continue;\n }\n }\n return raceNumber;\n }\n};\n\nint main() {\n Game game;\n int number = game.chooseRace();\n}\n\n</code></pre>\n<p>Adding a new type of 'Race' will be as simple as:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> races.emplace_back(&quot;Pigmen&quot;, &quot;Pigmen belong to Minceraft...&quot;);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T19:35:19.660", "Id": "529472", "Score": "0", "body": "Good point about making a class, since OP mentioned wanting to learn OOP. However, I would avoid starting member variables with an underscore (see [this post](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)). I would also write `races.emplace_back(1, \"Human, \"...\")` instead of using `push_back()`, or even better: `static const std::array<Race> races = {{1, \"Human\", \"...\"}, {2, \"Dwarf\", \"...\"}, ...};` If they are in a vector or array anyway, then `_number` seems a bit superfluous as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T12:25:01.327", "Id": "529515", "Score": "0", "body": "@G.Sliepen, I have updated my code based on your comments. Do you have any other suggestions, especially about the Race constructor?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T16:18:43.190", "Id": "268477", "ParentId": "268472", "Score": "1" } }, { "body": "<h2>use <code>else if</code></h2>\n<blockquote>\n<pre><code> if (i &lt; 13)\n {\n required_points++;\n }\n else\n {\n if (i &gt;= 13 &amp;&amp; i &lt; 15)\n {\n required_points += 2;\n }\n else\n {\n if (i &gt;= 15 &amp;&amp; i &lt; 17)\n {\n required_points += 3;\n }\n else\n {\n required_points += 4;\n }\n }\n }\n</code></pre>\n</blockquote>\n<p>Chains of logic like this can be simplified using <code>else if</code>. Each condition is checked in turn, so we can do the following:</p>\n<pre><code> if (i &lt; 13)\n {\n required_points++;\n }\n else if (i &lt; 15)\n {\n required_points += 2;\n }\n else if (i &lt; 17)\n {\n required_points += 3;\n }\n else\n {\n required_points += 4;\n }\n</code></pre>\n<hr />\n<h2>remove duplicate code</h2>\n<p>There seems to be very little difference between the various <code>define_[stat]</code> functions (at a glance, it looks like only the stat name is different?). Consider passing the stat name into the function as a <code>std::string</code>. That way we could define a single function, and call it for every stat:</p>\n<pre><code>bool define_stat(std::string const&amp; name, int&amp; stat, int&amp; unassigned_points);\n\n...\n\nselection_success = define_stat(&quot;strength&quot;, strength, unsassigned_points);\nselection_success = define_stat(&quot;wisdom&quot;, wisdom, unsassigned_points);\n</code></pre>\n<p>It's much easier to maintain 1 function, instead of 6. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T16:38:05.293", "Id": "268478", "ParentId": "268472", "Score": "5" } }, { "body": "<p>Few words from me.</p>\n<ol>\n<li><p>I would suggest to extract large texts into separate text files or resources. In you code you just need to load them and simply write on standard output. <a href=\"https://www.codegrepper.com/code-examples/cpp/c%2B%2B+load+text+file\" rel=\"nofollow noreferrer\">Here is an examle (codegrepper.com).</a> I would also suggest to extract smaller text messages into constants.</p>\n</li>\n<li><p>Somebody already mentioned about duplicated code -please do refactor it first. After that, the switch/case conditions could be simplified too. Consider converting a character from user input into lowercase first.</p>\n</li>\n<li><p>main function -please split into smaller subroutines with meaningful names informing what this step really does (their names usually can replace comments in code).</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:10:24.570", "Id": "268503", "ParentId": "268472", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T15:02:40.030", "Id": "268472", "Score": "2", "Tags": [ "c++", "performance", "beginner", "c++14" ], "Title": "Fantasy Character Creation Tool (early prototype)" }
268472
<p>This was my <a href="https://codereview.stackexchange.com/questions/268345/tic-tac-toe-in-c-with-classes">previous post</a> on Tic Tac Toe in C++. I received very good feedback and tried to implement all of the improvements. I could not implement some due to the AI needed functions or complexity.</p> <p>I wanted to know where I could -</p> <ul> <li>Optimize the performance.</li> <li>Improve my Tic Tac Toe class.</li> <li>Improve my AI.</li> <li>Improve the UX.</li> <li>Follow C++ conventions (I still prefer snake_case)</li> </ul> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;algorithm&gt; class TicTacToe; class AI; void play_game(TicTacToe game); class TicTacToe { private: char board[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; char current_turn = 'X'; char winner = ' '; // ' ' refers to None int state = -1; // -1 refers to running std::list&lt;int&gt; move_stack; void swap_turn(); void update_state(); public: friend class AI; friend void play_game(TicTacToe game); void print_board() const; int play_move(int index); void undo_move(); std::list&lt;int&gt; get_possible_moves(); }; class AI { private: int max(TicTacToe board, char max_symbol, int depth); int min(TicTacToe board, char max_symbol, int depth); public: int minmax(TicTacToe board, char max_symbol); }; int main() { TicTacToe game; play_game(game); return 0; } void play_game(TicTacToe game) { bool playing = true; int move; int count = 0; AI my_ai; while (playing) { game.print_board(); if (count % 2 == 1) { move = my_ai.minmax(game, game.current_turn); } else { std::cout &lt;&lt; &quot;Enter your move (1-9)\n&quot;; std::cin &gt;&gt; move; if (!std::cin) { std::cerr &lt;&lt; &quot;Input error\n&quot;; return; } --move; } if (game.play_move(move) == 0) { std::cout &lt;&lt; &quot;Box already occupied\n&quot;; continue; } if (game.state == 1) { game.print_board(); std::cout &lt;&lt; game.winner &lt;&lt; &quot; wins the game!\n&quot;; playing = false; } else if (game.state == 0) { game.print_board(); std::cout &lt;&lt; &quot;Draw!\n&quot;; playing = false; }; ++count; }; }; void TicTacToe::print_board() const { for (int i = 0; i &lt; 9; ++i) { if (i % 3) { std::cout &lt;&lt; &quot; | &quot;; } std::cout &lt;&lt; board[i]; if (i == 2 || i == 5) { std::cout &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;---------&quot; &lt;&lt; &quot;\n&quot;; } } std::cout &lt;&lt; &quot;\n&quot;; }; void TicTacToe::swap_turn() { current_turn = (current_turn == 'X') ? 'O' : 'X'; } int TicTacToe::play_move(int index) { if (index &gt;= 0 &amp;&amp; index &lt; 9) { if (board[index] == ' ') { board[index] = current_turn; move_stack.push_back(index); update_state(); swap_turn(); return 1; } } return 0; }; void TicTacToe::undo_move() { int move = move_stack.back(); board[move] = ' '; move_stack.pop_back(); update_state(); swap_turn(); }; std::list&lt;int&gt; TicTacToe::get_possible_moves() { std::list&lt;int&gt; possible_moves; for (int i = 0; i &lt; 9; ++i) { bool found = (std::find(move_stack.begin(), move_stack.end(), i) != move_stack.end()); if (!found) { possible_moves.push_back(i); } } return possible_moves; } void TicTacToe::update_state() { if ( // Horizontal checks (board[0] == current_turn &amp;&amp; board[1] == current_turn &amp;&amp; board[2] == current_turn) || (board[3] == current_turn &amp;&amp; board[4] == current_turn &amp;&amp; board[5] == current_turn) || (board[6] == current_turn &amp;&amp; board[7] == current_turn &amp;&amp; board[8] == current_turn) || // Vertical Checks (board[0] == current_turn &amp;&amp; board[3] == current_turn &amp;&amp; board[6] == current_turn) || (board[1] == current_turn &amp;&amp; board[4] == current_turn &amp;&amp; board[7] == current_turn) || (board[2] == current_turn &amp;&amp; board[5] == current_turn &amp;&amp; board[8] == current_turn) || // Diagonal Checks (board[0] == current_turn &amp;&amp; board[4] == current_turn &amp;&amp; board[8] == current_turn) || (board[2] == current_turn &amp;&amp; board[4] == current_turn &amp;&amp; board[6] == current_turn)) { state = 1; winner = current_turn; } else { bool draw = true; for (int i = 0; i &lt; 9; ++i) { if (board[i] == ' ') { draw = false; break; } }; if (draw) { state = 0; } else { winner = ' '; state = -1; } } }; int AI::minmax(TicTacToe board, char max_symbol) { int best_score = -100; int best_move = -1; // -1 refers to none for (auto move : board.get_possible_moves()) { board.play_move(move); int score = AI::min(board, max_symbol, 0); if (score &gt; best_score) { best_score = score; best_move = move; } board.undo_move(); } return best_move; } int AI::max(TicTacToe board, char max_symbol, int depth) { if (board.state == 1) { if (board.winner == max_symbol) { return 10 - depth; } else { return -10 + depth; } } else if (board.state == 0) { return 0; } int best_score = -100; for (auto move : board.get_possible_moves()) { board.play_move(move); int score = AI::min(board, max_symbol, depth + 1); if (score &gt; best_score) { best_score = score; } board.undo_move(); } return best_score; } int AI::min(TicTacToe board, char max_symbol, int depth) { if (board.state == 1) { if (board.winner == max_symbol) { return 10 - depth; } else { return -10 + depth; } } else if (board.state == 0) { return 0; } int best_score = 100; for (auto move : board.get_possible_moves()) { board.play_move(move); int score = AI::max(board, max_symbol, depth + 1); if (score &lt; best_score) { best_score = score; } board.undo_move(); } return best_score; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T20:31:41.457", "Id": "529476", "Score": "1", "body": "Generally you should avoid using `friend`. Make the necessary objects `public` or create getters / setters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T03:17:58.697", "Id": "529564", "Score": "0", "body": "Not sure if I agree with Johan exactly. But he is not entirely wrong either. The `friend` declaration has its uses, but I don't think the way you are using helps you or is good usage in this case. **BUT** getters/setters are also a bad pattern in C++ were you would normally use `actions()` (which is a better pattern, than `z.set(doSomething(z.get()))` ). But get/set does have its place just not here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:52:02.900", "Id": "529588", "Score": "0", "body": "@MartinYork That’s why I added the \"Generally\" disclaimer =) The way it was applied here just seemed lazy." } ]
[ { "body": "<blockquote>\n<p>Improve my Tic Tac Toe class.\nImprove my AI.\nImprove the UX.</p>\n</blockquote>\n<p>Maybe a redesign of the classes:</p>\n<p>Not sure you have the greatest class break down.</p>\n<p>The TikTakToa class seems to be a class that combines the state of the game the future state for the AI program and the game rules all in one.</p>\n<p>The AI class seems to just embed the AI algorithm but it does not store state in there (which seems odd).</p>\n<p>May I suggest a restructuring of the classe.</p>\n<pre><code>class Board\n{\n int currentMove;\n public:\n // Players can interagate the board history\n // to work out the current state of the game\n // or keep track of that locally.\n int getCurrentMove() const;\n int getMove(int m) const;\n\n // Only the Game (see below) can add moves as it\n // is the only object that will get a non const reference\n // to the board;\n void addMove(int m);\n};\n\n// An abstract player.\n// Human or AI (could be either).\nclass Player\n{\n public:\n virtual ~Player() {};\n\n // Players get a board to examine during there move\n // then they can decide return the best move to the game\n // who will apply the move after validation.\n virtual int getMove(Board const&amp;) = 0;\n};\nclass HumanPlayer\n{\n public:\n // The human player may need to see a visualization\n // of the board (or just a list of moves) up to you.\n //\n // So the first step of the human player would be\n // to print the board then get input from the human.\n virtual int getMove(Board const&amp;) override;\n};\nclass AIPlayer\n{\n public:\n virtual int getMove(Board const&amp;) override;\n};\n\n// The game object takes two player\n// Could be two humans or two AI or one of each.\n// Then sequentially gets each player to make a move\n// until it detects a winner.\nclass Game\n{\n public:\n // Set up a game with the two players and a board.\n Game(Player&amp; cross, Player&amp; nott, Board&amp; board);\n\n // Play a game asking each player for a move\n // until the game decides there is a winner.\n void playLoop();\n};\n \n\nint main()\n{\n std::unique_ptr&lt;Player&gt; p1 = getPlayer1();\n std::unique_ptr&lt;Player&gt; p2 = getPlayer2();\n\n Board board;\n Game game(*p1, *p2, board);\n game.play();\n \n}\n</code></pre>\n<hr />\n<p>Review of Code</p>\n<p>I prefer <code>camelCase</code> and you say you prefer <code>Snake_Case</code>. Do be honest it does not matter that much. But it would be preferable to maintain one style or the other rather than have a combination of each.</p>\n<pre><code>class TicTacToe;\nvoid play_game(TicTacToe game);\n</code></pre>\n<p>Why Not <code>Tic_Tac_Toe</code>?</p>\n<hr />\n<pre><code>class TicTacToe\n</code></pre>\n<p>This seems to be an uber class doing nearly everything:</p>\n<p>Board State:</p>\n<pre><code> char board[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};\n char current_turn = 'X';\n</code></pre>\n<p>Game State:</p>\n<pre><code> char winner = ' '; // ' ' refers to None\n int state = -1; // -1 refers to running\n</code></pre>\n<p>AI State?</p>\n<pre><code> std::list&lt;int&gt; move_stack;\n</code></pre>\n<hr />\n<p>Seems like <code>play_game()</code> should be a member of <code>TicTacToe</code> then it would not need to be a friend.</p>\n<pre><code>int main()\n{\n TicTacToe game;\n play_game(game);\n\n // Don't need this. line\n return 0;\n}\n</code></pre>\n<hr />\n<p>You passed <code>game</code> by value. So you are getting a copy of the game here:</p>\n<pre><code>void play_game(TicTacToe game)\n</code></pre>\n<p>You probably want to do:</p>\n<pre><code>void play_game(TicTacToe&amp; game)\n // ^ pass the game by reference.\n</code></pre>\n<hr />\n<p>You always want an AI? What happens with two humans? Or what about pitting two AI against each other? That could be really useful if you have a nerual network and want to train AI by playing them against each other.</p>\n<pre><code> AI my_ai;\n</code></pre>\n<hr />\n<p>If you have two AI playing. Not sure I want the board to always be updated or printed to the UI. Make that part of the human players interface.</p>\n<pre><code> game.print_board();\n</code></pre>\n<hr />\n<p>Not very fair to the AI to always go second?</p>\n<pre><code> if (count % 2 == 1)\n {\n move = my_ai.minmax(game, game.current_turn);\n } else\n</code></pre>\n<hr />\n<p>The human input code should be put into its own function.</p>\n<pre><code> {\n std::cout &lt;&lt; &quot;Enter your move (1-9)\\n&quot;;\n std::cin &gt;&gt; move;\n if (!std::cin) \n {\n std::cerr &lt;&lt; &quot;Input error\\n&quot;;\n return;\n }\n --move;\n }\n</code></pre>\n<hr />\n<p>This works but not the typical way to write it:</p>\n<pre><code> std::cin &gt;&gt; move;\n if (!std::cin) \n {\n std::cerr &lt;&lt; &quot;Input error\\n&quot;;\n return;\n }\n</code></pre>\n<p>I would write like this:</p>\n<pre><code> if (std::cin &gt;&gt; move) {\n // Good input\n }\n else {\n std::cerr &lt;&lt; &quot;Input error\\n&quot;;\n return;\n }\n</code></pre>\n<hr />\n<p>If the AI generates this move do you think it will change its mind if you ask again?</p>\n<pre><code> if (game.play_move(move) == 0)\n {\n std::cout &lt;&lt; &quot;Box already occupied\\n&quot;;\n continue;\n }\n</code></pre>\n<p>I think this check is for the human player only. Well the ouput anyway. So put this check with the human input in the function handling user input.</p>\n<p>You may need an external check that exits the application if the game recieves an invalid move as otherwise the AI is going to go into an infinite loop.</p>\n<hr />\n<p>You have two game states. <code>playing</code> and <code>game.state</code>. Keep this as one state so you simply exit the loop when the game is over. Then this output can be done outside the loop.</p>\n<pre><code> if (game.state == 1)\n {\n game.print_board();\n std::cout &lt;&lt; game.winner &lt;&lt; &quot; wins the game!\\n&quot;;\n playing = false;\n } else if (game.state == 0)\n {\n game.print_board();\n std::cout &lt;&lt; &quot;Draw!\\n&quot;;\n playing = false;\n };\n</code></pre>\n<hr />\n<p>This is not wrong.</p>\n<pre><code>int TicTacToe::play_move(int index)\n{\n if (index &gt;= 0 &amp;&amp; index &lt; 9)\n {\n if (board[index] == ' ')\n {\n board[index] = current_turn;\n move_stack.push_back(index);\n update_state();\n swap_turn();\n return 1;\n }\n }\n return 0;\n};\n</code></pre>\n<p>But I would do the precondition checks first and exit at the beginning of the function to show the preconditions had been broken:</p>\n<pre><code>int TicTacToe::play_move(int index)\n{\n if (index &lt; 0 || index &gt;= 9) {\n return 0;\n }\n\n if (board[index] != ' ') {\n return 0;\n }\n\n // Good Move.\n board[index] = current_turn;\n move_stack.push_back(index);\n update_state();\n swap_turn();\n};\n</code></pre>\n<hr />\n<p>Here we are looking at an effeciency issue.</p>\n<pre><code>std::list&lt;int&gt; TicTacToe::get_possible_moves()\n{\n std::list&lt;int&gt; possible_moves;\n for (int i = 0; i &lt; 9; ++i)\n {\n bool found = (std::find(move_stack.begin(), move_stack.end(), i) != move_stack.end());\n if (!found)\n {\n possible_moves.push_back(i);\n }\n }\n return possible_moves;\n}\n</code></pre>\n<p>This is being built every time around the loop. Why not build it once. Then take values off when you make a move. Then you can return a const reference to the list as the result of this function. This will prevent you from constantly rebuilding the list.</p>\n<hr />\n<p>Do you need to check all possible states after each move?</p>\n<p>You only need to check states that include the last move.</p>\n<pre><code>void TicTacToe::update_state()\n{\n</code></pre>\n<hr />\n<p>OK. This is hard. I have no idea to tell if this is correct.</p>\n<pre><code>int AI::minmax(TicTacToe board, char max_symbol)\nint AI::max(TicTacToe board, char max_symbol, int depth)\nint AI::min(TicTacToe board, char max_symbol, int depth)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T07:09:31.747", "Id": "529572", "Score": "0", "body": "Thanks for the review! Just to mention, I come from Python. In python its a convention to use `PascalCase` for classes and `snake_case` for variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:04:29.050", "Id": "529608", "Score": "0", "body": "@Random_Pythoneer59 Did not know they were so loosey goosey over in Python :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T03:35:51.533", "Id": "268529", "ParentId": "268486", "Score": "2" } }, { "body": "<p>These are my thoughts to follow up on Martin York’s excellent review.</p>\n<ol>\n<li>Create <code>enums</code> for <code>GameState</code> and <code>Symbols</code>:</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>enum GameState : int\n{\n Running,\n Draw,\n Win\n};\n\nenum Symbol : char\n{\n Tic = 'X',\n Tac = 'O',\n Space = ' '\n};\n</code></pre>\n<ol start=\"2\">\n<li>Simplify the board class. You do not need to keep track of previous moves and the current player etc.</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class TicTacToe\n{\npublic:\n std::array&lt;Symbol, 9&gt; board;\n\n TicTacToe() {\n board.fill(Symbol::Space);\n }\n\n void print_board() const {\n for (int i = 0; i &lt; 9; ++i) {\n if (i % 3)\n std::cout &lt;&lt; &quot; | &quot;;\n std::cout &lt;&lt; board[i];\n if (i == 2 || i == 5)\n std::cout &lt;&lt; &quot;\\n---------\\n&quot;;\n }\n std::cout &lt;&lt; &quot;\\n\\n&quot;;\n }\n\n GameState evalState(const Symbol symbol) {\n if (match(symbol, 0, 1, 2) || match(symbol, 3, 4, 5) || match(symbol, 6, 7, 8) || // Horizontal checks\n match(symbol, 0, 3, 6) || match(symbol, 1, 4, 7) || match(symbol, 2, 5, 8) || // Vertical Checks\n match(symbol, 0, 4, 8) || match(symbol, 2, 4, 6)) // Diagonal Checks\n return GameState::Win;\n if (std::count(board.begin(), board.end(), Symbol::Space) == 0)\n return GameState::Draw;\n return GameState::Running;\n }\n\nprivate:\n bool match(const Symbol symbol, int i1, int i2, int i3) {\n return board[i1] == symbol &amp;&amp; board[i2] == symbol &amp;&amp; board[i3] == symbol;\n }\n};\n</code></pre>\n<ol start=\"3\">\n<li>The <code>possible_moves</code> list is unnecessarily cumbersome. You can simply enumerate over the cells and use the empty ones:</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>for (int i = 0; i &lt; 9; i++) {\n if (game.board[i] == Symbol::Space) {\n // set move \n game.board[i] = symbol;\n\n int score = minimax(game, depth + 1, !isMax, symbol);\n best = std::max(best, score);\n\n // undo move\n game.board[i] = Symbol::Space;\n }\n}\n</code></pre>\n<ol start=\"4\">\n<li>Playing against an unbeatable AI isn't much fun. You can consider adding <code>maxdepth</code> to the minimax to dumb it down. It's already unbeatable at <code>maxDepth = 5</code> as far as I can tell. Selecting a random move from the best moves also makes the AI a bit more interesting.</li>\n</ol>\n<p>Putting it all together:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;array&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;ctime&gt;\n\nenum GameState : int\n{\n Running,\n Draw,\n Win\n};\n\nenum Symbol : char\n{\n Tic = 'X',\n Tac = 'O',\n Space = ' '\n};\n\nclass TicTacToe\n{\npublic:\n std::array&lt;Symbol, 9&gt; board;\n\n TicTacToe() {\n board.fill(Symbol::Space);\n }\n\n void print_board() const {\n for (int i = 0; i &lt; 9; ++i) {\n if (i % 3)\n std::cout &lt;&lt; &quot; | &quot;;\n std::cout &lt;&lt; board[i];\n if (i == 2 || i == 5)\n std::cout &lt;&lt; &quot;\\n---------\\n&quot;;\n }\n std::cout &lt;&lt; &quot;\\n\\n&quot;;\n }\n\n static Symbol swap(const Symbol symbol) {\n return symbol == Symbol::Tic ? Symbol::Tac : Symbol::Tic;\n }\n\n GameState evalState(const Symbol symbol) {\n if (match(symbol, 0, 1, 2) || match(symbol, 3, 4, 5) || match(symbol, 6, 7, 8) || // Horizontal checks\n match(symbol, 0, 3, 6) || match(symbol, 1, 4, 7) || match(symbol, 2, 5, 8) || // Vertical Checks\n match(symbol, 0, 4, 8) || match(symbol, 2, 4, 6)) // Diagonal Checks\n return GameState::Win;\n if (std::count(board.begin(), board.end(), Symbol::Space) == 0)\n return GameState::Draw;\n return GameState::Running;\n }\n\nprivate:\n bool match(const Symbol symbol, int i1, int i2, int i3) {\n return board[i1] == symbol &amp;&amp; board[i2] == symbol &amp;&amp; board[i3] == symbol;\n }\n};\n\nclass Player\n{\npublic:\n std::string name;\n virtual int getMove(TicTacToe&amp;, const Symbol) = 0;\n};\n\nclass PlayerHuman : public Player\n{\npublic:\n virtual int getMove(TicTacToe&amp; game, const Symbol symbol) override {\n int move = -1;\n while (move == -1) {\n std::cout &lt;&lt; &quot;Enter your move for &quot; &lt;&lt; symbol &lt;&lt; &quot; (1-9)\\n&quot;;\n std::cin &gt;&gt; move;\n if (!std::cin.good()) {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n }\n --move;\n if (move &lt; 0 || move &gt; 8 || game.board[move] != Symbol::Space) {\n std::cerr &lt;&lt; &quot;Invalid input\\n\\n&quot;;\n move = -1;\n }\n }\n return move;\n };\n};\n\nclass PlayerAI : public Player\n{\npublic:\n int maxDepth = 10;\n virtual int getMove(TicTacToe&amp; game, const Symbol symbol) override {\n std::cout &lt;&lt; &quot;AI thinking for &quot; &lt;&lt; symbol &lt;&lt; &quot;\\n&quot;;\n // select random move if board is empty\n if (std::count(game.board.begin(), game.board.end(), Symbol::Space) == 9)\n return std::rand() % 9;\n // calculate best move with minimax\n int bestScore = -1000;\n std::vector&lt;int&gt; moves;\n for (int i = 0; i &lt; 9; i++) {\n if (game.board[i] == Symbol::Space) {\n game.board[i] = symbol;\n int score = minimax(game, 0, false, symbol);\n if (score &gt; bestScore) {\n bestScore = score;\n moves.clear();\n }\n if (score == bestScore)\n moves.push_back(i);\n game.board[i] = Symbol::Space;\n }\n }\n return moves[std::rand() % moves.size()];\n }\n\nprotected:\n int minimax(TicTacToe&amp; game, int depth, bool isMax, const Symbol symbol) {\n Symbol opponent = TicTacToe::swap(symbol);\n GameState state = game.evalState(symbol);\n if (state == GameState::Win)\n return 10 - depth;\n if (game.evalState(opponent) == GameState::Win)\n return -10 + depth;\n if (state == GameState::Draw || depth &gt;= maxDepth)\n return 0;\n int best = isMax ? -1000 : 1000;\n for (int i = 0; i &lt; 9; i++) {\n if (game.board[i] == Symbol::Space) {\n game.board[i] = isMax ? symbol : opponent;\n int score = minimax(game, depth + 1, !isMax, symbol);\n best = isMax ? std::max(best, score) : std::min(best, score);\n game.board[i] = Symbol::Space;\n }\n }\n return best;\n }\n};\n\nclass Game\n{\nprivate:\n TicTacToe game;\n\npublic:\n void Play(Player&amp; player1, Player&amp; player2) {\n int index = std::rand() % 2;\n Symbol symbol = Symbol::Tic;\n\n GameState state = GameState::Running;\n while (state == GameState::Running) {\n Player&amp; player = index ? player1 : player2;\n\n game.print_board();\n int move = player.getMove(game, symbol);\n\n std::cout &lt;&lt; player.name &lt;&lt; &quot; selected &quot; &lt;&lt; move + 1 &lt;&lt; &quot;\\n\\n&quot;;\n game.board[move] = symbol;\n\n state = game.evalState(symbol);\n if (state != GameState::Running) {\n game.print_board();\n if (state == GameState::Win)\n std::cout &lt;&lt; player.name &lt;&lt; &quot; Won!&quot;;\n else\n std::cout &lt;&lt; &quot;It's a Draw.&quot;;\n }\n else\n {\n index = !index;\n symbol = TicTacToe::swap(symbol);\n }\n }\n }\n};\n\nint main() {\n std::srand(static_cast&lt;unsigned int&gt;(time(0)));\n\n PlayerHuman player1;\n player1.name = &quot;human&quot;;\n\n PlayerAI player2;\n player2.name = &quot;AI&quot;;\n\n Game game;\n game.Play(player1, player2);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T17:13:09.577", "Id": "529758", "Score": "0", "body": "The `class Symbol` very Java like. You could use an `enum` and achieve the same affect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T17:41:39.513", "Id": "529760", "Score": "0", "body": "@MartinYork, I agree and have updated my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T16:29:51.557", "Id": "268597", "ParentId": "268486", "Score": "1" } } ]
{ "AcceptedAnswerId": "268529", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T19:18:53.267", "Id": "268486", "Score": "2", "Tags": [ "c++", "algorithm", "tic-tac-toe", "ai" ], "Title": "C++ - Tic Tac Toe AI powered by minmax algorithm" }
268486
<p>I am working on a quite a big Spring Boot web service and I wanted a standardized and simplified way to handle responses and exceptions by following fluent API design.</p> <p>So this is what I did and it works as I expected.</p> <p>For handling responses, first i created an <code>interface</code> like this,</p> <pre><code>public interface BaseResponse { public short code(); //holds API specific code public HttpStatus httpStatus(); // holds corresponding HTTP status code } </code></pre> <p>And then i have created an <code>enum</code> which implements above <code>BaseResponse</code> interface, All the response codes are defined here.</p> <pre><code>public enum ResponseType implements BaseResponse { SUCCESS((short) 10000, HttpStatus.OK), INVALID_FILE_TYPE((short) 10001, HttpStatus.BAD_REQUEST), //rest... } </code></pre> <p>Here's the response object (<code>ApiResponse</code>) definition,</p> <pre><code>@Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ApiResponse { //holds http status code @JsonProperty(&quot;httpStatus&quot;) private short httpStatus; //holds API response code @JsonProperty(&quot;code&quot;) private short code; //holds data return from API @JsonProperty(&quot;data&quot;) private Map&lt;String, Object&gt; data; //holds errors return from API, if error response @JsonProperty(&quot;error&quot;) private Map&lt;String, Object&gt; error; public static ErrorResponseBuilder error(ApiError err) { return new ErrorResponseBuilder(err); } public static SuccessResponseBuilder success() { return new SuccessResponseBuilder(); } /** * */ public static class ErrorResponseBuilder { private ApiError err; public ErrorResponseBuilder(ApiError err) { this.err = err; } //returns error API response public ApiResponse build() { Map&lt;String, Object&gt; d = new HashMap&lt;&gt;(); d.put(&quot;error&quot;, err.getMessage()); short httpStatus = (short) err.getType().httpStatus().value(); return new ApiResponse( httpStatus, err.getType().code(), null, d ); } } /** * */ public static class SuccessResponseBuilder { private Map&lt;String, Object&gt; pd; public SuccessResponseBuilder() { pd = new HashMap&lt;&gt;(); } public SuccessResponseBuilder attr(String key, Object value) { pd.put(key, value); return this; } //returns success API response public ApiResponse build(BaseResponse type) { short httpStatus = (short) type.httpStatus().value(); return new ApiResponse( httpStatus, type.code(), pd, null ); } } //this is for logging @Override public String toString() { return new StringBuilder() .append(&quot;httpStatus:&quot;).append(getHttpStatus()).append(&quot;, &quot;) .append(&quot;code:&quot;).append(getCode()).append(&quot;, &quot;) .append(&quot;data:&quot;).append(getData()).append(&quot;, &quot;) .append(&quot;error:&quot;).append(getError()) .toString(); } } </code></pre> <p>Then i use this object to create responses like below,</p> <p><strong>Success response</strong></p> <pre><code>//call `@Service` method, and get result of it String fileId = this.fileHandlerService.storeFile(file); //create success response ApiResponse apiRes = ApiResponse.success() .attr(&quot;fileId&quot;, fileId) .build(ResponseType.SUCCESS); //return HTTP response with 'apiRes' in body return ResponseEntity.status(apiRes.getHttpStatus()).body(apiRes); </code></pre> <p>This results in below <code>json</code> response,</p> <pre><code>{ &quot;httpStatus&quot;: 200, &quot;code&quot;: 10000, &quot;data&quot;: { &quot;fileId&quot;: &quot;a251cb619dc145f684b9682bcb503a5c&quot; } } </code></pre> <p><strong>Error response</strong></p> <p>To handle exception responses, i created a <code>Runtime Exception</code> called <code>ApiException</code>. This is being used to handle every exceptional cases. For example: user-not-found, inactive-user, invalid-file-type, etc...</p> <p><code>ApiError</code> class was created for hold API error details,</p> <pre><code>public class ApiError { private BaseResponse type; private String message; private String debugMessage; private Exception exception; } </code></pre> <p><code>ApiException</code></p> <pre><code>public class ApiException extends RuntimeException { private ApiError apiError; //boilerplate code omitted } </code></pre> <p>Use this exception like this,</p> <pre><code>throw new ApiException(ApiError.builder() .type(ResponseType.INVALID_FILE_TYPE) .message(&quot;Invalid file, please upload ms-excel file&quot;) .debugMessage(&quot;expected file extension:xlsx, but found:&quot; + fileExt) .build() ); </code></pre> <p>This results in below <code>json</code> response,</p> <pre><code>{ &quot;httpStatus&quot;: 400, &quot;code&quot;: 10001, &quot;error&quot;: { &quot;error&quot;: &quot;Invalid file, please upload ms-excel file&quot; } } </code></pre> <p>This is the mechanism used every where in the web service.</p> <ul> <li>Is this a good way to handle response ?</li> <li>How can i improve it?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:46:02.160", "Id": "529550", "Score": "0", "body": "All the json responses are composed of two equal named fields and a third field (named error in the error response and data in the success response) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T07:16:55.507", "Id": "529573", "Score": "0", "body": "@dariosicily yes, they do, in `data` field of success response, i can add objects, arrays, strings etc..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T15:57:01.830", "Id": "529591", "Score": "0", "body": "One way to avoid duplicity of maps would be build a custom serializer but `jackson-databind` package has to be added in the starting spring boot configuration, have you it in your configuration ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T06:00:42.070", "Id": "529628", "Score": "0", "body": "there is a whole article [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) addressing your concern..." } ]
[ { "body": "<p>As you are using <code>Spring Boot</code>, the best way to handle you response is to add a <a href=\"https://www.bezkoder.com/spring-boot-restcontrolleradvice/\" rel=\"nofollow noreferrer\">RestControllerAdvice</a>.</p>\n<p>A few rules to follow :</p>\n<ol>\n<li><p>Create custom <code>POJO</code> to represent your custom message (you did it already)</p>\n</li>\n<li><p>Return directly the response message in your controller, by setting the HttpStatus, here <code>2XX</code>. You don't have to define your own HttpStatus, <code>Spring Boot</code> provides it already</p>\n</li>\n<li><p>Intercept your exceptions in your <code>RestControllerAdvice</code>. It allows you to return the custom message you want</p>\n</li>\n<li><p>Avoid sending the full exception message to your user. Send a customized clear and simple message. Log your exception full message for internal investigations instead</p>\n</li>\n<li><p>Choose the right HttpStatus code for differents situations in your <code>RestControllerAdvice</code> :</p>\n<p>Parameters <code>null</code> or <code>value not set</code> : <code>400 =&gt; Bad request</code></p>\n<p>Returned <code>value not found</code> (record or list empty) : <code>404 =&gt; Not found</code></p>\n<p>Exception from server (database error, network error etc.) : <code>500 =&gt; Internal server error</code></p>\n</li>\n</ol>\n<p>Following this, you should be able to change your code to follow those few rules.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T04:55:16.223", "Id": "268971", "ParentId": "268493", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T05:15:02.260", "Id": "268493", "Score": "0", "Tags": [ "java", "error-handling", "http", "spring", "spring-mvc" ], "Title": "Spring boot: better way to handle response and exceptions" }
268493
<p>I am currently migrating some code from class-based components to function components using hooks in <em>React</em>. Where I have come across a piece of code that works as expected but there are 3 <em>Axios</em> calls that are dependent on input from the first Axios call.</p> <p>First Axios call returns <em>order amount</em> and <em>merchant ID</em> that are required for the second API to execute and the third API requires order ID and customer ID.</p> <p>How can I deal with nested callbacks and write some clean, clear and readable code?</p> <pre><code>function getOrderDetails(customerId, token) { const orderDetailsPayload = { customerId, source: 'source' }; setLoader(true); firstApi(orderDetailsPayload, token) .then(res =&gt; { setMerchantName(res.merchantName); setMerchantRedirectLink(res.merchantPlatformLink); if (res.orderAmount) { orderDetails(res); const emiPayload = { orderAmount: res.orderAmount, merchantId: res.merchantId }; secondApi(emiPayload) .then(res =&gt; { console.log('EMI Response : ', res); if (res.data.status_code === 200) { setLoader(false); emiDetails(res.data); } else { setLoader(false); setAlert(true); console.log('EMI Details not present'); setErrorMsg(res.data.message); setRoute('SignUp'); } }) .finally(() =&gt; { setLOADERemiCalculator(false); }); const redirectionPayload = { customerId, orderId: res.orderId }; thirdApi(redirectionPayload).then(res =&gt; { console.log('Redirection Response : ', res); if (res.data.status_code === 200) { setLoader(false); redirectionDetails(res.data); setRedirection(true); setMerchantRedirectLink(res.data.redirectionInfo.redirectionUrl); } else { setLoader(false); setRedirection(false); console.log('Redirection URL not present'); } }); } else { setLoader(false); setAlert(true); console.log('Order Amount missing'); setErrorMsg( 'Oops something went wrong please contact customer care' ); setLOADERemiCalculator(false); setRoute('SignUp'); } }) .catch(exception =&gt; { setLoader(false); console.log('getCheckoutApprovedProduct exception : ', exception); setAlert(true); setErrorMsg( 'Oops something went wrong please contact customer care' ); setRoute('SignUp'); }) .finally(() =&gt; { setLOADERgetOrderDetails(false); console.log('Finally block:getOrderDetails'); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T06:38:47.260", "Id": "529492", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:10:03.587", "Id": "529527", "Score": "0", "body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:47:25.577", "Id": "529530", "Score": "3", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T21:05:30.813", "Id": "529552", "Score": "0", "body": "The best thing I can think of is to break this up into many smaller functions. This thing is pretty large and nested." } ]
[ { "body": "<p>You can use the async/await syntax, its purpose is exactly cleaning up nested callbacks like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T07:55:21.780", "Id": "529499", "Score": "0", "body": "I have added async and await to my code and updated my question. Please check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T10:10:27.400", "Id": "529578", "Score": "0", "body": "You need to put an `await` for each promise. You can check this guide from [MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) for a starter on this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T06:19:55.087", "Id": "268495", "ParentId": "268494", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T05:19:10.370", "Id": "268494", "Score": "0", "Tags": [ "javascript", "react.js", "axios" ], "Title": "How to deal with nested callbacks in a clean way?" }
268494
<p>A project of mine required me to search for certain workbooks in open instances of Excel. I found this article <a href="http://exceldevelopmentplatform.blogspot.com/2019/01/vba-code-to-get-excel-word-powerpoint.html" rel="nofollow noreferrer">Code to get Excel, Word, PowerPoint from window handle</a> which returns the applications for all the open Excel windows. Close to what I want but not exactly what I needed. The problem with that approach was that it could multiple references to the same instance. One reference per window. So after some research, blood sweet, and system crashes; this is what I came up with.</p> <pre><code>Option Explicit Rem VBA - Code to get Excel, Word, PowerPoint from window handle Rem http://exceldevelopmentplatform.blogspot.com/2019/01/vba-code-to-get-excel-word-powerpoint.html #If VBA7 Then Public Declare PtrSafe Function AccessibleObjectFromWindow Lib &quot;oleacc&quot; (ByVal hwnd As LongPtr, ByVal dwId As LongPtr, ByRef riid As Any, ByRef ppvObject As Object) As LongPtr Public Declare PtrSafe Function FindWindowEx Lib &quot;USER32&quot; Alias &quot;FindWindowExA&quot; (ByVal hWnd1 As LongPtr, ByVal Hwnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr Public Declare PtrSafe Function GetWindowThreadProcessId Lib &quot;USER32&quot; (ByVal hwnd As LongPtr, lpdwProcessId As Long) As Long #Else Public Declare Function AccessibleObjectFromWindow Lib &quot;oleacc&quot;(ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As Any, ByRef ppvObject As Object) As Long Public Declare Function FindWindowEx Lib &quot;User32&quot; Alias &quot;FindWindowExA&quot; (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long Public Declare Function GetWindowThreadProcessId Lib &quot;user32&quot; Alias &quot;GetWindowThreadProcessId&quot; (ByVal hwnd As Long, lpdwProcessId As Long) As Long #End If Function ProcIDFromHWnd(ByVal hwnd As Variant) As Variant Dim idProc As Variant GetWindowThreadProcessId hwnd, idProc ProcIDFromHWnd = idProc End Function Public Function InstanceMap(ParamArray ClassList() As Variant) As Collection Dim GUID&amp;(0 To 3) GUID(0) = &amp;H20400 GUID(1) = &amp;H0 GUID(2) = &amp;HC0 GUID(3) = &amp;H46000000 #If VBA7 Then Dim hwnd As LongPtr, ChildHwnd As LongPtr, PID As LongPtr #Else Dim hwnd As Long, ChildHwnd As Long, PID As Long #End If Dim WindowObject As Object Dim Map As New Collection Dim n As Long Do hwnd = FindWindowEx(0, hwnd, CStr(ClassList(0)), vbNullString) If hwnd = 0 Then Exit Do ChildHwnd = hwnd For n = 1 To UBound(ClassList) ChildHwnd = FindWindowEx(ChildHwnd, 0, CStr(ClassList(n)), vbNullString) Next If AccessibleObjectFromWindow(ChildHwnd, &amp;HFFFFFFF0, GUID(0), WindowObject) = 0 Then On Error Resume Next PID = ProcIDFromHWnd(hwnd) Map.Add WindowObject.Application, CStr(PID) On Error GoTo 0 End If DoEvents Loop Set InstanceMap = Map End Function Public Function ExcelInstanceMap() As Collection Set ExcelInstanceMap = InstanceMap(&quot;XLMAIN&quot;, &quot;XLDESK&quot;, &quot;EXCEL7&quot;) End Function Public Function WordInstanceMap() As Collection Set WordInstanceMap = InstanceMap(&quot;OpusApp&quot;, &quot;_WwF&quot;, &quot;_WwB&quot;, &quot;_WwG&quot;) End Function Public Function PowerPointInstanceMap() As Collection Set PowerPointInstanceMap = InstanceMap(&quot;PPTFrameClass&quot;, &quot;MDIClient&quot;, &quot;mdiClass&quot;) End Function </code></pre> <p>The code runs fine but while refactoring it a came across something peculiar in the following line:</p> <blockquote> <pre><code>If AccessibleObjectFromWindow(ChildHwnd, &amp;HFFFFFFF0, GUID(0), WindowObject) = 0 Then </code></pre> </blockquote> <p>GUID is a 4 element array of long values. No where in the code is the full array used, only the first element (&amp;H20400). So I thought that I could get rid of the array altogether and just pass in <code>&amp;H20400</code>. Wrong!</p> <p>My guess is that either the dll file's garbage collector is expecting to clean up all the values or the while array is getting referenced when <code>GUID(0)</code> is passed into the function or more than likely something different.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T12:22:08.357", "Id": "529514", "Score": "2", "body": "_\"No where in the code is the full array used, only the first element\"_ actually since you pass the first element `ByRef riid As Any` what you're actually supplying is a pointer to the first element of the GUID array rather than the value of the first element. The API function can offset this pointer to find other parts of the array, or more likely will just dereference the 128bits of the GUID at once starting from the pointer. This works because values from VBA SAFEARRAYs are stored adjacent in memory. Change to `ByVal pRiid As LongPtr` and `VarPtr(GUID(0))` and it will make more sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T14:51:29.023", "Id": "529525", "Score": "0", "body": "Basically what I originally thought but well stated. Thanks @Greedo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T14:53:18.930", "Id": "529526", "Score": "0", "body": "@Greedo Ah- that's why it's passing in the first value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T16:15:14.870", "Id": "529531", "Score": "1", "body": "Have you tried using `GetObject(, \"Excel.Application\")` ? If you think there are multiple instances I would go through them, closing them as I go until the `GetObject` fails. Would be much simpler with native methods like this. Related reading: https://docs.microsoft.com/en-us/office/troubleshoot/office-suite-issues/getobject-createobject-behavior" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T17:10:32.727", "Id": "529536", "Score": "1", "body": "Thanks @HackSlash But my code works as intended. Some uses cases require me to work with multiple instances. In this case, when the user double clicks a third party embedded chart object. The comAddIn then opens a workbook in anew instance of Excel populated with all the chart data. My program detects the new worksheet gathers the data, closed the instance and the user does a wash, rinse and repeat." } ]
[ { "body": "<blockquote>\n<pre><code>Public Declare PtrSafe Function AccessibleObjectFromWindow Lib &quot;oleacc&quot; (ByVal hwnd As LongPtr, ByVal dwId As LongPtr, ByRef riid As Any, ByRef ppvObject As Object) As LongPtr\nPublic Declare PtrSafe Function FindWindowEx Lib &quot;USER32&quot; Alias &quot;FindWindowExA&quot; (ByVal hWnd1 As LongPtr, ByVal Hwnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr\nPublic Declare PtrSafe Function GetWindowThreadProcessId Lib &quot;USER32&quot; (ByVal hwnd As LongPtr, lpdwProcessId As Long) As Long\n</code></pre>\n</blockquote>\n<p>I feel quite strongly that API declares are rarely used to their full potential in VBA. People too often <em>transliterate</em> these declarations - rewriting C++ code in VBA, rather than <em>translating them into</em> idiomatic VBA. The Alias keyword and ByRef/ByVal modifiers can be used to achieve a higher standard of abstraction similar to what you would expect from other VBA code you write, and renaming variables to avoid Systems Hungarian notation which is not required in VBA can simplify the black box of WinApi calls as well. For example why do I need to know <code>lpszFoo</code> is a long pointer to a zero terminated string when VBA literally defines native strings in that way? The code calling the API does not need to be aware of this low level information, get rid of it. I sometimes even declare the same function twice under different aliases to match the context in which it is called.</p>\n<p>So I would modify the declares to something like this:</p>\n<pre><code>'Stolen from https://github.com/wine-mirror/wine/blob/08b01d8271fe15c7680a957778d506221d7d94eb/include/winuser.h#L3181-L3195\nPrivate Enum ObjectIdentifier\n OBJID_WINDOW = 0\n OBJID_SYSMENU = -1\n OBJID_TITLEBAR = -2\n OBJID_MENU = -3\n OBJID_CLIENT = -4\n OBJID_VSCROLL = -5\n OBJID_HSCROLL = -6\n OBJID_SIZEGRIP = -7\n OBJID_CARET = -8\n OBJID_CURSOR = -9\n OBJID_ALERT = -10\n OBJID_SOUND = -11\n OBJID_QUERYCLASSNAMEIDX = -12\n OBJID_NATIVEOM = -16 'This is the one you use, &amp;HFFFFFFF0\nEnd Enum\n\nPrivate Declare PtrSafe Function AccessibleObjectFromWindow Lib &quot;oleacc&quot; (ByVal hWnd As LongPtr, ByVal ID As ObjectIdentifier, ByRef interfaceRiid As Any, ByRef outInstance As Object) As LongPtr\nPrivate Declare PtrSafe Function FindWindowEx Lib &quot;USER32&quot; Alias &quot;FindWindowExA&quot; (ByVal hWndParent As LongPtr, ByVal hWndChildAfter As LongPtr, ByVal className As String, Optional ByVal windowName As String) As LongPtr\nPrivate Declare PtrSafe Function GetWindowThreadProcessId Lib &quot;USER32&quot; (ByVal hwnd As LongPtr, ByRef outProcessId As Long) As Long\n</code></pre>\n<ul>\n<li>Everything <code>Private</code> because these are implementation details and don't need to be exposed.</li>\n<li>Introduce an <code>ObjectIdentifier</code> Enum to get rid of magic <code>&amp;HFFFFFFF0</code> later on.</li>\n<li>In <code>AccessibleObjectFromWindow</code>, change <code>ByVal dwId As LongPtr</code> to <code>ByVal ID As ObjectIdentifier</code> since dw stands for DWORD which is a 32-bit integer <em>always</em>, just like VBA's Long (Enum is an alias for Long, so they can be used interchangeably).</li>\n<li>Explicit <code>ByRef</code> keyword added to the <code>lpdwProcessID</code> because it's important it doesn't become ByVal.</li>\n<li>In fact if we say <code>ByRef</code> we can drop the <code>lp</code> prefix since that's what <code>ByRef</code> means, and we can also drop <code>dw</code> since that's what <code>As Long</code> means.</li>\n<li>Use <code>outBlah</code> for variables which will be assigned by the API functions.</li>\n<li>It's fine to use Optional in these functions too if you always pass <code>vbNullString</code></li>\n</ul>\n<p>I know you probably just copy-pasted from vb forums so moving on...</p>\n<hr />\n<blockquote>\n<pre><code>Function ProcIDFromHWnd(ByVal hwnd As Variant) As Variant\n Dim idProc As Variant\n GetWindowThreadProcessId hwnd, idProc\n ProcIDFromHWnd = idProc\nEnd Function\n</code></pre>\n</blockquote>\n<p>Instead, how about without variant:</p>\n<pre><code>Private Function ProcIDFromHWnd(ByVal hwnd As LongPtr) As Long\n If GetWindowThreadProcessId(hwnd, outProcessId:=ProcIDFromHWnd) = 0 Then\n Err.Raise 5, Description:=&quot;We didn't get a valid thread ID&quot;\n End If\nEnd Function\n</code></pre>\n<p>Notice you can also use the return value to see if the function succeeded.</p>\n<hr />\n<blockquote>\n<pre><code>Dim hwnd As LongPtr, ChildHwnd As LongPtr, PID As LongPtr\n</code></pre>\n</blockquote>\n<p>I guess declare these closer to usage would be nice, although I see you use conditional compilation so it could get messy. Should be <code>PID As Long</code> though, again DWORDs are always 32-bit.*</p>\n<p><sub>*Oversized variables still generally happen to work - because VBA is managing the memory so it gets allocated/ deallocated properly still, and integral types are little endian (or fill memory in reverse) meaning the first 32 bits of a Long or a LongLong with the same value will be the same.</sub></p>\n<hr />\n<blockquote>\n<pre><code>On Error Resume Next\nPID = ProcIDFromHWnd(hwnd)\nMap.Add WindowObject.Application, CStr(PID)\nOn Error GoTo 0\n</code></pre>\n</blockquote>\n<p>What error are you expecting? Better to remove so you can launch into the debugger when an error occurs.</p>\n<hr />\n<blockquote>\n<pre><code>Do\n hwnd = FindWindowEx(0, hwnd, CStr(ClassList(0)), vbNullString)\n If hwnd = 0 Then Exit Do\n\n ChildHwnd = hwnd\n For n = 1 To UBound(ClassList)\n ChildHwnd = FindWindowEx(ChildHwnd, 0, CStr(ClassList(n)), vbNullString)\n Next\n '[...]\n DoEvents\nLoop\n</code></pre>\n</blockquote>\n<p>This is kinda dangerous having an infinite loop with <code>DoEvents</code>. What if that allows the Z-Order of windows to change, meaning <code>hwnd = FindWindowEx(0, hwnd, CStr(ClassList(0)), vbNullString)</code> will never return 0 since you keep hopping between windows. Removing the <code>DoEvents</code> would be good although the situation could still crop up where you have a circular reference because another application is misbehaving. Safer would be to keep a track of all hwnds you've seen and then exit the loop if one repeats.</p>\n<p>Also the process of looping through top level windows with <code>FindWindowEx(0, 0 |prevhwnd, specialClassName,&quot;&quot;)</code> has a few too many re-assignments and could be cleaned up.</p>\n<p>I would add maybe:</p>\n<pre><code>Private Function TryGetNextWindowHwnd(ByVal className As String, ByVal prevHWnd As LongPtr, ByRef outNextHWnd As LongPtr) As Boolean\n outNextHWnd = FindWindowEx(0, prevHWnd, className)\n TryGetNextWindowHwnd = outNextHWnd &lt;&gt; 0\nEnd Function\n</code></pre>\n<p>... which you can use in the loop:</p>\n<pre><code>Do While TryGetNextWindowHwnd(TopLevelClassName, parentHWnd, outNextHWnd:=parentHWnd)\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>For n = 1 To UBound(ClassList)\n ChildHwnd = FindWindowEx(ChildHwnd, 0, CStr(ClassList(n)), vbNullString)\nNext\n</code></pre>\n</blockquote>\n<p>Maybe add a comment saying what this does, drilling down through window class names took me by surprise a little. Also CStr is redundant, and since ClassList(n) only goes from 1 to ubound, maybe ClassList(0) should be passed as its own argument:</p>\n<pre><code>Public Function InstanceMap(ByVal TopLevelClassName As String, ParamArray ClassList() As Variant) As Collection\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>Public Function ExcelInstanceMap() As Collection\n Set ExcelInstanceMap = InstanceMap(&quot;XLMAIN&quot;, &quot;XLDESK&quot;, &quot;EXCEL7&quot;)\nEnd Function\n\nPublic Function WordInstanceMap() As Collection\n Set WordInstanceMap = InstanceMap(&quot;OpusApp&quot;, &quot;_WwF&quot;, &quot;_WwB&quot;, &quot;_WwG&quot;)\nEnd Function\n\nPublic Function PowerPointInstanceMap() As Collection\n Set PowerPointInstanceMap = InstanceMap(&quot;PPTFrameClass&quot;, &quot;MDIClient&quot;, &quot;mdiClass&quot;)\nEnd Function\n</code></pre>\n</blockquote>\n<p>Really nice simple interface. A shame it isn't strongly typed as Excel.Application, Word.Application though. Still the iteration variable could be. Also why store PID as the key in a collection at all; since collection keys are not readable, the only reason I can think to use it would be to lookup the instance of the current process' Application from the collection - but in that case you could just use the default <code>Application</code> object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T21:49:32.490", "Id": "529617", "Score": "1", "body": "\"I feel quite strongly that API declares are rarely used to their full potential in VBA. People too often transliterate these declarations - rewriting C++ code in VBA, rather than translating them into idiomatic VBA\". Would give you +1 just for that. Lots of gems in rest as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T21:58:07.137", "Id": "529618", "Score": "0", "body": "Great Review!!! I use the Windows API Viewer for Excel x64. Agreed, the first class should be a named argument. I did not know that changing the Z-Order have that effect, awesome tip! `DoEvents` was added as a precaution. The user clicks a toggle which monitors for new applications being opened in a loop. I'll have to think about this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T22:04:32.977", "Id": "529619", "Score": "1", "body": "`AccessibleObjectFromWindow` returns a handle for each Excel window. An application may have more that 1 window. The `PID` is used to filter out the duplicates. This would have probably made a good comment in the script." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:25:06.420", "Id": "268545", "ParentId": "268498", "Score": "5" } } ]
{ "AcceptedAnswerId": "268545", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T09:46:56.423", "Id": "268498", "Score": "3", "Tags": [ "vba", "excel", "winapi" ], "Title": "Collecting all instances of an Office application (Excel, PowerPoint, Word)" }
268498
<p>I'm just getting to know the possibilities of Kotlin and mongoDB.<br /> I am writing a method that returns the name of the street after the ID.<br /> Everything works, but I find it quite sloppy.<br /> Empty String initialization, returning more data from the collection than I would like. How do I straighten it? Could it be made into some expression body one-liner?</p> <pre><code> fun getStreetNameByStreetId(id: String): String { val query = Query() query.fields().include(&quot;name&quot;) query.addCriteria(Criteria.where(&quot;_id&quot;).`is`(id)) var streetName = &quot;&quot; mongoTemplate.executeQuery( query, STREET_COLLECTION ) { document: Document -&gt; streetName = document.getValue(&quot;name&quot;).toString() } return streetName } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T01:02:54.557", "Id": "529812", "Score": "0", "body": "I don't use mongo, but this doesn't look like it would even work. You modify `streetName` with an asynchronous callback, so you're returning the original empty String before the callback even has a chance to be called. e.g. https://stackoverflow.com/questions/57330766/why-does-my-function-that-calls-an-api-return-an-empty-or-null-value" } ]
[ { "body": "<p>This is how it would look in <strong>Java</strong>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public String getStreetNameByStreetId(String id) {\n Query streetNameByStreetId = Query.query(\n Criteria.where(&quot;_id&quot;).is(id));\n byStreetId.fields().include(&quot;name&quot;);\n return mongoTemplate.find(streetNameByStreetId, Street.class)\n .get(0).getName();\n}\n</code></pre>\n<p><em>I realize you are looking for how this would look in Kotlin, but it should look very similar. Also, for simple CRUD operations you might want to consider just using a <strong>MongoRepository</strong> and leveraging the <strong>Domain Specific Language (DSL)</strong>.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:38:26.013", "Id": "269296", "ParentId": "268499", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T12:08:23.397", "Id": "268499", "Score": "1", "Tags": [ "database", "kotlin", "spring", "mongodb" ], "Title": "Cleaning Kotlin method which returns the document name after the id" }
268499
<p>I have a React hook &quot;useFetchSales&quot; that fetches all documents from the &quot;sales&quot; collection in Firestore:</p> <pre class="lang-js prettyprint-override"><code>import { useState, useEffect } from 'react'; import db from &quot;../firebase.config&quot;; import { collection, query, onSnapshot, orderBy } from &quot;firebase/firestore&quot;; function useFetchSales() { const [saleList, setSaleList] = useState([]); useEffect(() =&gt; { const q = query(collection(db, &quot;sales&quot;), orderBy(&quot;created_at&quot;, &quot;desc&quot;)); const unsubscribe = onSnapshot(q, (querySnapshot) =&gt; { const sales = querySnapshot.docs.map(doc =&gt; { const data = doc.data(); return { id: doc.id, created_at: data.created_at, product: data.product, user: data.user } }); setSaleList(sales); }) return () =&gt; unsubscribe(); }, []) /** * Should return: * [ * { * id, * created_at, * product, * user * } * ] */ return saleList; } export default useFetchSales; </code></pre> <p>This works great, because it's not asynchronous. Or at least... it doesn't use async/await. I say this because that's exactly my problem.</p> <p>The &quot;product&quot; data here is a code. I have an other collection (products) where each code is accompanied with product data. Like the name, price, etc.</p> <p>I list all the documents in the sales collection, but before that I go over each document in the collection; look up the code in the products collection and change the code with the name.</p> <p>The code for this seemingly simple idea is, in my opinion, overly complex. Because of the asynchronous nature of Firestore. All the functions kept returning fulfilled promises instead of the promise value. Super annoying in my opinion.</p> <p>To get a &quot;products&quot; state with the desired value I had to use this code:</p> <pre class="lang-js prettyprint-override"><code> // The FetchSales hook, which returns all the documents in sales as an array with objects in a certain layout. const sales = useFetchSales(); // The state which should in the end have the treated data. code =&gt; product name const [products, setProducts] = useState([]); // The first function. It fetches the document from the products collection and should return the name property of the document. This returns a &quot;promise&lt;fulfilled&gt;&quot; with the value inside. Which is completely useless as the value cannot be reached. async function fetchProductName(code) { const docRef = doc(db, &quot;products&quot;, code); const docSnap = await getDoc(docRef); if(docSnap.exists()) { return docSnap.data().name; } else { return &quot;Non existent&quot;; } } // Here I have a useEffect that maps over the sales when it's changed and gets the productName from the fetchProductName function above. Inside the map method there's an other async function so that I can access the returned value from the fetchProductName function. This is where it seems overly complicated IMO. useEffect(() =&gt; { sales.map(sale =&gt; { async function getProductName() { const productName = await fetchProductName(sale.product); setProducts(oldProducts =&gt; [...oldProducts, { id: sale.id, created_at: sale.created_at, product: productName, user: sale.user }]) } getProductName().then(() =&gt; console.log(&quot;fetched product name finally&quot;)); }) }, [sales]) </code></pre> <p>How can I do this differently? Thanks in advance!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:25:31.930", "Id": "268504", "Score": "0", "Tags": [ "javascript", "react.js", "asynchronous" ], "Title": "Overly complex code for a seemingly simple idea. Fulfilled promises returned instead of values" }
268504
<p>I'm using the <code>logging</code> module in python and I need a function or class method which logs only if some condition is false, similar to <code>assert</code> but logging a message instead of raising an exception.</p> <p>In order to still be able to use the condition in <code>if</code>, <code>while</code>, <code>any</code>, <code>all</code> etc., I would like to have the function/method pass through the condition.</p> <p>This is my code:</p> <pre><code>import logging def log_if_false(cond: bool, logmsg: str, level = logging.DEBUG: int, logger = logging): if not cond: logger.log(level, logmsg) return cond # Pass through so it is possible to log on the fly while checking a condition </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T13:56:52.007", "Id": "268505", "Score": "0", "Tags": [ "python-3.x", "logging" ], "Title": "Pass-through conditional logging" }
268505
<p>I was messing around with the csv package and I tried to implement a class that returns csv objects whenever I need to open a csv file directly from a url(and occasionally prints out something).I am still very green and I would like to know if there is something I can do to optimize this code.You are going to find the description of every method in each docstring.There are still some functionalities that I want to add, but I would like to know if the design of this very simple class is acceptable and if there is something that I could make better or faster. Thank you for your attention and time.</p> <pre><code>import csv, urllib.request class read_CSV_URL: def __init__(self, url): self.request = urllib.request.urlopen(url) def read_csv_from_url(self, delimiter=&quot;,&quot;, num_of_lines=&quot;all&quot;, print_lines=False) -&gt; object: &quot;&quot;&quot; Read a csv file form a url. Three default values: 1. Delimiter is a standard coma. 2. Number of lines that are going to be printed In case you wanted just the first three lines of your file you can just set num_of_lines=3. 3. In case you want to print the lines set, print_lines=True. &quot;&quot;&quot; lines = [l.decode('utf-8') for l in self.request.readlines()] # decode response csv_object = csv.reader(lines, delimiter=delimiter) if print_lines: if num_of_lines == &quot;all&quot;: for line in csv_object: print(line) else: for number in range(num_of_lines): row = next(csv_object) print(row) return csv_object def read_csv_from_url_as_dict(self, delimiter=&quot;,&quot;, num_of_lines=&quot;all&quot;, print_lines=False) -&gt; object: &quot;&quot;&quot; Read a csv file form a url as a dictionary. Three default values: 1. Delimiter is a standard coma. 2. Number of lines that are going to be printed In case you wanted just the first three lines of your file you can just set num_of_lines=3. 3. In case you want to print the lines set, print_lines=True. &quot;&quot;&quot; lines = [l.decode('utf-8') for l in self.request.readlines()] # decode response csv_object = csv.DictReader(lines, delimiter=delimiter) if print_lines: if num_of_lines == 'all': for dicty in csv_object: print(dicty) else: for number in range(num_of_lines): print(next(csv_object)) return csv_object def get_key(self, key : str, csv_object): &quot;&quot;&quot; Get a single key given a csv_dictionary_object. &quot;&quot;&quot; listy = [] for row in csv_object: listy.append(row[key]) return listy def get_keys(self, csv_object, **kwargs) -&gt; list: listy = [] for row in csv_object: sub_list = [] for key in kwargs.values(): sub_list.append(row[key]) listy.append(sub_list) return listy csv_1 = read_CSV_URL('http://winterolympicsmedals.com/medals.csv') print(csv_1.read_csv_from_url_as_dict(print_lines=True)) </code></pre>
[]
[ { "body": "<p>This is doing too much. You're trying to support reading rows as both a list and a dict; both printing and not; and reading all lines or some lines.</p>\n<p>Change the class name to follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n<p>Drop most of your configuration options.</p>\n<ul>\n<li>Don't print lines as you go. This was debugging code and can be removed in the final version.</li>\n<li>Either return <code>list</code> or <code>dict</code> items but not both--write two classes if you really need both options.</li>\n<li>Always read all lines. Let the user directly iterate over the class. As a feature, support streaming access--I assume the reason you're avoiding reading all lines is so you can print faster.</li>\n<li>Drop <code>get_key</code> and <code>get_keys</code> entirely, make them a static method, or move them out of the class.</li>\n</ul>\n<p>A piece of example code, the way I would want to use this as a user:</p>\n<pre><code>for row in read_CSV_URL('http://winterolympicsmedals.com/medals.csv'):\n​ print(row)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T02:28:31.430", "Id": "268834", "ParentId": "268506", "Score": "3" } }, { "body": "<p>Building off of what Zachary Vance said: since you haven't shown much usage of this class, I can only assume that some of your features (like supporting partial body retrieval) are not needed; and others should be moved like printing, which really should not be integrated.</p>\n<p>Generally, don't use <code>urllib.request</code> when <code>requests</code> exists. A basic implementation of <a href=\"https://docs.python-requests.org/en/latest/api/#requests.Response.iter_lines\" rel=\"nofollow noreferrer\">line-buffered</a>, streamed CSV retrieval can look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>from csv import DictReader\nfrom pprint import pprint\nfrom typing import Iterator, Dict\n\nimport requests\n\n\ndef read_csv_url(url: str, *args, **kwargs) -&gt; Iterator[Dict[str, str]]:\n with requests.get(url, stream=True) as resp:\n resp.raise_for_status()\n file_like = resp.iter_lines(decode_unicode=True)\n yield from DictReader(f=file_like, *args, **kwargs)\n\n\ndef test() -&gt; None:\n for record in read_csv_url('http://winterolympicsmedals.com/medals.csv'):\n pprint(record)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T14:02:12.127", "Id": "269913", "ParentId": "268506", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T14:14:30.187", "Id": "268506", "Score": "1", "Tags": [ "python", "object-oriented" ], "Title": "optimization csv from url analyzer" }
268506
<p>Below there is a full code for my app Staff Manager. The app does allow basic staff management, like adding, removing or changing details of employees. As it is one of my first GUI apps and I am self-taught (I have been learning for about 6 months now, a couple of hours every day after work) I would like to see what you guys think about my code. Would like to see the opinion of other people. Any advice on improvements (to my work and code) is welcome. Won't get upset if I will get criticized. Here to learn and improve.</p> <pre><code>from json.decoder import JSONDecodeError import tkinter as tk from tkinter import StringVar, Toplevel, ttk import os, json import copy class Staff_Manager(tk.Tk): def __init__(self) -&gt; None: super().__init__() self.check_save_file() self.geometry(&quot;1520x600&quot;) self.title(&quot;Staff Manager&quot;) self.iconbitmap(&quot;icon.ico&quot;) self.buttons() self.data_view() self.update self.delete self.is_retired # check if data save file exists and if not create one. def check_save_file(self): current_path = os.path.dirname(__file__) json_file = f'{current_path}\\emp_data.json' if os.path.isfile(json_file) == True and os.stat(json_file).st_size != 0: pass else: with open(json_file, 'w+') as f: data = {&quot;people&quot;: []} json.dump(data, f) def buttons(self): # managing buttons, main window add = ttk.Button(self, text= 'Add', command= Add_New_Emp) add.place(x= 10, y= 10, width= 75) amend = ttk.Button(self, text= 'Amend', command= self.amend) amend.place(x= 10, y= 45, width= 75) refresh = ttk.Button(self, text= 'Refresh', command= self.update) refresh.place(x= 10, y= 80, width= 75) retire = ttk.Button(self, text= 'Retire', command= self.is_retired) retire.place(x= 10, y= 135, width= 75, height= 40) remove = ttk.Button(self, text= 'Remove', command= self.delete) remove.place(x= 10, y= 230, width= 75, height= 40) exit_button = ttk.Button(self, text= 'EXIT', command= self.destroy) exit_button.place(x= 10, y= 538, width= 75, height= 40) def data_view(self): #create columns for tree view columns = ('#1', '#2', '#3', '#4', '#5', '#6', '#7') self.view_panel = ttk.Treeview(self, columns= columns, show= 'headings', height= 27) self.view_panel.place(x= 90, y= 10) # headings self.view_panel.heading('#1', text= 'Name') self.view_panel.heading('#2', text= 'Surname') self.view_panel.heading('#3', text= 'Position') self.view_panel.heading('#4', text= 'DoB') self.view_panel.heading('#5', text= 'Start Date') self.view_panel.heading('#6', text= 'End Date') self.view_panel.heading('#7', text= 'Retired?') # set up the scrollbar scrollbar = ttk.Scrollbar(self, orient= tk.VERTICAL, command= self.view_panel.yview) self.view_panel.configure(yscrollcommand= scrollbar.set) scrollbar.place(x= 1495, y= 10, height= 575) # insert data with open('emp_data.json', 'r') as f: empty_file = False try: data = json.load(f) except JSONDecodeError: empty_file = True pass employees = [] if empty_file == False: for item in data[&quot;people&quot;]: name = item[&quot;name&quot;] surname = item[&quot;surname&quot;] position = item[&quot;position&quot;] dob = item[&quot;dob&quot;] start = item[&quot;start&quot;] end = item[&quot;end&quot;] retired = item[&quot;retired&quot;] employees.append((name, surname, position, dob, start, end, retired)) # insert all the data to the view panel for emp in employees: self.view_panel.insert('', tk.END, values= emp) # update information on the view panel def update(self): self.data_view() # amend emp data def amend(self): amend_win = tk.Tk() amend_win.geometry('350x250') amend_win.title('Amend Employee Details') amend_win.iconbitmap('icon.ico') # cancel button def is_cancel(): amend_win.destroy() # change button def is_amended(to_change, new_personal_data): current_item = self.view_panel.focus() info = self.view_panel.item(current_item) details = info[&quot;values&quot;] to_remove = { &quot;name&quot;: str(details[0]), &quot;surname&quot;: str(details[1]), &quot;position&quot;: str(details[2]), &quot;dob&quot;: str(details[3]), &quot;start&quot;: str(details[4]), &quot;end&quot;: str(details[5]), &quot;retired&quot;: str(details[6]) } to_remove = copy.deepcopy(to_remove) details_dict = { &quot;name&quot;: str(details[0]), &quot;surname&quot;: str(details[1]), &quot;position&quot;: str(details[2]), &quot;dob&quot;: str(details[3]), &quot;start&quot;: str(details[4]), &quot;end&quot;: str(details[5]), &quot;retired&quot;: str(details[6]) } for key, value in details_dict.items(): if key == to_change: details_dict[f&quot;{to_change}&quot;] = new_personal_data with open('emp_data.json', 'r') as f: data = json.load(f) new_data = { &quot;people&quot;: [] } for emp_dict in data[&quot;people&quot;]: if to_remove != emp_dict: new_data[&quot;people&quot;].append(emp_dict) new_data[&quot;people&quot;].append(details_dict) with open('emp_data.json', 'w') as f: json.dump(new_data, f, indent= 4) amend_win.destroy() # check if data is not empty, if is: n/a def is_empty(data): if len(data) == 0: return 'n/a' else: return data main_choice_lbl = ttk.Label(amend_win, text= 'What would you like to change?', font= ('Arial', 12)) main_choice_lbl.place(x= 10, y= 10) self.data_options = ('name', 'surname', 'position', 'dob', 'start', 'end') self.choice = StringVar() options = ttk.OptionMenu(amend_win, self.choice, self.data_options[0], *self.data_options) options.place(x= 10, y= 47) options.config(width= 15) new_emp_data = ttk.Label(amend_win, text= 'New data:', font= ('Arial', 12)) new_emp_data.place(x= 10, y= 90) main_entry = ttk.Entry(amend_win, justify= 'right') main_entry.place(x= 10, y= 130) ok_button = ttk.Button(amend_win, text= 'CHANGE', command= lambda: is_amended(self.choice.get(), is_empty(main_entry.get()))) ok_button.place(x= 60, y= 200) cancel_button = ttk.Button(amend_win, text= 'CANCEL', command= is_cancel) cancel_button.place(x= 150, y= 200) def delete(self): # get the &quot;clicked&quot; emp current_item = self.view_panel.focus() # get the info of &quot;clicked&quot; emp : dict info = self.view_panel.item(current_item) # get details of &quot;clicked&quot; emp, &quot;values&quot; are stored emp data : list details = info[&quot;values&quot;] # set the data to json format (need to convert some int to str as program is creating all data as strings) details_dict = { &quot;name&quot;: str(details[0]), &quot;surname&quot;: str(details[1]), &quot;position&quot;: str(details[2]), &quot;dob&quot;: str(details[3]), &quot;start&quot;: str(details[4]), &quot;end&quot;: str(details[5]), &quot;retired&quot;: str(details[6]) } with open('emp_data.json', 'r') as f: data = json.load(f) new_data = { &quot;people&quot;: [] } for emp_dict in data[&quot;people&quot;]: if details_dict != emp_dict: new_data['people'].append(emp_dict) with open('emp_data.json', 'w') as f: json.dump(new_data, f, indent= 4) def is_retired(self): retired_win = tk.Tk() retired_win.geometry('280x130') # cancel button def is_cancel(): retired_win.destroy() def is_ok(): current_item = self.view_panel.focus() info = self.view_panel.item(current_item) details = info[&quot;values&quot;] to_remove = { &quot;name&quot;: str(details[0]), &quot;surname&quot;: str(details[1]), &quot;position&quot;: str(details[2]), &quot;dob&quot;: str(details[3]), &quot;start&quot;: str(details[4]), &quot;end&quot;: str(details[5]), &quot;retired&quot;: str(details[6]) } to_remove = copy.deepcopy(to_remove) details_dict = { &quot;name&quot;: str(details[0]), &quot;surname&quot;: str(details[1]), &quot;position&quot;: str(details[2]), &quot;dob&quot;: str(details[3]), &quot;start&quot;: str(details[4]), &quot;end&quot;: str(details[5]), &quot;retired&quot;: str(details[6]) } # for key, value in details_dict.items(): details_dict[&quot;retired&quot;] = &quot;Yes&quot; with open('emp_data.json', 'r') as f: data = json.load(f) new_data = { &quot;people&quot;: [] } for emp_dict in data[&quot;people&quot;]: if to_remove != emp_dict: new_data[&quot;people&quot;].append(emp_dict) new_data[&quot;people&quot;].append(details_dict) with open('emp_data.json', 'w') as f: json.dump(new_data, f, indent= 4) retired_win.destroy() ret_lbl = ttk.Label(retired_win, text= &quot;Are you sure you want to RETIRE your employee?&quot;) ret_lbl.place(x= 10, y= 20) ok_button = ttk.Button(retired_win, text= 'RETIRE', command= is_ok) ok_button.place(x= 40, y= 60) cancel_button = ttk.Button(retired_win, text= 'CANCEL', command= is_cancel) cancel_button.place(x= 150, y= 60) class Add_New_Emp(Toplevel): def __init__(self) -&gt; None: super().__init__() self.geometry('380x400') self.title('Employee Data') self.iconbitmap('icon.ico') self.labels() self.data_entry() # set labels def labels(self): name_lbl = ttk.Label(self, text= 'Name:', font= ('Arial', 12)) name_lbl.place(x= 10, y= 10) surname_lbl = ttk.Label(self, text= 'Surname:', font= ('Arial', 12)) surname_lbl.place(x= 10, y= 50) position_lbl = ttk.Label(self, text= 'Position:', font= ('Arial', 12)) position_lbl.place(x= 10, y= 90) dob_lbl = ttk.Label(self, text= 'Date of Birth:', font= ('Arial', 12)) dob_lbl.place(x= 10, y= 130) start_lbl = ttk.Label(self, text= 'Start Date:', font= ('Arial', 12)) start_lbl.place(x= 10, y= 170) end_lbl = ttk.Label(self, text= 'End Date:', font= ('Arial', 12)) end_lbl.place(x= 10, y= 210) retired_lbl = ttk.Label(self, text= 'Retired?', font= ('Arial', 12)) retired_lbl.place(x= 10, y= 250) # set data entry points def data_entry(self): def is_empty(data): if len(data) == 0: return 'n/a' else: return data # accepting details, pressing ok button def is_ok(): # get all the data name = is_empty(name_ent.get()) surname = is_empty(surname_ent.get()) position = is_empty(position_ent.get()) dob = is_empty(dob_ent.get()) start = is_empty(start_ent.get()) end = is_empty(end_ent.get()) retired = retired_var.get() # append row to the employee data file with open('emp_data.json', 'r+') as f: data = json.load(f) new_emp = { &quot;name&quot;: name, &quot;surname&quot;: surname, &quot;position&quot;: position, &quot;dob&quot;: dob, &quot;start&quot;: start, &quot;end&quot;: end, &quot;retired&quot;: retired } data[&quot;people&quot;].append(new_emp) with open('emp_data.json', 'w') as f: json.dump(data, f, indent= 4) self.destroy() # cancelation of adding new emp def is_cancel(): self.destroy() name_ent = ttk.Entry(self, justify= 'right') name_ent.place(x= 215, y= 10) surname_ent = ttk.Entry(self, justify= 'right') surname_ent.place(x= 215, y= 50) position_ent = ttk.Entry(self, justify= 'right') position_ent.place(x= 215, y= 90) dob_ent = ttk.Entry(self, justify= 'right') dob_ent.place(x= 215, y= 130) start_ent = ttk.Entry(self, justify= 'right') start_ent.place(x= 215, y= 170) end_ent = ttk.Entry(self, justify= 'right') end_ent.place(x= 215, y= 210) retired_var = StringVar(value= 'No') retired_chk = ttk.Checkbutton( self, text= 'Yes', onvalue= 'Yes', offvalue= 'No', variable= retired_var) retired_chk.place(x= 215, y= 250) ok_button = ttk.Button(self, text= 'ADD', command= is_ok) ok_button.place(x= 100, y= 350) cancel_button = ttk.Button(self, text= 'CANCEL', command= is_cancel) cancel_button.place(x= 200, y= 350) if __name__ == &quot;__main__&quot;: Staff_Manager().mainloop() </code></pre>
[]
[ { "body": "<h1>PEP 8</h1>\n<p>You deviate from the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> in a couple of areas:</p>\n<ul>\n<li>Keyword arguments should not have spaces around the equals. For example\n<pre><code>add = ttk.Button(self, text= 'Add', command= Add_New_Emp)\n</code></pre>\nshould be\n<pre><code>add = ttk.Button(self, text='Add', command=Add_New_Emp)\n</code></pre>\n</li>\n<li>Class names should be <code>CapitalizedWords</code>, not <code>Capitalized_Words_With_Underscores</code>. So <code>Staff_Manager</code> and <code>Add_New_Emp</code> should be <code>StaffManager</code> and <code>AddNewEmp</code>.</li>\n</ul>\n<h1>Type Hints</h1>\n<p>The only place I see type hints used is <code>def __init__(self) -&gt; None:</code>. Clearly you've just started using them, but you need to use them more, and run your could through a checker (<code>mypy</code>, <code>pylint</code>, ...)</p>\n<h1>Dead code</h1>\n<pre class=\"lang-py prettyprint-override\"><code> self.buttons()\n self.data_view()\n self.update\n self.delete\n self.is_retired\n</code></pre>\n<p>The last three &quot;statements&quot; do nothing, and should be deleted.</p>\n<h1>Poor naming</h1>\n<p>Functions named <code>is_xxx()</code> look like functions which do not modify any state and return a <code>True</code> or <code>False</code> result. Your functions change the state of the program, and return nothing. Find better names, like <code>do_cancel()</code> and <code>perform_amend</code>.</p>\n<h1>Reuse Components</h1>\n<p>Each time <code>.data_view()</code> is called, a new <code>ttk.Treeview</code> is created, and placed on top of where the previous one was.</p>\n<p>Create the <code>ttk.Treeview</code> once, and refresh its contents when information changes.</p>\n<h1>PathLib</h1>\n<p><code>os.path.isfile(file)</code> and <code>os.stat(file)</code> are old-school functions. You should start using the newer <code>pathlib</code>. Eg)</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\n\n...\n json_file = Path(__file__).parent / 'emp_data.json'\n if json_file.is_file() and json_file.stat().st_size != 0:\n ...\n</code></pre>\n<h1>Consistent Filename</h1>\n<p>Sometimes you use <code>f'{current_path}\\\\emp_data.json'</code> to specify the database file, other times you use <code>with open('emp_data.json', 'w') as f:</code> which might be writing to a completely different location!</p>\n<h1>Data Access Object</h1>\n<p>I'm seeing a lot of duplicate code for reading and writing to the <code>emp_data.json</code> database. You should create and use a Data Access Object to manage the your database.</p>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class EmployeeDB:\n\n def __init__(self, json_file: Path) -&gt; None:\n self._file = json_file\n\n # Create an empty database, if file doesn't exist or is empty\n if not json_file.is_file() or json_file.stat().st_size == 0:\n self.save([])\n\n def load(self) -&gt; list:\n employees = []\n with open(self._file, 'r') as f:\n data = json.load(f)\n for item in data['people']:\n ...\n return employees\n\n def save(self, employees: list) -&gt; None:\n with open(self._file, 'w') as f:\n data = {&quot;people&quot;: employees}\n json.dump(data, f, indent=4)\n\nclass StaffManager(tk.Tk):\n def __init__(self, database: EmployeeDB) -&gt; None:\n self._db = database\n ...\n ...\n...\n\nif __name__ == '__main__':\n db = EmployeeDB(Path('emp_data.json'))\n StaffManager(db).mainloop()\n</code></pre>\n<h1>Dataclass</h1>\n<p>Each employee is a dictionary.</p>\n<p>You should create an actual <code>Employee</code> <a href=\"https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#dataclasses.dataclass\" rel=\"nofollow noreferrer\">dataclass</a> to hold the information. From that, you can add additional methods, like <code>.age()</code> which could return a calculated value based on <code>.dob</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\n\n@dataclass\nclass Employee:\n name: str\n surname: str\n position: str\n dob: str\n start: str\n end: str\n retired: str\n</code></pre>\n<p>The <code>EmployeeDB</code> could now use <code>list[Employee]</code> as type-hints, instead of a bare <code>list</code>.</p>\n<hr />\n<p>There are many more changes I'd make, but this is a good start. I look forward to reviewing the next revision.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T19:49:24.970", "Id": "529548", "Score": "0", "body": "Thank you very much for your extensive answer. A lot to learn from it for me. This is what I wanted so I can improve. Thank You very much. Dead code and Class Names are already corrected." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T19:25:58.777", "Id": "268515", "ParentId": "268508", "Score": "1" } }, { "body": "<p>Not sure if I should create a new post or answer in this one. Here is a revised version of my Staff Manager APP.</p>\n<p>Improved:</p>\n<ul>\n<li>Class Names</li>\n<li>Function Names</li>\n<li>Type Hints (yes previously I thought I\nonly have to do only int, str etc.)</li>\n<li>PeP 8 (still learning and improving this one all the time)</li>\n<li>Dead Code removed</li>\n<li>Created Data Access Object (Thank you, that was a brilliant idea)</li>\n<li>Filename (specified in one place, will always have to be the same)</li>\n<li>Tried to reuse components more (view panel is being closed and created now if there are any changes to display)</li>\n</ul>\n<p>Not happened yet:</p>\n<ul>\n<li>Pathlib, yes still used os as I never used Pathlib in the past, currently learning that module as well.</li>\n<li>Dataclass, haven't done it in this version. Actually planning now to create a &quot;proper&quot; app with more functionality where I will use dataclass as it is a brilliant idea, although this app is meant to be very simple.</li>\n</ul>\n<p>Any advice, comments will be appreciated. A few small changes happened and Thanks to AJNeufeld also 290 lines of code went down to 225 lines while the program does exactly the same thing and everything is working as it is supposed. The data file is still in human-readable form (although it would be easier to store data as lists and just correctly display them in the app).</p>\n<pre><code>import json\nfrom os import path\nimport tkinter as tk\nfrom tkinter import StringVar, ttk\nimport os\nfrom tkinter.constants import CENTER, NO\nfrom ttkbootstrap import Style\n\n\nclass Window(tk.Tk):\n def __init__(self, database: object) -&gt; None:\n super().__init__()\n self._db = database\n\n self.geometry('1000x500')\n self.title('Staff Manager')\n self.iconbitmap('icon.ico')\n self.buttons()\n self.data_view()\n \n # set theme for the app (from ttkbootstrap)\n style = Style(theme='darkly')\n self = style.master\n\n\n def buttons(self) -&gt; None:\n # managing buttons, main window\n add = ttk.Button(self, text='Add', command=self.add_new_emp)\n add.place(x=10, y=10, width=75, height=40)\n\n amend = ttk.Button(self, text='Amend', command=self.amend_emp)\n amend.place(x=10, y=55, width=75, height=40)\n\n retire = ttk.Button(self, text='Retire', command=self.retire_emp)\n retire.place(x=10, y=100, width=75, height=40)\n\n remove = ttk.Button(self, text='Remove', command=self.delete_emp)\n remove.place(x=10, y=180, width=75, height=40)\n\n exit_button = ttk.Button(self, text= 'EXIT', command=self.destroy)\n exit_button.place(x=10, y=450, width=75, height=40)\n\n \n def data_view(self) -&gt; None:\n # create columns\n columns = ('#1', '#2', '#3', '#4', '#5', '#6', '#7')\n self.view_panel = ttk.Treeview(self, columns=columns, show='headings', height=27, selectmode='browse')\n self.view_panel.place(x=90, y=10, width=890, height=480)\n\n # headings\n self.view_panel.heading('#1', text='Name')\n self.view_panel.heading('#2', text='Surname')\n self.view_panel.heading('#3', text='Position')\n self.view_panel.heading('#4', text='DoB')\n self.view_panel.heading('#5', text='Start Date')\n self.view_panel.heading('#6', text='End Date')\n self.view_panel.heading('#7', text='Retired?')\n \n # set colums properties\n self.view_panel.column('#1', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#2', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#3', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#4', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#5', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#6', anchor=CENTER, stretch=NO, width=135)\n self.view_panel.column('#7', anchor=CENTER, stretch=NO, width=80)\n \n # set scrollbal for view panel\n scrollbar = ttk.Scrollbar(self, orient= tk.VERTICAL, command= self.view_panel.yview)\n self.view_panel.configure(yscrollcommand=scrollbar.set)\n scrollbar.place(x=980, y=10, width=20, height=480)\n\n for emp in EmployeeDatabase.load(self._db):\n self.view_panel.insert('', tk.END, values=emp)\n\n\n def refresh_view_panel(self) -&gt; None:\n self.view_panel.destroy()\n self.data_view()\n\n\n def add_new_emp(self) -&gt; None:\n new_emp_win = tk.Toplevel(self)\n new_emp_win.geometry('380x400')\n new_emp_win.title('Add New Employee')\n new_emp_win.iconbitmap('icon.ico')\n\n\n def check_empty_entry(data: str) -&gt; str:\n if len(data) == 0:\n return 'n/a'\n else:\n return data\n\n\n\n def accept_new_emp() -&gt; None:\n # get all the data\n name = check_empty_entry(name_ent.get())\n surname = check_empty_entry(surname_ent.get())\n position = check_empty_entry(position_ent.get())\n dob = check_empty_entry(dob_ent.get())\n start = check_empty_entry(start_ent.get())\n end = check_empty_entry(end_ent.get())\n retired = retired_var.get()\n\n new_emp = [name, surname, position, dob, start, end, retired]\n EmployeeDatabase.save(self._db, employees=new_emp)\n \n new_emp_win.destroy()\n self.refresh_view_panel()\n \n\n # set labels for Add New Emp window\n name_lbl = ttk.Label(new_emp_win, text='Name:', font=('Arial', 12))\n name_lbl.place(x=10, y=10)\n\n surname_lbl = ttk.Label(new_emp_win, text='Surname:', font=('Arial', 12))\n surname_lbl.place(x=10, y=50)\n\n position_lbl = ttk.Label(new_emp_win, text='Position:', font=('Arial', 12))\n position_lbl.place(x=10, y=90)\n\n dob_lbl = ttk.Label(new_emp_win, text='Date of Birth:', font=('Arial', 12))\n dob_lbl.place(x=10, y=130)\n\n start_lbl = ttk.Label(new_emp_win, text='Start Date:', font=('Arial', 12))\n start_lbl.place(x=10, y=170)\n\n end_lbl = ttk.Label(new_emp_win, text='End Date:', font=('Arial', 12))\n end_lbl.place(x=10, y=210)\n\n retired_lbl = ttk.Label(new_emp_win, text='Retired?', font=('Arial', 12))\n retired_lbl.place(x=10, y=250)\n\n # set entry points for data\n name_ent = ttk.Entry(new_emp_win, justify='right')\n name_ent.place(x=215, y=10)\n \n surname_ent = ttk.Entry(new_emp_win, justify='right')\n surname_ent.place(x=215, y=50)\n \n position_ent = ttk.Entry(new_emp_win, justify='right')\n position_ent.place(x=215, y=90)\n \n dob_ent = ttk.Entry(new_emp_win, justify='right')\n dob_ent.place(x=215, y=130)\n \n start_ent = ttk.Entry(new_emp_win, justify='right')\n start_ent.place(x=215, y=170)\n \n end_ent = ttk.Entry(new_emp_win, justify='right')\n end_ent.place(x=215, y=210)\n\n retired_var = StringVar(value='No')\n retired_chk = ttk.Checkbutton(\n new_emp_win,\n text='Yes',\n onvalue='Yes',\n offvalue='No',\n variable=retired_var)\n retired_chk.place(x=215, y=250)\n\n\n ok_button = ttk.Button(new_emp_win, text='ADD', command=accept_new_emp)\n ok_button.place(x=100, y=350)\n\n cancel_button = ttk.Button(new_emp_win, text='CANCEL', command=new_emp_win.destroy)\n cancel_button.place(x=200, y=350)\n\n\n def delete_emp(self) -&gt; None:\n # get &quot;clicked&quot; emp\n current_emp = self.view_panel.focus()\n emp_info = self.view_panel.item(current_emp)\n emp_details = emp_info[&quot;values&quot;]\n # need it as tuple for 'for loop' comparison\n emp_details = tuple(emp_details)\n\n # delete emp\n new_data = []\n for employee in EmployeeDatabase.load(self._db):\n if employee != emp_details:\n new_data.append(employee)\n\n EmployeeDatabase.create_new(self._db, [])\n \n for emp in new_data:\n EmployeeDatabase.save(self._db, emp)\n # update view panel\n self.refresh_view_panel()\n\n\n def change_details(self, change_detail_index: int, new_detail: str) -&gt; None:\n # get 'clicked' emp\n current_emp = self.view_panel.focus()\n emp_info = self.view_panel.item(current_emp)\n details = emp_info[&quot;values&quot;]\n # need it as tuple for 'for loop' comparison\n details_tup = tuple(details)\n\n emp_to_change = details\n\n # copy rest of emps\n new_data = []\n for employee in EmployeeDatabase.load(self._db):\n if employee != details_tup:\n new_data.append(employee)\n\n # append emp with changed detail\n details[change_detail_index] = new_detail\n new_data.append(details)\n\n EmployeeDatabase.create_new(self._db, [])\n # write to database\n for emp in new_data:\n EmployeeDatabase.save(self._db, emp)\n \n self.refresh_view_panel()\n\n\n\n def amend_emp(self) -&gt; None:\n amend_win = tk.Toplevel()\n amend_win.geometry('250x250')\n amend_win.title('Amend Employee Details')\n amend_win.iconbitmap('icon.ico')\n\n \n # check if data is not empty, if is: n/a\n def is_empty(data: str) -&gt; str:\n if len(data) == 0:\n return 'n/a'\n else:\n return data\n\n \n main_choice_lbl = ttk.Label(amend_win, text='What would you like to change?', font=('Arial', 12))\n main_choice_lbl.place(x=10, y=10)\n\n self.data_options = ('Name', 'Surname', 'Position', 'DoB', 'Start', 'End')\n self.choice = StringVar()\n options = ttk.OptionMenu(amend_win,\n self.choice,\n self.data_options[0],\n *self.data_options)\n options.place(x=10, y=47)\n options.config(width=15)\n\n new_emp_data = ttk.Label(amend_win, text='New data:', font=('Arial', 12))\n new_emp_data.place(x=10, y=90)\n\n\n main_entry = ttk.Entry(amend_win, justify='right')\n main_entry.place(x=10, y=130)\n\n\n ok_button = ttk.Button(amend_win, text='CHANGE', command=lambda: [self.change_details(self.data_options.index(self.choice.get()), is_empty(main_entry.get())), amend_win.destroy()])\n ok_button.place(x=60, y=200)\n\n cancel_button = ttk.Button(amend_win, text='CANCEL', command=amend_win.destroy)\n cancel_button.place(x=150, y=200)\n\n\n def retire_emp(self) -&gt; None:\n retired_win = tk.Toplevel()\n retired_win.geometry('280x130')\n\n ret_lbl = ttk.Label(retired_win, text=&quot;Are you sure you want to RETIRE your employee?&quot;)\n ret_lbl.place(x=10, y=20)\n \n ok_button = ttk.Button(retired_win, text='RETIRE', command=lambda: [self.change_details(6, &quot;Yes&quot;), retired_win.destroy()])\n ok_button.place(x=40, y=60)\n\n cancel_button = ttk.Button(retired_win, text='CANCEL', command=retired_win.destroy)\n cancel_button.place(x=150, y=60)\n\nclass EmployeeDatabase:\n def __init__(self, json_file: str) -&gt; None:\n self._file = json_file\n \n\n if os.path.isfile(json_file) == True and os.stat(json_file).st_size != 0:\n pass\n else:\n self.create_new([])\n\n\n def load(self) -&gt; list[str]:\n employees: list[str] = []\n with open(self._file, 'r') as f:\n data = json.load(f)\n for item in data[&quot;people&quot;]:\n name: str = item[&quot;name&quot;]\n surname: str = item[&quot;surname&quot;]\n position: str = item[&quot;position&quot;]\n dob: str = item[&quot;dob&quot;]\n start: str = item[&quot;start&quot;]\n end: str = item[&quot;end&quot;]\n retired: str = item[&quot;retired&quot;]\n \n employees.append((name, surname, position, dob, start, end, retired))\n return employees\n \n \n def create_new(self, employees: list) -&gt; None:\n with open(self._file, 'w') as f:\n data = {&quot;people&quot;: employees}\n json.dump(data, f, indent=4)\n\n\n def save(self, employees: list[str]) -&gt; None:\n new_emp = {\n &quot;name&quot;: employees[0],\n &quot;surname&quot;: employees[1],\n &quot;position&quot;: employees[2],\n &quot;dob&quot;: employees[3],\n &quot;start&quot;: employees[4],\n &quot;end&quot;: employees[5],\n &quot;retired&quot;: employees[6]\n }\n with open(self._file, 'r') as f:\n data = json.load(f)\n data[&quot;people&quot;].append(new_emp)\n with open(self._file, 'w') as f:\n json.dump(data, f, indent=4)\n\n\nif __name__ == '__main__':\n path = f'{os.path.dirname(__file__)}\\\\emp_db.json'\n db = EmployeeDatabase(path)\n Window(database= db).mainloop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T21:09:03.153", "Id": "529891", "Score": "1", "body": "In general, do not bother posting quick updates like this. Instead, wait a day or two (or seven) to get all the responses, then if you want more feedback post a new question with your updated code. (And if you want \"help\" feel free to post a link to an online repository for the code.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T21:13:44.877", "Id": "529892", "Score": "0", "body": "Thank you. Will remember for the next time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T20:58:05.493", "Id": "268665", "ParentId": "268508", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:50:13.127", "Id": "268508", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "tkinter" ], "Title": "Staff Manager Windows APP -Python" }
268508
<p>So, I've written this small calculator for computing the volumetric weight of a parcel. I've been trying to kick some bad habits to the kerb lately so I was wondering if I could get a code review. Specifically, I'm hoping you lovely people could point out/correct my pitfalls in this example.</p> <p><strong>Here's the Calculator:</strong></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>var getSpans = document.getElementsByClassName('calcValues'); // Get all Spans // console.log("Span Array:", getSpans); var getInputs = document.getElementsByClassName('calcInput'); // Get all inputs // console.log("Input Array:", getInputs); const calcDivisionVal = 6000; // Dividing Factor $(getInputs[0]).val(calcDivisionVal); // Set Dividing Factor // Set Placeholders $(getInputs[1]).attr("placeholder", "0"); $(getInputs[2]).attr("placeholder", "0"); $(getInputs[3]).attr("placeholder", "0"); $(getInputs[4]).attr("placeholder", "0"); $('input').keyup(function() { // run anytime the value changes var lengthVal = $(getInputs[1]).val(); var widthVal = $(getInputs[2]).val(); var heightVal = $(getInputs[3]).val(); var DivisionVal = $(getInputs[0]).val(); var resultVal = $(getInputs[4]).val(); var volume = lengthVal * widthVal * heightVal; var volumeWeight = volume / DivisionVal; x = volumeWeight - parseInt(volumeWeight); if (x &lt;= 0.5 &amp;&amp; 0 &lt; x &amp;&amp; calcDivisionVal == 6000) { y = 0.5; } else { y = 1; } if (x == 0) y = 0; calcedWeight = volumeWeight - x + y; if (volume != 0 &amp;&amp; (isNaN(calcedWeight) || calcedWeight &lt; 1)) calcedWeight = 1; // console.log("Answer:", calcedWeight); resultVal = $(getInputs[4]).val(parseFloat(calcedWeight)) if (volumeWeight &gt; 0) { // Set Spans to reflect inputted values var spanLengthVal = $(getSpans[0]).html($(getInputs[1]).val()); var spanWidthVal = $(getSpans[1]).html($(getInputs[2]).val()); var spanHeightVal = $(getSpans[2]).html($(getInputs[3]).val()); var spanDivisionVal = $(getSpans[3]).html($(getInputs[0]).val()); var spanResultVal = $(getSpans[4]).html($(getInputs[4]).val()); } else { // Set Spans to default values var spanLengthVal = $(getSpans[0]).html("Length"); var spanWidthVal = $(getSpans[1]).html("Width"); var spanHeightVal = $(getSpans[2]).html("Height"); var spanDivisionVal = $(getSpans[3]).html(calcDivisionVal); var spanResultVal = $(getSpans[4]).html("Volumetric Weight"); } }); $('input').keyup();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { padding: 20px; font-family: Helvetica; } .wrapper { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: 10px; } .box input[type=text] { box-sizing: border-box; display: inline-block; } .box .appended { display: inline-block; font-size: 12px; } .calcValues { font-weight: bold; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;p&gt;&lt;span class="calcValues lengthVal"&gt;Length&lt;/span&gt; x &lt;span class="calcValues widthVal"&gt;Width&lt;/span&gt; x &lt;span class="calcValues HeightVal"&gt;Height&lt;/span&gt; in centimetres / &lt;span class="calcValues divisionVal"&gt;6000&lt;/span&gt; = &lt;span class="calcValues ResultVal"&gt;Volumetric Weight&lt;/span&gt; in kilograms rounded up to the nearest 0.5kg.&lt;/p&gt; &lt;form name="vwc-form"&gt; &lt;input type="hidden" id="calcDivision" class="calcInput" name="calcDivision"&gt; &lt;div class="wrapper"&gt; &lt;div class="box calcLength"&gt; &lt;label for="calcLength"&gt;Length:&lt;/label&gt; &lt;input type="text" id="calcLength" class="calcInput" name="calcLength"&gt; &lt;span class="appended"&gt;cm&lt;/span&gt; &lt;/div&gt; &lt;div class="box calcWidth"&gt; &lt;label for="calcWidth"&gt;Width:&lt;/label&gt; &lt;input type="text" id="calcWidth" class="calcInput" name="calcWidth"&gt; &lt;span class="appended"&gt;cm&lt;/span&gt; &lt;/div&gt; &lt;div class="box calcHeight"&gt; &lt;label for="calcHeight"&gt;Height:&lt;/label&gt; &lt;input type="text" id="calcHeight" class="calcInput" name="calcHeight"&gt; &lt;span class="appended"&gt;cm&lt;/span&gt; &lt;/div&gt; &lt;div class="box calcResult"&gt; &lt;label for="calcResult"&gt;Result:&lt;/label&gt; &lt;input type="text" id="calcResult" class="calcInput" name="calcResult" disabled&gt; &lt;span class="appended"&gt;kg&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>Thanks in advance!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T16:42:55.437", "Id": "268509", "Score": "1", "Tags": [ "jquery", "html", "css" ], "Title": "Here's my attempt at a Volumetric Weight Calculator (in cm). How did I do?" }
268509
<p>This is my solution for <a href="https://leetcode.com/problems/zigzag-conversion" rel="nofollow noreferrer">ZigZag Conversion</a>, a coding challenge from LeetCode.</p> <p>The challenge:</p> <blockquote> <p>Write a program that takes two parameters, a string and a number of rows, that interprets the string as if it were displayed in a zigzag pattern and returns a line by line conversion of this interpretation in a final answer string.</p> <p>Example:</p> <p>Given the string 'PAYPALISHIRING', and 3 rows:</p> <pre class="lang-none prettyprint-override"><code>P A H N A P L S I I G Y I R </code></pre> <p>The program should output:</p> <p>&quot;PAHNAPLSIIGYIR&quot;</p> </blockquote> <p>My approach was to use a list of dictionaries, with the dictionaries as columns and their position in the list representing row positions. At the end of the control flow the list of dictionaries is unpacked and returned in the final output string.</p> <p>My solution:</p> <pre><code>class Solution(object): def convert(self, s, numRows): row = numRows if row &lt;= 1: return(s) else: a_lst = [] a_dict = {} outer_count = 0 loop_count = 0 my_count = 0 inner_count = row if row == 2: minus = 0 else: minus = 2 for i in s: loop_count+=1 if outer_count &lt; row: outer_count+=1 a_dict[outer_count] = i if outer_count == row: my_count = 0 inner_count = row dict_copy = a_dict.copy() a_lst.append(dict_copy) a_dict.clear() elif loop_count == len(s): dict_copy = a_dict.copy() a_lst.append(dict_copy) a_dict.clear() elif my_count &lt; row - minus: my_count+=1 if row == 2: inner_count = my_count else: inner_count-=1 a_dict[inner_count] = i if my_count == row - minus: outer_count = 0 dict_copy = a_dict.copy() a_lst.append(dict_copy) a_dict.clear() elif loop_count == len(s): dict_copy = a_dict.copy() a_lst.append(dict_copy) a_dict.clear() my_count = 1 my_str = '' while my_count &lt;= row: for d in a_lst: for key in d: try: my_str+=(d[my_count]) break except KeyError: break my_count+=1 return(my_str) </code></pre> <p>I would like any suggestions on improving code readability or conditional control logic. I would also like to know if I missed any edge cases. Thank you.</p>
[]
[ { "body": "<ul>\n<li><p>DRY. Every path through the loop ends up in</p>\n<pre><code> dict_copy = a_dict.copy()\n a_lst.append(dict_copy)\n a_dict.clear()\n</code></pre>\n<p>Lift it out out of the conditionals. You will also immediately see that the branches <code>oop_count == len(s)</code> become no-ops, and could be safely removed, along with now irrelevant <code>loop_count</code>. The loop now looks a bit more manageable:</p>\n<pre><code> for i in s:\n if outer_count &lt; row:\n outer_count+=1\n a_dict[outer_count] = i\n if outer_count == row:\n my_count = 0\n inner_count = row\n elif my_count &lt; row - minus:\n my_count+=1\n inner_count-=1\n a_dict[inner_count] = i\n if my_count == row - minus:\n outer_count = 0\n\n dict_copy = a_dict.copy()\n a_lst.append(dict_copy)\n a_dict.clear()\n</code></pre>\n<p>Still, it is a textbook example of spaghetti. I must admit I failed to follow the control flow.</p>\n</li>\n<li><p>Special casing of <code>row==2</code> is extremely suspicious. I don't see why it should be a special case. If it should indeed, it is a trong indication that the algorithm is flawed.</p>\n</li>\n<li><p>Speaking of the algorithm, it seems overcomplicated. As far as I can tell, the point of this exercise is to determine a pattern of indices. For example, consider a case of 5 rows. The zigzag table looks like</p>\n<pre><code> 0 8 16\n 1 7 9 15 17\n 2 6 10 14 18 ...\n 3 5 11 13 19\n 4 12 20\n</code></pre>\n<p>Take e.g. a row 1 (<code>1, 7, 9, 15, 19, ...</code>). See that the differences alternate between <code>6</code> and <code>2</code>.</p>\n<p>Prove (or at least convince yourself) that it is the case. Whatever <code>numRows</code> is, the indices' deltas in the <code>row</code> alternate between <code>(numRows - row - 1) * 2</code> and <code>row * 2</code>. Once you do it, the construction of the output string is trivial, and does not require any heavy-weight structures like dictionaries (or the list of them).</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T17:44:41.690", "Id": "529862", "Score": "0", "body": "Thanks! I should first look for a pattern, I just sort of eye-balled it and made an attack at the first idea that seemed to work. I should think these out much more. Any tips on how I could better approach such problems? Also what is DRY?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T00:06:25.077", "Id": "268555", "ParentId": "268511", "Score": "1" } } ]
{ "AcceptedAnswerId": "268555", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T17:29:24.167", "Id": "268511", "Score": "3", "Tags": [ "python", "programming-challenge", "hash-map" ], "Title": "ZigZag Conversion Coding Challenge" }
268511
<p>I'm using <a href="https://the-odds-api.com/liveapi/guides/v4/#overview" rel="noreferrer">this API</a> to get information on sports-betting odds. I am then processing it in Python to discard the irrelevant information.</p> <p>Here's what the response looks like:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;id&quot;: &quot;9eec062ad8ed334517ab3a4be8362739&quot;, &quot;sport_key&quot;: &quot;americanfootball_nfl&quot;, &quot;sport_title&quot;: &quot;NFL&quot;, &quot;commence_time&quot;: &quot;2021-10-01T00:20:00Z&quot;, &quot;home_team&quot;: &quot;Cincinnati Bengals&quot;, &quot;away_team&quot;: &quot;Jacksonville Jaguars&quot;, &quot;bookmakers&quot;: [ { &quot;key&quot;: &quot;unibet&quot;, &quot;title&quot;: &quot;Unibet&quot;, &quot;last_update&quot;: &quot;2021-09-29T16:41:30Z&quot;, &quot;markets&quot;: [ { &quot;key&quot;: &quot;spreads&quot;, &quot;outcomes&quot;: [ { &quot;name&quot;: &quot;Cincinnati Bengals&quot;, &quot;price&quot;: -110, &quot;point&quot;: -7.5 }, { &quot;name&quot;: &quot;Jacksonville Jaguars&quot;, &quot;price&quot;: -110, &quot;point&quot;: 7.5 } ] }, { &quot;key&quot;: &quot;totals&quot;, &quot;outcomes&quot;: [ { &quot;name&quot;: &quot;Over&quot;, &quot;price&quot;: -111, &quot;point&quot;: 46.0 }, { &quot;name&quot;: &quot;Under&quot;, &quot;price&quot;: -109, &quot;point&quot;: 46.0 } ] } ] }, ... </code></pre> <p>My code:</p> <pre class="lang-py prettyprint-override"><code># filter http response odds = [] for game in resp: for bookmaker in game[&quot;bookmakers&quot;]: if bookmaker[&quot;key&quot;] == &quot;betmgm&quot;: for bet in bookmaker[&quot;markets&quot;]: if bet[&quot;outcomes&quot;][0][&quot;name&quot;] == &quot;Over&quot;: over_under_line = bet[&quot;outcomes&quot;][0][&quot;point&quot;] elif bet[&quot;outcomes&quot;][0][&quot;name&quot;] == game[&quot;home_team&quot;]: spread = bet[&quot;outcomes&quot;][0][&quot;point&quot;] odds.append( { &quot;home_team&quot;: game[&quot;home_team&quot;], &quot;away_team&quot;: game[&quot;away_team&quot;], &quot;spread&quot;: spread, &quot;total&quot;: over_under_line, } ) </code></pre> <p>I have a strong feeling that this could be made more pythonic. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T23:07:23.200", "Id": "529557", "Score": "0", "body": "I notice that the values for `spread` and `over_under_line` are not set in many of your code paths. That means you will get lots of garbage in your `odds`." } ]
[ { "body": "<p>I don't think you win something by avoiding loops in that case...</p>\n<p>Personally, I probably would just introduce a <code>namedtuple</code>, extract the processing of each <code>game</code> record to a function and use <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>get(key)</code> to access a value within a <code>dict</code></a> to avoid <code>KeyError</code>s.</p>\n<p>If you want it to be more pythonic, maybe you could consider using list comprehensions. I don't think it's more efficient but more readable. See Example 2.</p>\n<p>(Example 1 does not follow EAFP (easier to ask for forgiveness than permission) and therefore not pythonic in that regard. However, when working with data from an API, I prefer to ask for permission instead of forgiveness.)</p>\n<p>Note: I assume that <code>[0]</code> in <code>bet[&quot;outcomes&quot;][0][&quot;name&quot;]</code> (in your question's code snippet) is purposely and therefore only the first outcome has to be considered.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\n\nBet = namedtuple(&quot;Bet&quot;, [&quot;home_team&quot;, &quot;away_team&quot;, &quot;spread&quot;, &quot;total&quot;])\n\ndef get_odds(game):\n \n home_team = game.get(&quot;home_team&quot;)\n away_team = game.get(&quot;away_team&quot;)\n spread = None\n over_under_line = None\n \n for bookmaker in game.get(&quot;bookmakers&quot;):\n if bookmaker.get(&quot;key&quot;) == &quot;betmgm&quot;:\n for bet in bookmaker.get(&quot;markets&quot;):\n \n outcome = bet.get(&quot;outcomes&quot;)\n if not outcome:\n continue # or raise an exception\n \n name = outcome[0].get(&quot;name&quot;)\n point = outcome[0].get(&quot;point&quot;)\n \n if name == &quot;Over&quot;:\n over_under_line = point\n elif name == home_team:\n spread = point\n \n return Bet(home_team, away_team, spread, over_under_line)\n\nodds = (get_odds(game) for game in data) # generator comprehension\n\nfor record in odds:\n print(record)\n</code></pre>\n<hr />\n<p><strong>Using List Comprehensions</strong></p>\n<p>In case you rather want to use list comprehensions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\n\nBet = namedtuple(&quot;Bet&quot;, [&quot;home_team&quot;, &quot;away_team&quot;, &quot;spread&quot;, &quot;total&quot;])\n\ndef get_odds(game):\n \n home_team = game.get(&quot;home_team&quot;)\n away_team = game.get(&quot;away_team&quot;)\n spread = None\n over_under_line = None\n \n bets = [ \n bookmaker.get(&quot;markets&quot;) for bookmaker in game.get(&quot;bookmakers&quot;)\n if bookmaker.get(&quot;key&quot;) == &quot;betmgm&quot;\n ]\n outcomes = [ # possible KeyError\n bet.get(&quot;outcomes&quot;)[0] for bet_list in bets for bet in bet_list\n ]\n \n for outcome in outcomes:\n\n name = outcome.get(&quot;name&quot;)\n point = outcome.get(&quot;point&quot;)\n\n if name == &quot;Over&quot;:\n over_under_line = point\n elif name == home_team:\n spread = point\n \n return Bet(home_team, away_team, spread, over_under_line)\n\nodds = (get_odds(game) for game in data) # generator comprehension\n\nfor record in odds:\n print(record)\n\n</code></pre>\n<hr />\n<p><strong>Using <a href=\"https://github.com/jmespath/jmespath.py\" rel=\"nofollow noreferrer\"><code>JMESPath</code></a></strong></p>\n<p>I wouldn't call it more pythonic though. It's just another way to extract the data from the JSON string. Note: There are also alternatives to <code>JMESPath</code>: <a href=\"https://github.com/zhangxianbing/jsonpath-python\" rel=\"nofollow noreferrer\"><code>jsonpath-python</code></a> and others.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\nimport jmespath\n\nBet = namedtuple(&quot;Bet&quot;, [&quot;home_team&quot;, &quot;away_team&quot;, &quot;spread&quot;, &quot;total&quot;])\n\ndef get_odds(game):\n \n home_team = game.get(&quot;home_team&quot;)\n away_team = game.get(&quot;away_team&quot;)\n \n search_outcomes = &quot;bookmakers[?key=='betmgm'].markets[*].outcomes[0] | [0]&quot;\n outcomes = {\n &quot;outcomes&quot;: jmespath.search(search_outcomes, game)\n }\n \n over_under_line = jmespath.search(&quot;outcomes[?name=='Over'].point | [0]&quot;, outcomes)\n spread = jmespath.search(f&quot;outcomes[?name=='{home_team}'].point | [0]&quot;, outcomes)\n \n return Bet(home_team, away_team, spread, over_under_line)\n\nodds = (get_odds(game) for game in data) # generator comprehension\n\nfor record in odds:\n print(record)\n</code></pre>\n<hr />\n<p>Note: your code example and all my example have <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">magic numbers</a> which is an anti-pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:08:54.620", "Id": "268519", "ParentId": "268512", "Score": "5" } }, { "body": "<p>If this were for a job, I'd say you need to potentially translate the JSON soup into well-typed, well-defined models, but it's probably not. In that case, you should still break your logic up into functions with type hints.</p>\n<p>Note that there's an opportunity for early-break since you probably only care about the first entries found for your over/under and spread values. The reusable way to represent this is a generator where only the first value is used, via <code>next</code>.</p>\n<p>Try to factor out values like <code>betmgm</code> into parameters. It's also worth noting that your sample data are not a great representation of what your code is actually looking for, since you hard-code <code>betmgm</code> when only <code>unibet</code> is shown.</p>\n<p>Your code is slightly fragile since it ignores <code>bet['key']</code> when it should pay attention to that to filter for over/under and spread respectively.</p>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Dict, Any, Iterable, Tuple, Iterator\n\nJsonDict = Dict[str, Any]\n\n\ndef get_over_under(markets: Iterable[JsonDict]) -&gt; Iterator[float]:\n for bet in markets:\n if bet['key'] == 'totals':\n for outcome in bet['outcomes']:\n if outcome['name'] == 'Over':\n yield outcome['point']\n\n\ndef get_spread(markets: Iterable[JsonDict], home_team: str) -&gt; Iterator[float]:\n for bet in markets:\n if bet['key'] == 'spreads':\n for outcome in bet['outcomes']:\n if outcome['name'] == home_team:\n yield outcome['point']\n\n\ndef get_bets(resp: Iterable[JsonDict], book_name: str) -&gt; Iterator[Tuple[\n float, # over/under\n float, # spread\n]]:\n for game in resp:\n for bookmaker in game['bookmakers']:\n if bookmaker['key'] == book_name:\n markets = bookmaker['markets']\n yield (\n next(get_over_under(markets)),\n next(get_spread(markets, home_team=game['home_team'])),\n )\n\n\ndef test() -&gt; None:\n resp = [\n {\n 'id': '9eec062ad8ed334517ab3a4be8362739',\n 'sport_key': 'americanfootball_nfl',\n 'sport_title': 'NFL',\n 'commence_time': '2021-10-01T00:20:00Z',\n 'home_team': 'Cincinnati Bengals',\n 'away_team': 'Jacksonville Jaguars',\n 'bookmakers': [\n {\n 'key': 'unibet',\n 'title': 'Unibet',\n 'last_update': '2021-09-29T16:41:30Z',\n 'markets': [\n {\n 'key': 'spreads',\n 'outcomes': [\n {\n 'name': 'Cincinnati Bengals',\n 'price': -110,\n 'point': -7.5\n },\n {\n 'name': 'Jacksonville Jaguars',\n 'price': -110,\n 'point': 7.5\n },\n ],\n },\n {\n 'key': 'totals',\n 'outcomes': [\n {\n 'name': 'Over',\n 'price': -111,\n 'point': 46.0\n },\n {\n 'name': 'Under',\n 'price': -109,\n 'point': 46.0\n },\n ],\n },\n ],\n },\n ],\n },\n ]\n\n for over_under, spread in get_bets(\n resp,\n book_name='unibet' # 'betmgm'\n ):\n print(f'Over/under: {over_under} Spread: {spread}')\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T02:08:00.533", "Id": "268527", "ParentId": "268512", "Score": "6" } } ]
{ "AcceptedAnswerId": "268527", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T18:25:53.537", "Id": "268512", "Score": "8", "Tags": [ "python", "json", "api" ], "Title": "Efficiently parsing JSON response data in python" }
268512
<p>I built a class in C#, <code>DiscountManager</code>, which is responsible for calculating a customer discount based on years of loyalty. I want to refactor it and am seeking any suggestions for conciseness and efficiency.</p> <pre><code>public class DiscountManager { public decimal Calculate(decimal amount, int type, int years) { decimal result = 0; decimal disc = (years &gt; 5) ? (decimal)5/100 : (decimal)years/100; if (type == 1) { result = amount; } else if (type == 2) { result = (amount - (0.1m * amount)) - disc * (amount - (0.1m * amount)); } else if (type == 3) { result = (0.7m * amount) - disc * (0.7m * amount); } else if (type == 4) { result = (amount - (0.5m * amount)) - disc * (amount - (0.5m * amount)); } return result; } } </code></pre>
[]
[ { "body": "<p>Try to keep your calculations consistent.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>price * 0.9m\n</code></pre>\n<p>Is the same as</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>(price - (0.1m * price))\n</code></pre>\n<p>Based on this you could have simplified it to the following:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeOfHavingAccountInYears)\n{\n bool registered;\n decimal baseFactor;\n switch (accountStatus)\n {\n case AccountStatus.NotRegistered:\n registered = false;\n baseFactor = 1.0m;\n break;\n case AccountStatus.SimpleCustomer:\n registered = true;\n baseFactor = 0.9m;\n break;\n case AccountStatus.ValuableCustomer:\n registered = true;\n baseFactor = 0.7m;\n break;\n case AccountStatus.MostValuableCustomer:\n registered = true;\n baseFactor = 0.5m;\n break;\n default:\n throw new Exception(&quot;Invalid status: &quot; + accountStatus);\n }\n\n // apply base discount\n price *= baseFactor;\n\n // apply loyalty discount\n if (registered == true)\n {\n int years = Math.Min(5, timeOfHavingAccountInYears);\n decimal loyaltyFactor = 1.0m - (decimal)years / 100m;\n price *= loyaltyFactor;\n }\n\n return price;\n}\n</code></pre>\n<p>You can also use a <code>Dictionary</code> like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class StatusValues\n{\n public bool registered;\n public decimal baseFactor;\n}\n\npublic class DiscountManager\n{\n public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeOfHavingAccountInYears)\n {\n var statusTypes = new Dictionary&lt;AccountStatus, StatusValues&gt;()\n {\n { AccountStatus.NotRegistered, new StatusValues{ registered = false, baseFactor = 1.0m } },\n { AccountStatus.SimpleCustomer, new StatusValues{ registered = true, baseFactor = 0.9m } },\n { AccountStatus.ValuableCustomer, new StatusValues{ registered = true, baseFactor = 0.7m } }, \n { AccountStatus.MostValuableCustomer, new StatusValues { registered = true, baseFactor = 0.5m } }\n };\n var statusType = statusTypes[accountStatus];\n // apply base discount\n price *= statusType.baseFactor;\n // apply loyalty discount\n if (statusType.registered)\n {\n int years = Math.Min(5, timeOfHavingAccountInYears);\n decimal loyaltyFactor = 1.0m - (decimal)years / 100m;\n price *= loyaltyFactor;\n }\n return price;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T21:59:09.193", "Id": "529553", "Score": "1", "body": "Consider using extension methods to enhance the `AccountStatus` providing the required values such as `registered`. Also consider extracting the calculation of the loyalty factor to a separate method with `timeOfHaving...` as a parameter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T19:45:49.173", "Id": "268517", "ParentId": "268513", "Score": "4" } }, { "body": "<p>I would recommend to move <code>discountForLoyaltyInPercentage</code> and <code>switch</code> statement into their own methods.</p>\n<p>The issue with the current method is that it has multiple purposes :</p>\n<ol>\n<li>Calculating and setting the Loyalty Discount Percentage.</li>\n<li>Calculating and setting the General Discount Percentage.</li>\n<li>Applying All discounts to the price, and return the result.</li>\n</ol>\n<p>If you move each point above to one method, it would be easier to read, extend, and to have a proper handling.</p>\n<pre><code>public static class DiscountManager\n{\n /// &lt;summary&gt;\n /// Calculates and returns the discount percentage \n /// based on the time period of the account (number of years since created).\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;timeOfHavingAccountInYears&quot;&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static decimal GetLoyaltyDiscountPercentage(int timeOfHavingAccountInYears)\n {\n return timeOfHavingAccountInYears &gt; 5 ? 0.50m : timeOfHavingAccountInYears / 100.00m;\n }\n\n /// &lt;summary&gt;\n /// Calculates and returns the general discount \n /// based on the &lt;see cref=&quot;AccountStatus&quot;/&gt; \n /// &lt;/summary&gt;\n /// &lt;param name=&quot;accountStatus&quot;&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static decimal GetDiscountPercentage(AccountStatus accountStatus)\n {\n switch(accountStatus)\n {\n case AccountStatus.SimpleCustomer:\n return 0.10m;\n case AccountStatus.ValuableCustomer:\n return 0.30m;\n case AccountStatus.MostValuableCustomer:\n return 0.50m;\n default:\n return 0.00m;\n }\n }\n\n /// &lt;summary&gt;\n /// Applying the discounts (if any) on the price and returns the final price (after discounts).\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;price&quot;&gt;&lt;/param&gt;\n /// &lt;param name=&quot;accountStatus&quot;&gt;&lt;/param&gt;\n /// &lt;param name=&quot;timeOfHavingAccountInYears&quot;&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static decimal ApplyDiscount(decimal price , AccountStatus accountStatus , int timeOfHavingAccountInYears)\n {\n decimal loyaltyDiscountPercentage = GetLoyaltyDiscountPercentage(timeOfHavingAccountInYears);\n\n decimal discountPercentage = GetDiscountPercentage(accountStatus);\n\n decimal priceAfterDiscount = price * (1.00m - discountPercentage);\n \n decimal finalPrice = priceAfterDiscount - ( loyaltyDiscountPercentage * priceAfterDiscount );\n \n return finalPrice;\n } \n}\n</code></pre>\n<p>since all methods don't need several instance, and the nature of the class is unchangeable, making the class <code>static</code> would be more appropriate.</p>\n<p>You can then reuse it :</p>\n<pre><code>var finalPrice = DiscountManager.ApplyDiscount(price, accountStatus, timeOfHavingAccountInYears);\n</code></pre>\n<p>Now, this would be fine for small discount system, but with larger scale discount system, you may need to use abstractions to make each discount with its own properties. (so you can manage discounts on accounts, products, season discounts .. etc).</p>\n<p>Something like this :</p>\n<pre><code>public abstract class AccountDiscount\n{\n public abstract decimal Discount { get; }\n \n public virtual decimal GetDiscountedPrice(decimal price)\n {\n return price * (1.00m - Discount);\n }\n\n}\n\npublic class DefaultDiscount : AccountDiscount\n{\n public override decimal Discount =&gt; 0.00m;\n}\n\n\npublic class SimpleCustomerDiscount : AccountDiscount\n{\n public override decimal Discount =&gt; 0.10m;\n}\n\npublic class LoyaltyDiscount : AccountDiscount\n{\n public override decimal Discount { get; }\n\n public LoyaltyDiscount(int totalYears) : base()\n {\n Discount = totalYears &gt; 5 ? 0.50m : totalYears / 100.00m;\n }\n}\n</code></pre>\n<p>then you can add each discount to an account and store that in the database level, which will help you achieve this :</p>\n<pre><code>public decimal ApplyDiscounts(IEnumerable&lt;AccountDiscount&gt; discounts, decimal price)\n{\n decimal finalPrice = price;\n \n foreach(var discount in discounts)\n {\n finalPrice -= discount.GetDiscountedPrice(finalPrice);\n }\n \n return finalPrice;\n}\n\npublic decimal ApplyDiscountsByAccountId(int accountId, decimal price)\n{\n List&lt;AccountDiscount&gt; discounts = _someRepoistory.GetAccountDiscounts(accountId);\n \n return ApplyDiscounts(discounts, price); \n}\n</code></pre>\n<p>as here the <code>discounts</code> would be already linked to an account, and you only need to handle the logic between them, so you can pass an <code>accountId</code> and the system will populate the account profile along with its registered discounts. This is just an example on how it can be implemented on a larger scale.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T11:47:08.813", "Id": "529580", "Score": "0", "body": "I like the way you split it into functions, but be mindful to not confuse percentages and factors. In `GetDiscountPercentage` it looks like `SimpleCustomer` will get a 90% discount." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T12:16:00.917", "Id": "529581", "Score": "0", "body": "@JohanduToit my apology on my humble understanding on math, I did it because I was wondering why the `ValuableCustomer` has a higher discount than `MostValuableCustomer` ? so I figured, they must use `price * (100 - (actual discount * 100) / 100)`, so doing `price * .9` or `price * 0.7` would return the price after the discount." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T12:48:43.397", "Id": "529583", "Score": "0", "body": "No need for apologies =) You could change it to something like this [TIO](https://tio.run/##jZExa8NADIX3@xUa7YKDQ@kS0yGk0KkQCGRXZbk5uPOZk64ZSn67Yzc4JClt@jbpPX3DE0nhQxsK2bFzfd9F@4nKIIpqCWom69HBK@uLFQqp1TVH4lbxg7MlfW82QzYJ4OWUmy8Dg2RvlXbZjTc6J38UoTBcsWYb6zvHqyQaPMfFOToqsqbYQjmbl776C7JFl/D9LubxDuYtiP4T9XSJqrnB5PSXaDlFD@ZgzNTzUD/xslGOU93wfFrCA2Tz8QoKqH@8Iq/6/gg)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:02:30.883", "Id": "529584", "Score": "0", "body": "@JohanduToit isn't `price * (1.00m - discountPercentage)` is the same as `price * 0.9` ? could you please enlighten me with the differences ? because both approaches will return the same results ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:16:27.690", "Id": "529585", "Score": "0", "body": "You are correct, but if you look at `GetDiscountPercentage` on its own, it makes more sense to return actual percentages rather than factors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:29:35.990", "Id": "529586", "Score": "0", "body": "@JohanduToit i've got your point, and you're correct, looking at it, it seems it would be better if returns the percentage. thanks man for your eagle eye ;)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:36:50.660", "Id": "529587", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/130129/discussion-between-johan-du-toit-and-isr5)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T01:56:41.733", "Id": "268526", "ParentId": "268513", "Score": "4" } } ]
{ "AcceptedAnswerId": "268526", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T18:32:29.997", "Id": "268513", "Score": "-1", "Tags": [ "c#", "formatting" ], "Title": "DiscountManager class in C#" }
268513
<p>I have a simple program that matches words with descriptions. The program should do the following.</p> <ol> <li>Allow a user to enter a set of inputs: keys and descriptions.</li> <li>When the user clicks generate html a textarea should be created with html to be rendered in the word matching exercise.</li> <li>When the user clicks show answer the program should show the keys with the corresponding descriptions.</li> <li>When the user clicks add more new inputboxes are generated. After this state change when the user clicks generate html the new input boxes should be used to update the html shown in the text box.</li> <li>When the user clicks render html the html from the textarea should be rendered below the textarea.</li> <li>When the user clicks reset the textarea, controls, and rendered html should be removed. The program should return to the original state.</li> <li>When the html from the text is rendered the descriptions should be randomized.</li> </ol> <p>This is the html</p> <pre><code>&lt;div id=&quot;maincontentstyle&quot;&gt; &lt;div id=&quot;boxstyle&quot;&gt; &lt;h3 id= &quot;title&quot;&gt;Section 5.2 Word Matching Exercise&lt;/h3&gt; &lt;div class=&quot;row&quot;&gt; &lt;div id=&quot;inputs&quot; class=&quot;column column-1&quot;&gt; &lt;div id=&quot;inputBoxes&quot; class=&quot;inputBoxes&quot;&gt; &lt;title&gt;Input:&lt;/title&gt; &lt;div class=&quot;row&quot;&gt; Title: &lt;input id= &quot;title_input&quot; type=&quot;text&quot;&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; Key Term 1: &lt;input id=&quot;el1&quot; type=&quot;text&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; Description 1: &lt;input id=&quot;dl1&quot; type=&quot;text&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; Key Term 2: &lt;input id=&quot;el2&quot; type=&quot;text&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; Description 2: &lt;input id=&quot;dl2&quot; type=&quot;text&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;span style=&quot;padding: 3px&quot;&gt; &lt;button id =&quot;one&quot; class=&quot;button&quot; type=&quot;button&quot; onClick=&quot;add_more()&quot;&gt;add more&lt;/button&gt; &lt;/span&gt; &lt;span style=&quot;padding: 3px&quot;&gt; &lt;button id =&quot;one&quot; class=&quot;button&quot; type=&quot;button&quot; onClick=&quot;generate_html()&quot;&gt;generate html&lt;/button&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;results&quot; class=&quot;row&quot;&gt; &lt;/div&gt; &lt;div id=&quot;renderedHTML&quot; class=&quot;row&quot;&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is the javascript:</p> <pre><code> &lt;script&gt; // initially html is not generated. var htmlGenerated = false; // number of inputs start out as 2. var numberOfInputs = 2; // initially no addtional inputs have been added. var addMore = false; // initially html is not rendered var htmlRendered = false; // initialize the answer. var answer = ''; function shuffle(a){ for(let j,i=a.length;i&gt;1;){ j=Math.floor(Math.random()*i--); if (i!=j) [a[i],a[j]]=[a[j],a[i]] } return a } function reset() { // reset the htmGenerated to false. htmlGenerated = false; htmlRendered = false; numberOfInputs = 2; var someVarName = true; sessionStorage.setItem(&quot;someVarKey1&quot;, someVarName); window.location.reload(); } function show_answer() { // retrieve the keys and descriptions. Then load them into their respective arrays. const e_inputs = document.querySelectorAll(&quot;[id^='el']&quot;); const d_inputs = document.querySelectorAll(&quot;[id^='dl']&quot;); let elArray = []; let dlArray = []; const title = document.getElementById('title_input').value; e_inputs.forEach( i =&gt; { if(i.value) elArray.push(i.value) }); d_inputs.forEach( i =&gt; { if(i.value) dlArray.push(i.value) }); //reset the answer once the generate_html() is called. answer = ''; for (let i = 0; i &lt; elArray.length; i++) { answer += `${elArray[i]}`; answer += ':'; answer += `${dlArray[i]}`; answer += '\n'; } jAlert(answer, 'Correct Match'); } function generate_html() { // retrieve the keys and descriptions. Then load them into their respective arrays. const e_inputs = document.querySelectorAll(&quot;[id^='el']&quot;); const d_inputs = document.querySelectorAll(&quot;[id^='dl']&quot;); let elArray = []; let dlArray = []; const title = document.getElementById('title_input').value; e_inputs.forEach( i =&gt; { if(i.value) elArray.push(i.value) }); d_inputs.forEach( i =&gt; { if(i.value) dlArray.push(i.value) }); console.log(&quot;generating answer&quot;); console.log(answer); //If we added more if(addMore){ // then delete the old textarea. if(document.getElementById(&quot;generated_html_textarea&quot;)){ textarea = document.getElementById(&quot;generated_html_textarea&quot;); textarea.remove(); } if(document.getElementById(&quot;program1&quot;)){ // delete the controls. controls = document.getElementById(&quot;program1&quot;); controls.remove(); } } //if the html isn't generated or if we added more then create it. if(!htmlGenerated || addMore){ //fetch the results box results = document.getElementById(&quot;results&quot;); //create textarea textarea = document.createElement(&quot;textarea&quot;); textarea.setAttribute(&quot;id&quot;,&quot;generated_html_textarea&quot;); // initialize blank html let html = ''; html += '&lt;div id=\&quot;maincontentstyle\&quot;&gt;\n' html += '\t&lt;center&gt;\n' html += '\t\t&lt;div id=\&quot;boxstyle\&quot;&gt;\n' html += '\t\t\t&lt;h3 id=\&quot;h3style\&quot;&gt;'+title+&quot;&lt;/h3&gt;\n&quot;; //create key inputs html += '\t\t\t\t&lt;center&gt;\n' html += '\t\t\t\t\t&lt;div class=&quot;source&quot;&gt;\n' for (let i = numberOfInputs; i &lt; elArray.length+numberOfInputs; i++){ html += '\t\t\t\t\t\t&lt;div id=&quot;s'; id = (1+i-numberOfInputs); html += id; html +='\&quot; class=\&quot;draggyBox-small\&quot;&gt;\n'; html += `\t\t\t\t\t\t\t${elArray[i-numberOfInputs]}\n`; html +='\t\t\t\t\t\t&lt;/div&gt;\n'; } html += '\t\t\t\t\t&lt;/div&gt;\n' html += '\t\t\t\t\t&lt;/center&gt;\n' //create description inputs html += '\t\t\t\t\t&lt;table id=\&quot;tablestyle\&quot;&gt;\n' for (let i = numberOfInputs; i &lt; dlArray.length+numberOfInputs; i++){ html +='\t\t\t\t\t\t&lt;tr&gt;\n' html += '\t\t\t\t\t\t&lt;td id=&quot;row'; id = (1+i-numberOfInputs); html += id; html +='&quot;&gt;\n'; html += '\t\t\t\t\t\t\t&lt;div id=\&quot;t'; html += id; html +='&quot; class=\&quot;ltarget\&quot;&gt;' html +='&lt;/div&gt;\n' html +='\t\t\t\t\t\t&lt;/td &gt;\n' html +='\t\t\t\t\t\t&lt;td id=\&quot;d' html += id html += '\&quot;&gt;\n' html +=`\t\t\t\t\t\t\t${dlArray[i-numberOfInputs]}\n`; html +='\t\t\t\t\t\t\t&lt;/td &gt;\n' html +='\t\t\t\t\t\t&lt;/tr&gt;\n'; } html += '\t\t\t\t\t&lt;/table&gt;\n'; html += '\t\t\t\t&lt;/center&gt;\n' html += '\t\t&lt;/div&gt;\n' html += '\t&lt;/center&gt;\n' html += '&lt;/div&gt;' // html generation is done. htmlGenerated = true; textarea.value = html; results.appendChild(textarea); if(addMore) addMore = false; // Generate reset, show answer, , and render html buttons controls = document.createElement(&quot;div&quot;); controls.setAttribute(&quot;id&quot;,&quot;program1&quot;); controls.setAttribute(&quot;style&quot;,&quot;border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;&quot;); controls.innerHTML += '&lt;span style=&quot;padding: 3px&quot;&gt; &lt;button id =&quot;one&quot; class=&quot;button&quot; type=&quot;button&quot; onClick=&quot;show_answer()&quot;&gt;Show Answer&lt;/button&gt; &lt;button id = &quot;resetButton&quot; class=&quot;button&quot; type=&quot;button&quot; onClick=&quot;reset()&quot;&gt;Reset&lt;/button&gt;&lt;button id = &quot;renderHTMLButton&quot; class=&quot;button&quot; type=&quot;button&quot; onClick=&quot;render_html()&quot;&gt;Render html&lt;/button&gt; &lt;span id = &quot;audio&quot; style=&quot;&quot;&gt; &lt;a href=&quot;&quot; title=&quot;Turns Text-to-Speech Output On or Off&quot; class=&quot;menulink&quot; style=&quot;text-decoration: none;&quot;&gt;&lt;img id=&quot;bg&quot; src=&quot;audioOff.png&quot; height=&quot;30&quot; width=&quot;30&quot; style=&quot;margin-bottom:-10px; padding-bottom:-20px;&quot;/&gt; &lt;/a&gt; &lt;/span&gt; &lt;/span&gt;'; results.appendChild(controls); } } function add_more() { // we've added more inputs. addMore = true; // increment the number of inputs. numberOfInputs++; //fetch the input boxes. inputs = document.getElementById(&quot;inputBoxes&quot;); //create a new row for a key term. row = document.createElement(&quot;div&quot;); row.setAttribute(&quot;class&quot;,&quot;row&quot;); // set the key term text. row.innerHTML = &quot;Key Term &quot;; row.innerHTML +=numberOfInputs; row.innerHTML +=&quot; :&quot;; // create the input for the key. key = document.createElement(&quot;input&quot;); key.setAttribute(&quot;id&quot;,&quot;el&quot;+numberOfInputs); //add the key to the row. row.appendChild(key); //create a row for the new description. row2 = document.createElement(&quot;div&quot;); row2.setAttribute(&quot;class&quot;,&quot;row&quot;); // set the description text. row2.innerHTML = &quot;Description &quot; row2.innerHTML+=numberOfInputs; row2.innerHTML+=&quot; :&quot;; // create the description input description = document.createElement(&quot;input&quot;); description.setAttribute(&quot;id&quot;,&quot;dl&quot;+numberOfInputs); // add the description to the row. row2.appendChild(description); // add the rows for the key and the description to the inputBoxes. inputs.appendChild(row); inputs.appendChild(row2); } function render_html(){ // was html rendered? if(!htmlRendered){ textarea = document.getElementById(&quot;generated_html_textarea&quot;); generated_html = textarea.value; console.log(generated_html); maincontentstyle = document.getElementById(&quot;maincontentstyle&quot;); rendered_html = document.createElement(&quot;div&quot;); rendered_html.setAttribute(&quot;id&quot;,&quot;rendered_html&quot;); rendered_html.setAttribute(&quot;style&quot;,&quot;border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;&quot;); rendered_html.innerHTML += generated_html; maincontentstyle.appendChild(rendered_html); htmlRendered = true; } } &lt;/script&gt; </code></pre> <p>I've created four functions reset(), show_answer(), generate_html(), and add_more(). This works, but it could be optimized.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T19:46:35.703", "Id": "268518", "Score": "2", "Tags": [ "javascript", "html" ], "Title": "Word Matching Exercise Game" }
268518
<p>I inserted this code snippet in the functions.php of my child theme, to create the woocommerce single product page in the hook woocommerce_after_single_variation of the custom icons in line centered on the text, without using css, everything works, but I ask you much more experienced if that's okay, or could you do better? thank you so much ( sorry my poor english, i use translate :)</p> <pre><code>/** * added 3 icons in line to the single product page */ add_action( 'woocommerce_after_single_variation', 'icone_rassicurazione_cliente'); function icone_rassicurazione_cliente() { echo '&lt;i class=&quot;fas fa-undo&quot; style=&quot;font-size:40px; text-align:center; border-radius:20px margin-left: 0 auto; margin-right: 5%;&quot;&gt; &lt;p style=&quot;text-align: center;&quot;&gt; &lt;h6&gt;reso gratuito&lt;br&gt;antro 90 gg&lt;/h6&gt;&lt;/i&gt;' ; echo '&lt;i class=&quot;fas fa-phone-volume&quot; style=&quot;font-size:40px; text-align:center; border-radius:20px margin-left: 5%; margin-right:5%;&quot;&gt; &lt;p style=&quot;text-align: center;&quot;&gt; &lt;h6&gt;assistenza anche&lt;br&gt;tramite whatsapp&lt;/h6&gt;&lt;/i&gt;' ; echo '&lt;i class=&quot;fab fa-cc-paypal&quot; style=&quot;font-size:40px; text-align:center; border-radius:20px margin-left: 5%; margin-right: 0 auto;&quot;&gt; &lt;p style=&quot;text-align: center;&quot;&gt; &lt;h6&gt;pagameni certificati&lt;br&gt;Paypal, carta di&lt;/h6&gt;&lt;/i&gt;' ; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:38:44.087", "Id": "268520", "Score": "2", "Tags": [ "wordpress" ], "Title": "Added custom woocommerce product page hook" }
268520
<p>Saw <a href="https://codereview.stackexchange.com/q/268436/507">this question</a> and though I wanted to try.</p> <p>So my version of reading Mine Sweeper: For the <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;page=show_problem&amp;category=0&amp;problem=1130&amp;mosmsg=Submission+received+with+ID+26820726" rel="noreferrer">Online Judge</a></p> <h2>Some Utilities Classes</h2> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; #include &lt;vector&gt; // Each member of the grid is either a mine // which is printed as a '*' or empty which is represented by a number. struct MineCount { bool mine; int count; }; // We need to save the size of the grid. using Size = std::pair&lt;int, int&gt;; </code></pre> <h2>The MineField class</h2> <pre><code>// MineField // Knows about mines and counts only. // // The maximum size of the field is [100 * 100] // But to maximize speed we use contiguous piece of memory // rather than an array of arrays. This reduces the cost // of memory access as we only have to do one accesses to get // the required location. // // To simplify the code we add a border of cells around the // minefield. So all accesses to the grid is increment by 1 // in both X and Y dimensions. This allows us to increment // the count in all adjoining fields without having to check if // we are on the border of the field and thus incrementing // beyond the edge of the array // // This should make the code faster and simpler to read. class MineField { Size size; std::vector&lt;MineCount&gt; mines; static constexpr int maxSize = 103; int index(int x, int y) {return x + (y * maxSize);} public: MineField() : size{0, 0} , mines(maxSize * maxSize) {} // Re-Use a minefield. // Reset only the state needed (previously used). // without having to reallocate the array. void reset(int n, int m) { for(int xLoop = 0; xLoop &lt; size.first; ++xLoop) { for(int yLoop = 0; yLoop &lt; size.second; ++ yLoop) { mines[index(xLoop, yLoop)] = {false, 0}; } } // Store Size +2 as we have an extra border around // the field. size.first = n + 2; size.second = m + 2; } // Add a mine to location X, Y void add(int x, int y) { ++x; ++y; // We have a mine in this square. mines[index(x, y)].mine = true; // Increment the count of all surrounding squares. // I was tempted to manually onroll this loop. for(int xLoop = -1; xLoop &lt; 2; ++xLoop) { for(int yLoop = -1; yLoop &lt; 2; ++yLoop) { ++mines[index(x + xLoop, y + yLoop)].count; } } } // Get the character for a specific location. char get(int x, int y) const { ++x; ++y; if (mines[index(x, y)].mine) { return '*'; } return '0' + mines[index(x, y)].count; } }; </code></pre> <h2>The Field class</h2> <pre><code>// Wrapper class that understands about reading and writing // to a stream for a minefield. // This class does not know about the extra border on the field. class Field { Size size; MineField mineField; public: void reset(int n, int m); // Functionality to read and write. :-) void read(std::istream&amp; stream); void write(std::ostream&amp; stream) const; // Standard friend functions to make // reading and writting look like C++. friend std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Field&amp; data) { data.read(stream); return stream; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Field const&amp; data) { data.write(stream); return stream; } }; void Field::reset(int n, int m) { size = {n, m}; mineField.reset(n, m); } void Field::read(std::istream&amp; stream) { // Assumes input file is correctly formatted. // The operator&gt;&gt; will ignore white space so we // don't need to deal with new line characters. // You can probably make it faster by manually handling this. for(int y = 0; y &lt; size.second; ++y) { for(int x = 0; x &lt; size.first; ++x) { char c; std::cin &gt;&gt; c; // Only care about '*' // Everything else is a '.' and can be ignored. if (c == '*') { mineField.add(x, y); } } } } void Field::write(std::ostream&amp; stream) const { for(int y = 0; y &lt; size.second; ++y) { for(int x = 0; x &lt; size.first; ++x) { std::cout &lt;&lt; mineField.get(x, y); } stream &lt;&lt; &quot;\n&quot;; } } </code></pre> <h2>Main</h2> <pre><code>bool isField(int n, int m) { return n != 0 &amp;&amp; m != 0; } int main() { // Only allocate the memory once. // Will reuse inside the loop by calling reset. Field field; int loop = 0; int n; int m; while (std::cin &gt;&gt; n &gt;&gt; m &amp;&amp; isField(n,m)) { // Reset then read the new field. field.reset(m, n); std::cin &gt;&gt; field; // The Judge does not want a trailing empty line. // So print it before each new field. But not before // the first one. if (loop != 0) { std::cout &lt;&lt; &quot;\n&quot;; } // Increment count and output. ++loop; std::cout &lt;&lt; &quot;Field #&quot; &lt;&lt; loop &lt;&lt; &quot;:\n&quot; &lt;&lt; field; } } </code></pre>
[]
[ { "body": "<p>It looks good to me, but there are a few things I would suggest changing.</p>\n<h2>Make <code>index</code> static</h2>\n<p>The <code>index</code> function only uses <code>maxSize</code> from the class and does not alter the class, so I would suggest making it <code>static</code>.</p>\n<h2>Prefer a <code>std::array</code> to <code>std::vector</code> when the size is known</h2>\n<p>Because we don't do any dynamic resizing of the <code>mines</code> data member, it would be sensible to make it a <code>std::array</code> instead of a <code>std::vector</code>.</p>\n<h2>Fix the bug</h2>\n<p>The <code>Field::read()</code> function is correctly taking a <code>std::istream&amp;</code> as a parameter, but is using <code>std::cin</code> instead of the passed stream. A similar error exists in <code>Field::write()</code>.</p>\n<h2>Consider using a custom allocator</h2>\n<p>The use of <code>field.reset</code> inside the loop isn't too terrible, but without knowing what is behind the <code>Field</code> type, I'd more likely have simply made it a local variable within the loop. We can get the best of both worlds by creating a custom allocator for the <code>Field</code> class that does essentially what <code>reset</code> is doing, but without disturbing a more intuitive user interface.</p>\n<h2>Consider processing on the fly</h2>\n<p>Each mine affects exactly three rows; the row it's in and the rows above and below. With this observation, it's easy to see that by buffering only three rows, any size array could be processed on the fly as it is being read. This would reduce the memory requirement (although that wasn't large) and allow processing on the fly. Here's one way to do that: <a href=\"https://codereview.stackexchange.com/questions/268539/yet-another-minesweeper-field-calculator\">Yet another minesweeper field calculator</a></p>\n<h2>Consider changing the data format</h2>\n<p>Since the goal is to print each square as either a mine or a single digit, why not keep the data in text format? That way, each row could be kept as a <code>std::string</code> (or <code>char *</code>) and printed directly instead of requiring conversion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T11:19:56.587", "Id": "268533", "ParentId": "268521", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T20:53:31.407", "Id": "268521", "Score": "5", "Tags": [ "c++", "c++17", "rags-to-riches", "minesweeper" ], "Title": "C++ Mine Sweeper Attempt" }
268521
<p>I have a working solution for the problem below. I have the feeling that it could be improved using memoization, but I cannot see how to do it.</p> <p>The problem:</p> <p>You are given an array arr of N integers. For each index i, you are required to determine the number of contiguous subarrays that fulfill the following conditions: The value at index i must be the maximum element in the contiguous subarrays, and These contiguous subarrays must either start from or end on index i.</p> <p>Signature</p> <p>int[] countSubarrays(int[] arr)</p> <p>Input</p> <p>Array arr is a non-empty list of unique integers that range between 1 to 1,000,000,000 Size N is between 1 and 1,000,000</p> <p>Output</p> <p>An array where each index i contains an integer denoting the maximum number of contiguous subarrays of arr[I]</p> <p>Example:</p> <pre><code>arr = [3, 4, 1, 6, 2] output = [1, 3, 1, 5, 1] Explanation: For index 0 - [3] is the only contiguous subarray that starts (or ends) with 3, and the maximum value in this subarray is 3. For index 1 - [4], [3, 4], [4, 1] For index 2 - [1] For index 3 - [6], [6, 2], [1, 6], [4, 1, 6], [3, 4, 1, 6] For index 4 - [2] So, the answer for the above input is [1, 3, 1, 5, 1] </code></pre> <p>My solution (Is it O(n^2) time complexity?):</p> <pre><code>function countSubarrays(arr) { // Write your code here if(arr.length === 0) return []; if(arr.length === 1) return [1]; const checkLeft = (index) =&gt; { let count = 0; for(let i=index-1; i&gt;=0; i--) { if(arr[i] &lt; arr[index]) { count++; } else break; } return count; } const checkRight = (index) =&gt; { let count = 0; for(let i=index+1; i&lt;arr.length; i++) { if(arr[i] &lt; arr[index]) { count++; } else break; } return count; } const output = []; for(let i=0; i&lt;arr.length; i++) { output.push(1 + checkLeft(i) + checkRight(i)) } return output; } </code></pre>
[]
[ { "body": "<p>Starting from your main question <em>My solution (Is it O(n^2) time complexity?)</em> the answer is <em>yes</em> because for every element of the array you are looking for elements at the left and at the right of it so the complexity of your algorithm is quadratic. You can erase from your code the <code>if(arr.length === 0) return [];</code> line because it is guarantee that array is always not empty.</p>\n<p>It is possible to reach a linear complexity <em>O(n)</em> using an auxiliary structure like a stack and iterating two times over the elements of your array, first one from the beginning :</p>\n<pre><code>function countSubarrays(arr) {\n const length = arr.length;\n const result = new Array(length).fill(1);\n let stack = [];\n\n for (let i = 0; i &lt; length; ++i) {\n while(stack.length &amp;&amp; arr[stack[stack.length - 1]] &lt; arr[i]) {\n result[i] += result[stack.pop()];\n }\n stack.push(i);\n }\n\n //code for the reversed loop I'adding after\n}\n</code></pre>\n<p>Taking your <code>[3, 4, 1, 6, 2]</code> array example I create an initial <code>[1, 1, 1, 1, 1]</code> result array obtaining the <code>[1, 2, 1, 4, 1]</code> result array equal to the <strong>left</strong> maximum number of contiguous subarrays of arr[i] including itself.</p>\n<p>The same algorithm can be applied to calculate the the <strong>right</strong> maximum number of contiguous subarrays of arr[i] subtracting itself in a reverse cycle, arriving to the final code :</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>function countSubarrays(arr) {\nconst length = arr.length;\nconst result = new Array(length).fill(1);\nlet stack = [];\n\nfor (let i = 0; i &lt; length; ++i) {\n while(stack.length &amp;&amp; arr[stack[stack.length - 1]] &lt; arr[i]) {\n result[i] += result[stack.pop()];\n\n }\n stack.push(i);\n}\n\nstack = [];\nlet tmp = new Array(length).fill(1);\nfor (let i = length - 1; i &gt;= 0; --i) {\n while((stack.length) &amp;&amp; (arr[stack[stack.length - 1]] &lt; arr[i])) {\n tmp[i] += tmp[stack.pop()];\n }\n stack.push(i);\n result[i] += (tmp[i] - 1);\n}\n\nreturn result;\n}\n\nconsole.log(countSubarrays([3, 4, 1, 6, 2]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T16:49:06.677", "Id": "529688", "Score": "0", "body": "Note: I tried to format the javascript runnable snippet like the first one and surely I made some error somewhere, if someone could suggest me how to do I appreciate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T19:45:10.173", "Id": "529702", "Score": "0", "body": "Very nice solution. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T20:44:14.990", "Id": "529708", "Score": "0", "body": "@myTest532myTest532 You are welcome." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T16:04:46.957", "Id": "268571", "ParentId": "268522", "Score": "1" } } ]
{ "AcceptedAnswerId": "268571", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T22:03:55.850", "Id": "268522", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Is it possible to get a better performance using memoization? Array algorithm" }
268522
<h2>Motivation</h2> <p>While working on a completely unrelated task, I wanted to share a screenshot of my current Emacs frame, but <em>not</em> of the actual text contents. And while GIMP's pixelate filter did the job, I didn't want to fire up my image manipulation program just to share a picture of a custom theme or some functionality.</p> <p>I thought that Emacs <em>must</em> have some functionality to hide certain information on the displayed text. I remembered <code>toggle-rot13-mode</code>, but anyone interested in the text could decrypt it rather quickly. So instead, I had a look into its implementation and put my Emacs Lisp hat on to find my own solution.</p> <h2>Screenshot</h2> <p>On the left, the original buffer. On the right, an indirect clone with <code>secret-mode</code> enabled.</p> <p><a href="https://i.stack.imgur.com/6BBGx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6BBGx.png" alt="screenshot of secret-mode" /></a></p> <p><sup>(Note: this is the <code>wombat</code> theme, with <em>Fira Code</em> in Emacs 27.2 on Windows.)</sup></p> <h2>Code</h2> <p>I'm using two code blocks here to keep the noise from the actual lisp implementation. The actual code is just a single lisp file (<code>secret-mode.el</code>).</p> <pre class="lang-lisp prettyprint-override"><code>;;; secret-mode.el --- hide text in buffer -*- lexical-binding: t; -*- ;; Copyright (C) 2021 (omitted*) ;; Author: (omitted*) ;; Keywords: games ;; Version: 0.0.1 ;; This program is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. </code></pre> <pre class="lang-lisp prettyprint-override"><code>;;; Commentary: ;; This package provides `secret-mode', a buffer-local mode that uses ;; `buffer-display-table' to replace the displayed glyphs with Unicode ;; blocks. ;;; Code: (defconst secret-mode-table (let ((disptbl (make-display-table))) (dotimes (i 1024) (aset disptbl i (pcase (get-char-code-property i 'general-category) ((or 'Cc 'Cf 'Zs 'Zl 'Zp) nil) ('Lu (vector (make-glyph-code ?▆))) (_ (vector (make-glyph-code ?▃)))))) disptbl) &quot;Display table for the command `secret-mode'.&quot;) ;;;###autoload (define-minor-mode secret-mode &quot;Hide text.&quot; :lighter &quot; Secret&quot; (if secret-mode (setq buffer-display-table secret-mode-table) (setq buffer-display-table nil))) (provide 'secret-mode) ;;; secret-mode.el ends here </code></pre> <h2>What I'm looking for</h2> <p>Any kind of feedback is welcome. Feel free to trash the use of Display Tables if its unidiomatic or if there is a more practical way with another feature.</p> <p>Since I'm pretty happy with the result, I would like to publish this package, so feel especially encouraged to point anything out that needs to be done beforehand, as it will be my first published package.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T08:03:27.033", "Id": "529575", "Score": "0", "body": "Looks good to me - sorry I don't have any suggestions to improve it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T08:56:35.363", "Id": "529577", "Score": "0", "body": "@TobySpeight Still: thanks for the feedback! :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T22:12:44.757", "Id": "268523", "Score": "2", "Tags": [ "lisp", "elisp" ], "Title": "Hide your text with colorful blocks in secret(-mode)" }
268523
<p>I'm working on a personal project to build a website that quizzes users on chess opening theory moves. I know my code is not very object-oriented but I am working on refactoring it right now. I just wanted to get the basics of it working before I started to restructure everything.</p> <p>Here is the <a href="https://github.com/jdouglass/chess-openings" rel="nofollow noreferrer">link</a> to the repo to see all of the code. The website is live on <a href="https://jdouglass.github.io/chess-openings/" rel="nofollow noreferrer">Github pages</a> if you want to try it out right now (I have not added anything to the Results section yet).</p> <p>My question is how can I improve my JavaScript code to make it shorter for the menuJQeuryFunctions.js file? The file is over 1000 lines of just JQuery functions, there must be a way to truncate this code.</p> <p>Here is a snippet of my HTML code:</p> <pre><code> &lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;flex-div nav&quot;&gt; &lt;nav class=&quot;openings-menu&quot;&gt; &lt;div class=&quot;text&quot;&gt;Openings Menu&lt;/div&gt; &lt;ul class=&quot;parent&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-1-btn&quot; id=&quot;kings-pawn-opening&quot;&gt;King's Pawn Opening&lt;span class=&quot;fas fa-angle-down kings-pawn-arrow&quot;&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;ul class=&quot;level-2-class&quot; id=&quot;kings-pawn-show&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-2-btn&quot; id=&quot;sicilian-defence&quot;&gt;Sicilian Defence&lt;span class=&quot;fas fa-angle-down&quot;&gt;&lt;/a&gt;&lt;/li&gt; &lt;ul class=&quot;level-3-class&quot; id=&quot;sicilian-defence-show&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-3-btn&quot; id=&quot;open-sicilian&quot;&gt;Open Sicilian&lt;span class=&quot;fas fa-angle-down&quot;&gt;&lt;/a&gt;&lt;/li&gt; &lt;ul class=&quot;level-4-class&quot; id=&quot;open-sicilian-show&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-4-btn&quot; id=&quot;najdorf-variation&quot;&gt;Najdorf Variation&lt;span class=&quot;fas fa-angle-down&quot;&lt;/a&gt;&lt;/li&gt; &lt;ul class=&quot;level-5-class&quot; id=&quot;najdorf-variation-show&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-classical&quot;&gt;Classical Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-english&quot;&gt;English Attack&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-lipnitzky&quot;&gt;Lipnitzky Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-opocensky&quot;&gt;Opocensky Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-amsterdam&quot;&gt;Amsterdam Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-adams&quot;&gt;Adams Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;sicilian-najdorf-argentine&quot;&gt;Argentine Variation&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-4-btn&quot; id=&quot;dragon-variation&quot;&gt;Dragon Variation&lt;span class=&quot;fas fa-angle-down&quot;&gt;&lt;/a&gt;&lt;/li&gt; &lt;ul class=&quot;level-5-class&quot; id=&quot;dragon-variation-show&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-positional&quot;&gt;Positional Line&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-yugoslav&quot;&gt;Yugoslav Attack&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-soltis&quot;&gt;Soltis Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-classical&quot;&gt;Classical Variation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-levenfish&quot;&gt;Levenfish Attack&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;level-5-btn&quot; id=&quot;dragon-harrington-glek&quot;&gt;Harrington-Glek Variation&lt;/a&gt;&lt;/li&gt; </code></pre> <p>Here is what a snippet of my script.js code looks like. This code runs the main chess game after it knows what opening is selected.</p> <pre><code>let board = null let $board = $('#board') const game = new Chess() let squareClass = 'square-55d63' let squareToHighlight = null let colorToHighlight = null let $status = $('#status') let $fen = $('#fen') let $pgn = $('#pgn') let variation = [] let attempt = [] let totalMoves = 0 // updates three variables which are the colour's turn, FEN, and PGN // after each move is made and prints to the HTML tags function updateStatus () { let status = '' let moveColor = 'White' if (game.turn() === 'b') { moveColor = 'Black' } // checkmate? if (game.in_checkmate()) { status = 'Game over, ' + moveColor + ' is in checkmate.' } // draw? else if (game.in_draw()) { status = 'Game over, drawn position' } else { // game still on status = moveColor + ' to move' // check? if (game.in_check()) { status += ', ' + moveColor + ' is in check' } } // update html id tags $status.html(status) $fen.html(game.fen()) $pgn.html(game.pgn()) } function removeHighlights (color) { $board.find('.' + squareClass).removeClass('highlight-' + color) } function onDragStart (source, piece, position, orientation) { // do not pick up pieces if the game is over if (game.game_over()) return false if (variation.length === 0) { if ((game.turn() === 'w' &amp;&amp; piece.search(/^b/) !== -1) || (game.turn() === 'b' &amp;&amp; piece.search(/^w/) !== -1)) { return false } } else { // only pick up pieces for White if (piece.search(/^b/) !== -1) return false } } function onDrop (source, target) { // see if the move is legal let move = game.move({ from: source, to: target, // not necessary to have this i think // promotion: 'q' // NOTE: always promote to a queen for example simplicity }) // illegal move if (move === null) return 'snapback' attempt = game.history() if (variation.length !== 0) { if (attempt[attempt.length-1] !== variation[attempt.length-1]) { game.undo() } else { // highlight white's move removeHighlights('white') removeHighlights('hint') $board.find('.square-' + source).addClass('highlight-white') $board.find('.square-' + target).addClass('highlight-white') // make random move for black window.setTimeout(makeBlackMove, 250) } } else { if (move.color === 'w') { removeHighlights(&quot;white&quot;) $board.find('.square-' + move.from).addClass('highlight-white') squareToHighlight = move.to colorToHighlight = 'white' } if (move.color === &quot;b&quot;) { removeHighlights(&quot;black&quot;) $board.find('.square-' + move.from).addClass('highlight-black') squareToHighlight = move.to colorToHighlight = 'black' } } updateStatus() } function highlightSquare() { // will possibly use this later } function makeBlackMove() { game.move(variation[attempt.length]) let blackMove = game.history({verbose: true}) // console.log(blackMove) console.log(blackMove[attempt.length]) // highlight black's move removeHighlights('black') $board.find('.square-' + blackMove[attempt.length].from).addClass('highlight-black') squareToHighlight = blackMove[attempt.length].to // update the board to the new position board.position(game.fen()) attempt = game.history() } function onMoveEnd() { $board.find('.square-' + squareToHighlight).addClass('highlight-black') updateStatus() } // update the board position after the piece snap // for castling, en passant, pawn promotion function onSnapEnd() { if (variation.length === 0) { $board.find('.square-' + squareToHighlight).addClass('highlight-'+ colorToHighlight) } board.position(game.fen()) } function showHint() { if (variation.length !== 0 &amp;&amp; game.turn() === &quot;w&quot;) { let hintSquare = game.move(variation[attempt.length]) hintSquare = hintSquare.from $board.find('.' + squareClass).removeClass('highlight-hint') $board.find('.square-' + hintSquare).addClass('highlight-hint') game.undo() } } function flipBoard() { // NEED TO FIX PIECE HIGHLIGHTING WHEN FLIPPING THE BOARD if (board.orientation() === &quot;white&quot;) { board.orientation(&quot;black&quot;) $board.find('.square-' + squareToHighlight).addClass('highlight-'+colorToHighlight) } else { board.orientation(&quot;white&quot;) $board.find('.square-' + squareToHighlight).addClass('highlight-'+colorToHighlight) } } function startGame() { let config = { draggable: true, position: 'start', onDragStart: onDragStart, onDrop: onDrop, onSnapEnd: onSnapEnd, onMoveEnd: onMoveEnd } variation = [] attempt = [] board = Chessboard('board', config) game.reset() updateStatus() totalMoves = 0 } // this function is called after every move is made and updates the turn status, // FEN and PGN updateStatus() // when page loads, initialize the chess board to the starting position $(document).ready(startGame) // when the reset button is pressed it resets the game state, // and resets the status variables $('#resetBtn').click(startGame) $('#hintBtn').click(showHint) $('#flipBoardBtn').click(flipBoard) </code></pre> <p>Lastly, here is the JQuery code for each time the menu item opening variation is clicked on. The fact that the code is over 1000 lines (but I'm only going to show a portion of it because it's very repetitive code) of just almost the same JQuery functions but with different opening variation names makes me think I can shorten it.</p> <pre><code>// openings menu scripts $(&quot;#kings-pawn-opening&quot;).click(function() { $(&quot;#kings-pawn-show&quot;).toggleClass(&quot;show&quot;); // $(&quot;#kings-pawn-arrow&quot;).toggleClass(&quot;rotate&quot;); }); // SICILIAN DEFENCE $(&quot;#sicilian-defence&quot;).click(function() { $(&quot;#sicilian-defence-show&quot;).toggleClass(&quot;show&quot;); }); $(&quot;#open-sicilian&quot;).click(function() { $(&quot;#open-sicilian-show&quot;).toggleClass(&quot;show&quot;); }); $(&quot;#najdorf-variation&quot;).click(function() { $(&quot;#najdorf-variation-show&quot;).toggleClass(&quot;show&quot;); }); $(&quot;#sicilian-najdorf-classical&quot;).click(function() { startGame() variation = sicilianNajdorfClassicalMainLine console.log(variation) }); $(&quot;#sicilian-najdorf-english&quot;).click(function() { startGame() variation = sicilianNajdorfEnglishAttack console.log(variation) }); $(&quot;#sicilian-najdorf-lipnitzky&quot;).click(function() { startGame() variation = sicilianNajdorfLipnitzkyAttack console.log(variation) }); $(&quot;#sicilian-najdorf-opocensky&quot;).click(function() { startGame() variation = sicilianNajdorfOpocensky console.log(variation) }); $(&quot;#sicilian-najdorf-amsterdam&quot;).click(function() { startGame() variation = sicilianNajdorfAmsterdam console.log(variation) }); </code></pre> <p>Here is a snippet of the chess opening variation arrays that I am using:</p> <pre><code> // ----------------------- OPEN SICILIAN ----------------------- // sicilian najdorf const sicilianNajdorfClassicalMainLine = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;Bg5&quot;, &quot;e6&quot;, &quot;f4&quot;, &quot;Be7&quot;, &quot;Qf3&quot;, &quot;Qc7&quot;, &quot;O-O-O&quot;, &quot;Nbd7&quot;, &quot;g4&quot;] const sicilianNajdorfArgentine = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;Bg5&quot;, &quot;e6&quot;, &quot;f4&quot;, &quot;Be7&quot;, &quot;Qf3&quot;, &quot;Qc7&quot;, &quot;h6&quot;, &quot;Bh4&quot;, &quot;g5&quot;, &quot;fxg5&quot;, &quot;Nfd7&quot;] // maybe not include this one const sicilianNajdorfEnglishAttack = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;Be3&quot;, &quot;e5&quot;, &quot;Nb3&quot;, &quot;Be6&quot;, &quot;f3&quot;] const sicilianNajdorfLipnitzkyAttack = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;Bc4&quot;, &quot;e6&quot;, &quot;Bb3&quot;, &quot;b5&quot;] const sicilianNajdorfOpocensky = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;Be2&quot;, &quot;e6&quot;] // maybe not include this one const sicilianNajdorfAmsterdam = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;f4&quot;, &quot;e5&quot;, &quot;Nf3&quot;, &quot;Nbd7&quot;, &quot;a4&quot;, &quot;Be7&quot;, &quot;Bd3&quot;, &quot;O-O&quot;] const sicilianNajdorfAdams = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;a6&quot;, &quot;h3&quot;, &quot;e5&quot;, &quot;Nde2&quot;, &quot;h5&quot;] // sicilian dragon const sicilianDragonPositional = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'g6', 'Be3', 'Bg7', 'f3', 'O-O', 'Qd2', 'Nc6', 'O-O-O'] const sicilianDragonYugoslav = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;g6&quot;, &quot;Be3&quot;, &quot;Bg7&quot;, &quot;f3&quot;, &quot;O-O&quot;, &quot;Qd2&quot;, &quot;Nc6&quot;, &quot;Bc4&quot;, &quot;Bd7&quot;, &quot;O-O-O&quot;, &quot;Rc8&quot;, &quot;Bb3&quot;, &quot;Ne5&quot;, &quot;h4&quot;, &quot;Nc4&quot;, &quot;Bxc4&quot;, &quot;Rxc4&quot;, &quot;h5&quot;, &quot;Nxh5&quot;, &quot;g4&quot;, &quot;Nf6&quot;, &quot;Bh6&quot;] const sicilianDragonSoltis = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'g6', 'Be3', 'Bg7', 'f3', 'O-O', 'Qd2', 'Nc6', 'Bc4', 'Bd7', 'O-O-O', 'Rc8', 'Bb3', 'Ne5', 'h4', 'h5'] const sicilianDragonClassical = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;g6&quot;, &quot;Be2&quot;, &quot;Bg7&quot;, &quot;Be3&quot;, &quot;Nc6&quot;, &quot;O-O&quot;, &quot;O-O&quot;, &quot;Nb3&quot;, &quot;d5&quot;] const sicilianDragonLevenfish = [&quot;e4&quot;, &quot;c5&quot;, &quot;Nf3&quot;, &quot;d6&quot;, &quot;d4&quot;, &quot;cxd4&quot;, &quot;Nxd4&quot;, &quot;Nf6&quot;, &quot;Nc3&quot;, &quot;g6&quot;, &quot;f4&quot;, &quot;Nc6&quot;, &quot;e5&quot;] const sicilianDragonHarrington = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'g6', 'Be3', 'Bg7', 'Be2', 'O-O', 'Qd2', 'Nc6', 'O-O-O'] // sicilian classical const sicilianRichter = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'Nc6', 'Bg5', 'e6', 'Qd2'] const sicilianFischerSozin = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'Nc6', 'Bc4', 'e6', 'Bb3', 'a6', 'O-O'] const sicilianVelimirovic = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'Nc6', 'Bc4', 'e6', 'Be3', 'Be7', 'Qe2'] const sicilianBoleslavsky = ['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'Nc6', 'Be2', 'e5', 'Nf3', 'h6', 'O-O', 'Be7', 'Re1', 'O-O', 'h3'] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T07:57:52.127", "Id": "529574", "Score": "1", "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." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T23:24:11.003", "Id": "268524", "Score": "1", "Tags": [ "javascript", "jquery", "html", "chess" ], "Title": "Chess quiz web site" }
268524
<p>I do have my code running but again I'm wondering if there is a nicer solution since mine seems to be clumsy and I'm wondering if there is a better way like chaining (but I can't work out how to do that)</p> <p>What I want to do is: <strong>for each element in data.lines</strong> replace properties &quot;<strong>from</strong>&quot; and &quot;<strong>to</strong>&quot; with an <strong>array of the &quot;x&quot; and &quot;y&quot;</strong> values given in <strong>data.points depending on the id</strong>.</p> <p>Meaning: data.lines.[0]from = 1 - so look for which item in data.points has the id=1 and assign its values x and y to data.lines[0]from in an array for each prop in data.lines.</p> <p>I do have an array like that:</p> <pre><code>data = [ &quot;points&quot;: [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;Point 1&quot;, &quot;x&quot;: 40, &quot;y&quot;: 30 }, { &quot;id&quot;: 2, &quot;name&quot;: &quot;Point 2&quot;, &quot;x&quot;: 180, &quot;y&quot;: 30 }, { &quot;id&quot;: 3, &quot;name&quot;: &quot;Point 3&quot;, &quot;x&quot;: 40, &quot;y&quot;: 120, } ], &quot;lines&quot;: [ { &quot;id&quot;: 1001, &quot;from&quot;: 2, &quot;to&quot;: 1 }, { &quot;id&quot;: 1002, &quot;from&quot;: 1, &quot;to&quot;: 3 }, ] ] </code></pre> <p>So it should look like:</p> <pre><code>let newData = [ { &quot;id&quot;: 1001, &quot;from&quot;: [180, 30], &quot;to&quot;: [40, 30] }, { &quot;id&quot;: 1002, &quot;from&quot;: [40, 30], &quot;to&quot;: [40, 120] }, ] </code></pre> <p>My solution looks like that but I think it's not good to use if 2x</p> <pre><code> compileLines(data) { let result = []; data.lines.map(element =&gt; { data.points.filter(item =&gt; { if(item.id === element.from) { element.from = [item.x, item.y]; } if(item.id === element.to) { element.to = [item.x, item.y]; result.push(element); } }) }); this.newData = result; } </code></pre>
[]
[ { "body": "<p>You're using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">map</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">filter</a> but not their return values. They both return a modified version of the given array. No need to create a new one and push each element into it.</p>\n<p>Furthermore i used <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\">find</a> to get a single result. Combine this with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring</a> and you've got the same results.</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 data={points:[{id:1,name:\"Point 1\",x:40,y:30},{id:2,name:\"Point 2\",x:180,y:30},{id:3,name:\"Point 3\",x:40,y:120}],lines:[{id:1001,from:2,to:1},{id:1002,from:1,to:3}]};\n\nconst compileLines = ( data ) =&gt; {\n const { points, lines } = data;\n \n return lines.map(( line ) =&gt; {\n const p1 = points.find(({ id }) =&gt; id === line.from);\n const p2 = points.find(({ id }) =&gt; id === line.to);\n \n return {\n ...line,\n from: [p1.x, p1.y],\n to: [p2.x, p2.y],\n }\n });\n}\n\nconst result = compileLines( data );\n\nconsole.log( result );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T13:41:55.183", "Id": "268535", "ParentId": "268532", "Score": "0" } }, { "body": "<p>You should make the points array into a lookup table to make it constant time (ie <code>points.reduce((acc, {id, x, y}) =&gt; (acc[id] = [x, y], acc), {})</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T14:27:22.173", "Id": "529944", "Score": "0", "body": "Thank you for that hint! I tested it and like this approach very much" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T16:18:46.423", "Id": "268572", "ParentId": "268532", "Score": "0" } } ]
{ "AcceptedAnswerId": "268535", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T09:39:00.507", "Id": "268532", "Score": "0", "Tags": [ "javascript", "array", "iteration" ], "Title": "Add Properties from one array of Objects to another array of Objects based on property id" }
268532
<p>I primarily work with C#, and when working with an array of arrays, I can sum the length of the sub arrays using Linq:</p> <pre><code>var myArray = new int[2][] { new int[3] { 1, 2, 3 }, new int[4] { 1, 2, 3, 4 } }; myArray.Sum(s =&gt; s.Length); </code></pre> <p>Printing the result of that sum to a console should produce a <code>7</code>. With that in mind, I'm having trouble finding resources on a simple way to do this in JavaScript, and as such I'm stuck doing it with nested <code>for</code> iterators:</p> <pre><code>let containedLength = 0; let myArray = [ [1, 2, 3], [1, 2, 3, 4] ]; for (let x = 0; x &lt; myArray.length; x++) for (let y = 0; y &lt; myArray[x].length; y++) containedLength++; </code></pre> <p>I <em>could</em> write a function to do this, but that would be over the top for what I'm trying to do today since I already have a basic way to do it. Is there a simpler way similar to C#'s Linq that could get the sum of the lengths of arrays, within an array of arrays?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T04:33:56.660", "Id": "529622", "Score": "4", "body": "For the sake of completeness: the analogous javascript would be `myArray.map(a => a.length).reduce((a, b) => a + b, 0)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:37:06.260", "Id": "529677", "Score": "7", "body": "@Quelklef: …or just `myArray.reduce((a, s) => a + s.length, 0)`" } ]
[ { "body": "<p>the simple way is to flatten out the array then get the length as it flattens out all the array.</p>\n<pre><code>let myArray = [ [1, 2, 3], [1, 2, 3, 4] ];\nconsole.log(myArray.flat().length);\n</code></pre>\n<p>That will output 7.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T15:46:15.317", "Id": "268538", "ParentId": "268536", "Score": "2" } }, { "body": "<p>There's no need for the inner loop to compute the length element by element. It's better to use the <code>.length</code> property on each row, reducing the inner loop time complexity to O(1), and covert your C-style loop to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for..of</code> loop</a> which is less prone to errors:</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 arr = [[1, 2, 3], [1, 2, 3, 4]];\nlet innerLength = 0;\n\nfor (const row of arr) {\n innerLength += row.length;\n}\n\nconsole.log(innerLength);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(You can see a few style preferences here; use vertical whitespace and braces around <code>for</code>/<code>if</code> blocks, prefer <code>const</code> to <code>let</code>, avoid &quot;my&quot; in var name)</p>\n<hr />\n<p>The above code isn't satisfying relative to the C# code, though. JS has a much less expressive API for array opterations than Linq. The normal approximation is to use <code>map</code>/<code>reduce</code>/<code>flat</code>/<code>flatMap</code>/<code>filter</code>-type functions. For example, if <code>flat</code> is available:</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 arr = [[1, 2, 3], [1, 2, 3, 4]];\nconsole.log(arr.flat().length); // flatten 1 level only, like original code</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>But the problem is that this is O(n) space, unlike your O(1) space code. We allocate and build a whole new array just to take its <code>.length</code>, then send it to the garbage collector.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>Array#reduce</code></a> can give you the functional style but preserving O(1) space and is probably the closest we can get to C# without helper functions or third-party libraries:</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 arr = [[1, 2, 3], [1, 2, 3, 4]];\nconsole.log(arr.reduce((a, e) =&gt; a + e.length, 0));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This is probably a little slower than <code>for..of</code> (due to function call overhead) and isn't quite as elegant as <code>flat</code>, but might be a good balance depending on your use case.</p>\n<p>It's good not to prematurely optimize though, so <code>flat()</code> is fine for starters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:43:54.820", "Id": "529678", "Score": "2", "body": "I like your answer in general, but I do slightly disagree with the last paragraph. It's indeed good not to *spend significant effort* on prematurely optimizing something that hasn't been determined to be an issue, especially if such optimization might introduce bugs or make the code harder to read. But it's also good not to deliberately litter your code with known inefficient idioms, when a clean and more efficient alternative exists. I would consider `array.flat().length` to be an example of such a pointlessly wasteful idiom that should be avoided merely on principle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T15:59:16.813", "Id": "529685", "Score": "2", "body": "My point is that although JS array funcs tend to be space inefficient, it's fine to use them anyway and focus on bigger problems. In this particular case, the `reduce` option happens to be O(1) space and also quite clean, but usually you don't get so lucky and it's just better to use `flat`, `map` or `filter` and trade space for readability. `reduce` can get ugly quickly. It's a use-case-specific judgment call, and I'd err on the side of whatever's easiest first. \"Fine for starters\" seems like an appropriately mild endorsement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T19:46:39.740", "Id": "529703", "Score": "1", "body": "I would like to point out that `reduce` is a common name (the even more common name being `fold`) for what .NET LINQ calls `Aggregate`, so it does exist in LINQ as well. Also, I would like to point out that `reduce` aka `fold` aka `Aggregate` is known to be a universal iteration operation, i.e. it can do everything a `foreach` can do, and thus it is not surprising that it can solve this problem, because it can solve *all* problems (that involve iterating over a collection). The `Sum` method in the question is essentially a restricted version of `Aggregate`. (Which is again trivially true …" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T19:52:21.520", "Id": "529704", "Score": "0", "body": "because *all* collection operations are in some sense special cases of `Aggregate`, but here the equivalence is much closer. Basically, `const sum = (arr, f) => arr.reduce((acc, ...args) => acc + f(...args), 0);`.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T16:10:44.170", "Id": "268540", "ParentId": "268536", "Score": "13" } } ]
{ "AcceptedAnswerId": "268540", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T15:22:31.643", "Id": "268536", "Score": "4", "Tags": [ "javascript", "array" ], "Title": "Is there a simpler way to sum the lengths of arrays within an array of arrays in JavaScript?" }
268536
<p>The task is to read in a data file containing a representation of a rectangular array with '*' signifying a mine and '.' signifying the absence of one. Each such array is preceded by a row and column count. The file is terminated with an entry that has zero for both the row and column counts. The expected output counts each frame (starting from 1) and emits a modified representation of the input that substitutes a digit for each '.' in the input. The digit is the number of mines next to that space.</p> <p>As with <a href="https://codereview.stackexchange.com/questions/268521/c-mine-sweeper-attempt/268533#268533">C++ Mine Sweeper Attempt</a> I did a review and decided to create a version as well. On my machine with a 25,000 line input file mostly containing <span class="math-container">\$99 \times 100\$</span> fields, the original took an average of 0.140 seconds while this version took an average of 0.025 seconds (less than 20% of the time).</p> <p>Internally, it keeps three pointers into a common buffer area. The pointers are for the <code>currentRow</code> and also for the <code>aboveRow</code> and <code>belowRow</code>. It reads data into the <code>currentRow</code> calling the <code>placeMine</code> function when a mine has been read. As each mine is read, all rows are appropriately updated using the <code>increment</code> function.</p> <p>No attempt is made at error checking or recovery, so if the user sets the maximum width (given here as a template parameter) to say, 50, but the input has rows much larger, the program will likely segfault and crash. In the same vein, the input file is expected to be formatted perfectly.</p> <h2>mines.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;array&gt; template &lt;std::size_t maxWidth = 100&gt; class MineField { static constexpr char mine{'*'}; static constexpr int maxSize{maxWidth + 2}; int rows = 0; int cols = 0; std::array&lt;char, maxSize * 3&gt; buffer; char *aboveRow = &amp;buffer[0]; char *currentRow = &amp;buffer[maxSize]; char *belowRow = &amp;buffer[maxSize * 2]; void increment(char&amp; location) { if (location != mine) ++location; } void showrow(std::ostream&amp; out) const { out.write(&amp;aboveRow[1], cols); out &lt;&lt; '\n'; } // place the mine at the current row and adjust neighboring counts void placeMine(int i) { currentRow[i+1] = mine; increment(currentRow[i]); increment(currentRow[i+2]); increment(aboveRow[i]); increment(aboveRow[i+1]); increment(aboveRow[i+2]); increment(belowRow[i]); increment(belowRow[i+1]); increment(belowRow[i+2]); } // shift the rows up and fill the bottom row with zeroes void shift() { std::swap(aboveRow, currentRow); std::swap(belowRow, currentRow); std::fill_n(belowRow, cols, '0'); } public: void process(std::istream&amp; in, std::ostream&amp; out) { in &gt;&gt; rows &gt;&gt; cols; for (int fieldnum{0}; rows &amp;&amp; cols; ) { buffer.fill('0'); if (fieldnum) { out &lt;&lt; '\n'; } out &lt;&lt; &quot;Field #&quot; &lt;&lt; ++fieldnum &lt;&lt; &quot;:\n&quot;; for (int j{0}; j &lt; rows; ++j) { for (int i{0}; i &lt; cols; ++i) { char ch; in &gt;&gt; ch; if (ch == mine) { placeMine(i); } } if (j) { showrow(out); } shift(); } showrow(out); in &gt;&gt; rows &gt;&gt; cols; } } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); MineField&lt;100&gt; field; field.process(std::cin, std::cout); } </code></pre> <h2>Example input</h2> <pre><code>4 4 *.** .... .*.. ...* 3 6 ***... *.*..* ***... 0 0 </code></pre> <h2>Example output</h2> <pre><code>Field #1: *2** 2332 1*23 112* Field #2: ***211 *8*31* ***211 <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:30:28.440", "Id": "529601", "Score": "0", "body": "What is the processor, memory size and OS on your computer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:46:54.420", "Id": "529605", "Score": "0", "body": "This computer has an Intel i7 running at 3.4GHz, with 16 RAM running 64-bit Linux (Fedora 34). Compiler is gcc 11.2 with -O2 optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:16:49.170", "Id": "529612", "Score": "0", "body": "That should be 16GiB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:06:20.257", "Id": "529671", "Score": "0", "body": "@Edward you can go back and edit your comments, FYI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:07:37.173", "Id": "529672", "Score": "0", "body": "You can edit comments, but only within 5 minutes of posting." } ]
[ { "body": "<h1>Consider using an array of rows</h1>\n<p>The idea to use pointers into buffer is a good one, as swapping those pointers around is quite fast. However, instead of using three distinct variables to hold those pointers, consider storing them in an array:</p>\n<pre><code>std::array&lt;char *, 3&gt; rows = {&amp;buffer[0], &amp;buffer[maxSize], &amp;buffer[maxSize * 2]};\n</code></pre>\n<p>Now you can do more with loops, for example <code>placeMine()</code> could become:</p>\n<pre><code>void placeMine(int i) {\n for (int y: {0, 1, 2})\n for (int x: {0, 1, 2})\n increment(rows[y][i + x]);\n rows[1][i + 1] = mine;\n}\n</code></pre>\n<p>And let the compiler worry about unrolling that loop. The two swaps in <code>shift()</code> could be replaced by a <a href=\"https://en.cppreference.com/w/cpp/algorithm/rotate\" rel=\"noreferrer\"><code>std::rotate()</code></a>:</p>\n<pre><code>std::rotate(rows.begin(), ++rows.begin(), rows.end());\n</code></pre>\n<h1>Possible optimizations</h1>\n<p>In <code>showrow()</code>, I would set the last character of the row to '\\n', so you can print the line in a single call.</p>\n<p>Instead of checking if <code>fieldnum</code> is non-zero to print an empty line separating the fields, I would unconditionally print a newline at the end of the outer <code>for</code>-loop in <code>process()</code>.</p>\n<p>It might be possible to vectorize this. For example, if your CPU has 128 bit vectors, each one can hold 16 characters. So read in 16 characters into a temporary 16 x 8 bit vector register, then use some bit operations to ensure every <code>*</code> is converted to a 1, and every <code>.</code> to a 0. Then in <code>placeMine()</code> you basically do what you are already doing, but now with 16 positions at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:16:04.480", "Id": "529611", "Score": "0", "body": "I particularly like the `array` idea. It didn't speed things up in my testing, but I think it makes the code nicer, so that's a win." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T19:24:09.057", "Id": "529613", "Score": "1", "body": "Unless the width if the fields is very large, everything will fit into the L1 data cache, so apart from vectorization I don't see how to improve it. Even with vectorization, it might be that I/O is already dominating the performance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:48:51.163", "Id": "268548", "ParentId": "268539", "Score": "5" } }, { "body": "<p>The style in C++ is to put the <code>*</code> or <code>&amp;</code> with the <em>type</em>, not the identifier. This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.</p>\n<hr />\n<p>I don't like how<br />\n<code> in &gt;&gt; rows &gt;&gt; cols;</code><br />\nneeds to be repeated at the top and bottom of the loop.\nI think you should consider a mid-decision loop as the most straightforward solution:</p>\n<pre><code>for (;;) {\n read values\n if (value meets exit condition) break;\n body of loop\n body statements...\n};\n</code></pre>\n<p>Or, you can make the reading of the bounds a separate function call, and cram it into the <code>while</code> condition:</p>\n<pre><code>while (read_bounds(rows,cols)) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:22:56.053", "Id": "529674", "Score": "0", "body": "I thought about writing `for (in >> rows >> cols; rows && cols; in >> rows >> cols)`. What do you think of that variation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:29:09.760", "Id": "529675", "Score": "2", "body": "@Edward hard to follow when cramming everything into the `for` statement, and you still have to state it twice! Use a separate function call as I showed: it's readable and only describes the reading once (in the function). The `for` loop does not match the semantics thus the need to restate the iteration step as the initial step. The semantics are logically a `while` as there is only one kind of thing, not different \"set up the first time\" and \"advance to the next\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:31:15.400", "Id": "529676", "Score": "1", "body": "I would include in the condition: `while (in >> rows >> cols && rows && cols)` (even though the usual input error checking is omitted elsewhere)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:18:46.660", "Id": "268569", "ParentId": "268539", "Score": "3" } } ]
{ "AcceptedAnswerId": "268548", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T15:50:52.083", "Id": "268539", "Score": "9", "Tags": [ "c++", "programming-challenge", "c++17", "minesweeper" ], "Title": "Yet another minesweeper field calculator" }
268539
<p>I have a directory that includes a number of subdirectories. Each subdirectories contains subdirectories of its own. I'd like to construct a list of all sub-subdirectories in python. Here is my attempt:</p> <pre><code>import os list_of_lists = [[sub_dir + '/' + sub_subdir for sub_subdir in os.listdir(my_dir + '/' + sub_dir)] for sub_dir in os.listdir(my_dir)] flat_list = [item for sublist in list_of_lists for item in sublist] </code></pre> <p>Is there a better/more efficient/more aesthetic way to construct this?</p> <p>To clarify, here is an example:</p> <pre><code>My_dir | |--sub_dir_1 | | | |--sub_sub_dir_1 | | | |--sub_sub_dir_2 | |--sub_dir_2 | | | |--sub_sub_dir_1 | |--sub_dir_3 | |--sub_sub_dir_1 | |--sub_sub_dir_2 | |--sub_sub_dir_2 </code></pre> <p>In this example, the output that I'm looking for is <code>['sub_dir_1/sub_sub_dir_1', 'sub_dir_1/sub_sub_dir_2', 'sub_dir_2/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_2', 'sub_dir_3/sub_sub_dir_3']</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T23:08:20.753", "Id": "529620", "Score": "1", "body": "Your example has only two levels. Do you care about deeper hierarchy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T10:05:14.500", "Id": "529659", "Score": "1", "body": "[os.walk](https://docs.python.org/3/library/os.html#os.walk) is what you are looking for. e.g. `[folder for folder, folders, files in os.walk(\".\") if not folders]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:02:45.823", "Id": "529670", "Score": "0", "body": "@vnp No, I don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:17:29.193", "Id": "529673", "Score": "0", "body": "@stefan Beautiful! Thanks!" } ]
[ { "body": "<p>The os module provides many functions to interact with operating system features, and one such method is <code>os.walk()</code>, which generates and fetch the files and folders in a directory tree. It can traverse the tree either top-down or bottom-up search, and by default, it sets as top-down search.</p>\n<p><strong>What you are looking for is to get the subdirectories with absolute path</strong> and using the <code>os.walk()</code> method you can retrieve the subdirectories in the absolute path.</p>\n<p>Below code gets both files and sub-directories but you can modify it to get only the subfolders according to your need.</p>\n<pre><code># import OS module\nimport os\n\n# List all the files and directories\npath = &quot;C:\\Projects\\Tryouts&quot;\nfor (root, directories, files) in os.walk(path, topdown=False):\n for name in files:\n print(os.path.join(root, name))\n for name in directories:\n print(os.path.join(root, name))\n</code></pre>\n<p>The other alternate way is to use the <code>glob</code> module. The glob module helps you retrieve the files/path matching a specified pattern as the glob supports the wildcard search. We can get both files and folders using the glob module.</p>\n<p>Source: <a href=\"https://itsmycode.com/python-list-files-in-a-directory/\" rel=\"nofollow noreferrer\">List Files and folders in a Directory</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T04:01:37.353", "Id": "529813", "Score": "1", "body": "You've been dropping links to your blog in your answers. Please take a look at [\"how not to be a spammer\"](//codereview.stackexchange.com/help/promotion) and consider making the affiliation more explicitly apparent in your answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T23:44:47.507", "Id": "268632", "ParentId": "268541", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T16:23:50.120", "Id": "268541", "Score": "0", "Tags": [ "python", "file-system" ], "Title": "Efficient way to construct list of sub-subdirectories in python" }
268541
<p>I'm writing a task list tracker with VueJS. Each task has a <code>Frequency</code> label (How often it needs to be done), Last completed date label (When the task was completed last) and a <code>Due Date</code> label which tells the user when a particular task needs to be done.</p> <p>The code below is used to update the <code>Due Date</code> field by accepting 2 arguments (Last_Completed_Date, Frequency). Based on parameters provided I want the Due Date label to change to one of the following options:</p> <ul> <li>Today</li> <li>Tomorrow</li> <li>n Number of days</li> </ul> <p>Is this a good way of writing such a function?</p> <pre><code>console.log(difference(&quot;2021-09-09T13:52:56.000Z&quot;, &quot;Monthly&quot;)) // Date=3 Weeks ago, expected result: 21 Days console.log(difference(&quot;2021-09-23T13:52:56.000Z&quot;, &quot;Weekly&quot;)) // Date=1 Week ago, expected result: Today console.log(difference(&quot;2021-09-29T13:52:56.000Z&quot;, &quot;Weekly&quot;)) // Date=1 Day ago, expected result: Tomorrow difference(data, freq) { const today = moment(); const newData = moment(data); if (freq === &quot;Daily&quot;) { return &quot;Today&quot;; } else if (freq === &quot;Weekly&quot;) { if (Math.abs(newData.diff(today, &quot;days&quot;)) &gt;= 7) { return &quot;Today&quot;; } else if ( Math.abs(newData.diff(today, &quot;days&quot;)) &lt; 7 &amp;&amp; Math.abs(newData.diff(today, &quot;days&quot;)) &gt; 1 ) { return Math.abs(newData.diff(today, &quot;days&quot;)) + &quot; Days&quot;; } else if (Math.abs(newData.diff(today, &quot;days&quot;)) == 1) { return &quot;Tomorrow&quot;; } } else if (freq === &quot;Monthly&quot;) { if (Math.abs(newData.diff(today, &quot;days&quot;)) &gt;= 30) { return &quot;Today&quot;; } else if ( Math.abs(newData.diff(today, &quot;days&quot;)) &lt; 30 &amp;&amp; Math.abs(newData.diff(today, &quot;days&quot;)) &gt; 1 ) { return Math.abs(newData.diff(today, &quot;days&quot;)) + &quot; Days&quot;; } else if (Math.abs(newData.diff(today, &quot;days&quot;)) == 1) { return &quot;Tomorrow&quot;; } } }, </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:05:43.557", "Id": "529597", "Score": "0", "body": "\"Today\", \"tomorrow\", etc., these depend on the timezone (for example, \"in 5 hours\" can be today if it's 13:00 in my timezone, but will be tomorrow if it's 23:00). Is it OK to default to UTC here? Also, I'm not sure about your examples, could you double-check?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:01:25.400", "Id": "529607", "Score": "0", "body": "Hi. Thanks for your comment. The time zone used in the examples come from a server set to ‘en-GB’. So UTC+1" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T16:37:54.527", "Id": "268542", "Score": "3", "Tags": [ "javascript", "datetime" ], "Title": "Calculate difference between dates and output desired result like (Today, Tomorrow, or 20 Days from now)" }
268542
<p>Here is my take at a lightweight interface implementation, where I focus on discoverability of suitable classes from strings (for simplicity, class name is used as an id). Each interface has it's own &quot;registry&quot; of implementations.</p> <p>My choice of <code>abc</code> module is due to presence of registration method there, better support from IDEs, and the fact that it's a part of Python standard library. I have not that much explored typing, but there is still one illustration for it as well.</p> <p>My examples are borrowed from this <a href="http://RealPython%20publication" rel="nofollow noreferrer">https://realpython.com/python-interface/#formal-interfaces</a>, though I've enhanced the original.</p> <p>I am mostly interested critiques towards the interface_meta module. The rest of the code is an illustration.</p> <p>Targeting Python 3.8+ here.</p> <pre><code>from __future__ import annotations ##### interface_meta module import inspect from abc import ABCMeta from abc import abstractmethod from typing import Type def _registration_hook(cls, subclass): subclass_name = subclass.__name__ if subclass_name in cls._all_classes: print(f&quot;Already registered {subclass_name}&quot;) cls._all_classes[subclass_name] = subclass def all_classes(cls): return cls._all_classes def for_id(cls, an_id): return cls._all_classes.get(an_id) def comparable(cls, subclass, attr): cls_attr = getattr(cls, attr, None) if not hasattr(subclass, attr): return f&quot;Attribute {attr!r} of {cls.__name__!r} not implemented in {subclass.__name__!r}&quot; subclass_attr = getattr(subclass, attr, None) if callable(cls_attr) == callable(subclass_attr) == False: return cls_argspec = inspect.getfullargspec(cls_attr) subclass_argspec = inspect.getfullargspec(subclass_attr) if cls_argspec != subclass_argspec: return (f&quot;\nSignature mismatch '{cls.__name__}.{attr}' &lt;-&gt; '{subclass.__name__}.{attr}'.&quot; f&quot;\nIn the interface : {cls_argspec}.&quot; f&quot;\nIn concrete class: {subclass_argspec}&quot;) def subclasshook(cls, subclass): cls._registration_hook(cls, subclass) errors = [comparable(cls, subclass, am) for am in cls.__abstractmethods__] if any(errors): raise TypeError(&quot;&quot;.join(e for e in errors if e)) return True class InterfaceMeta(ABCMeta): def __new__(mcs, *args, **kwargs): i = super().__new__(mcs, *args, **kwargs) i._all_classes = {} i._registration_hook = _registration_hook i.__subclasshook__ = classmethod(subclasshook) i.all_classes = classmethod(all_classes) i.for_id = classmethod(for_id) return i ##### examples of interfaces in different modules class FormalParserInterface(metaclass=InterfaceMeta): @abstractmethod def load_data_source(self, path: str, file_name: str) -&gt; str: &quot;&quot;&quot;Load in the data set&quot;&quot;&quot; @abstractmethod def extract_text(self, full_file_path: str) -&gt; dict: &quot;&quot;&quot;Extract text from the data set&quot;&quot;&quot; FormalParserInterfaceType = Type[FormalParserInterface] class SuccessfulSubFormalParserInterface(FormalParserInterface): @abstractmethod def extract_html(self, full_file_path: str) -&gt; dict: &quot;&quot;&quot;Extract html from the data set&quot;&quot;&quot; return {} ##### class ParserClassificationInterface(metaclass=InterfaceMeta): @property @abstractmethod def category(self): &quot;&quot;&quot;For classification&quot;&quot;&quot; def get_name(self): &quot;&quot;&quot;Example of concrete method. OK to provide concrete methods when then depend only on other methods in the same interface&quot;&quot;&quot; return self.__class__.__name__ ParserClassificationInterfaceType = Type[ParserClassificationInterface] ##### Implementation modules @FormalParserInterface.register @ParserClassificationInterface.register class EmlParserNew(FormalParserInterface, ParserClassificationInterface): &quot;&quot;&quot;Extract text from an email.&quot;&quot;&quot; category = &quot;EML&quot; def load_data_source(self, path: str, file_name: str) -&gt; str: &quot;&quot;&quot;Overrides FormalParserInterface.load_data_source()&quot;&quot;&quot; print(self.__class__, &quot;load_data_source&quot;, path, file_name) return &quot;&quot; def extract_text(self, full_file_path: str) -&gt; dict: &quot;&quot;&quot;A method defined only in EmlParser. Does not override FormalParserInterface.extract_text() &quot;&quot;&quot; return {} ##### @ParserClassificationInterface.register @FormalParserInterface.register class PdfParserNew(FormalParserInterface, ParserClassificationInterface): &quot;&quot;&quot;Extract text from a PDF.&quot;&quot;&quot; category = &quot;PDF&quot; def load_data_source(self, path: str, file_name: str) -&gt; str: &quot;&quot;&quot;Overrides FormalParserInterface.load_data_source()&quot;&quot;&quot; print(self.__class__, &quot;load_data_source&quot;, path, file_name) return &quot;does not matter&quot; def extract_text(self, full_file_path: str) -&gt; dict: &quot;&quot;&quot;Overrides FormalParserInterface.extract_text()&quot;&quot;&quot; print(self.__class__, &quot;extract_text&quot;, full_file_path) return {&quot;k&quot;: &quot;does not matter&quot;} @ParserClassificationInterface.register @FormalParserInterface.register class PdfParserNewest(PdfParserNew): &quot;&quot;&quot;Extract text from a PDF.&quot;&quot;&quot; def load_data_source(self, path: str, file_name: str) -&gt; str: &quot;&quot;&quot;Overrides FormalParserInterface.load_data_source()&quot;&quot;&quot; print(self.__class__, &quot;load_data_source&quot;, path, file_name) return &quot;does not matter&quot; ##### Usage examples def get_classification() -&gt; (ParserClassificationInterface | FormalParserInterface): return ParserClassificationInterface.for_id(&quot;PdfParserNew&quot;)() if __name__ == &quot;__main__&quot;: assert issubclass(PdfParserNew, FormalParserInterface) is True assert issubclass(PdfParserNew, ParserClassificationInterface) is True assert issubclass(SuccessfulSubFormalParserInterface, FormalParserInterface) is True try: issubclass(SuccessfulSubFormalParserInterface, ParserClassificationInterface) except TypeError as e: assert str(e) == &quot;&quot;&quot;Attribute 'category' of 'ParserClassificationInterface' not implemented in 'SuccessfulSubFormalParserInterface'&quot;&quot;&quot; pdf_parser = PdfParserNew() pdf_parser.load_data_source(&quot;&quot;, &quot;&quot;) pdf_parser2 = PdfParserNewest() pdf_parser2.load_data_source(&quot;&quot;, &quot;&quot;) eml_parser = EmlParserNew() eml_parser.load_data_source(&quot;&quot;, &quot;&quot;) print(FormalParserInterface.all_classes()) print(ParserClassificationInterface.all_classes()) some_parser = get_classification() print(some_parser.load_data_source(&quot;&quot;, &quot;&quot;)) assert pdf_parser.category == &quot;PDF&quot; assert pdf_parser2.category == &quot;PDF&quot; assert eml_parser.category == &quot;EML&quot; assert eml_parser.get_name() == &quot;EmlParserNew&quot; assert isinstance(pdf_parser2, ParserClassificationInterface) assert isinstance(pdf_parser2, FormalParserInterface) assert issubclass(PdfParserNew, ParserClassificationInterface) assert issubclass(PdfParserNewest, FormalParserInterface) # Ability to find implementation by string id. print(FormalParserInterface.for_id(&quot;PdfParserNew&quot;)().load_data_source(&quot;&quot;, &quot;&quot;)) assert FormalParserInterface.for_id(&quot;PdfParserHtml&quot;) is None </code></pre> <p>I am aware of <a href="https://codereview.stackexchange.com/questions/171457/implement-oo-interfaces-in-python">this question</a>, but in my implementation I wanted to to implement dispatching. And yes I am aware of zope.interface, but this implementation is supposed to be lightweight.</p> <p>Answering some questions. Demo has two lines of examples: One from the Real Python article, and an example of &quot;classification&quot;, purpose of which is just to add an attribute or property. There is no greater purpose.</p> <p>The <code>for_id</code> is runtime discovery of specific implementation, this is the main reason for the whole library. String id can be easily stored or communicated between systems, making it easy to implement completely declarative code, for example, for rules engine.</p> <p>My code at the time of this review can be found on <a href="https://github.com/rnd0101/python-interfaces-example/blob/CR/interface_meta.py" rel="nofollow noreferrer">github</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:31:45.223", "Id": "529602", "Score": "0", "body": "I like the simplicity of the `InterfaceMeta`, but why not build this on `typing.Protocol` instead? The interface-checking logic itself would be more or less the same, but with the added benefit of users being able to re-use your `Protocol` for static type hinting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:10:20.373", "Id": "529609", "Score": "0", "body": "On second though, you don't get the `__subclasshook__` behavior with `typing.Protocol`. I'll have to ponder this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:10:22.793", "Id": "529610", "Score": "0", "body": "I need to explore typing.Protocol better before seeing it's benefits (it's quite fresh, and probably not mature enough?). At the moment I am more interested in being able to discover implementations rather than strictly checking anything so this code is next step from purely 'marker interfaces'. I like zope.interface adapters and multi-dispatch features, but they are quite verbose. And actually I can probably even go \"meta-level\" by having registration on interfaces as well - so those can be discovered \"from strings\"... hmmm" } ]
[ { "body": "<h2>Initial impressions</h2>\n<ul>\n<li>Re-using the ABC registration system is a nice idea. Note that this will not raise any errors at class <em>definition</em> time, only at <em>instantiation</em> time.\n<ul>\n<li>I personally think is a mis-feature of ABCs and not really your fault, but maybe you are happy with that behavior.</li>\n<li>Another option is to entirely skip runtime type-checking of subclasses of interfaces, leaving all of this work to the type checker.</li>\n</ul>\n</li>\n<li>Write docstrings! Some of this code is what I would call &quot;non-obvious&quot;. You should document what each of these functions does.\n<ul>\n<li>At the very least, you should put in a comment on each of the functions that are meant to be attached to <code>Interface</code> classes, because it took a couple re-reads to realize what you were doing.</li>\n</ul>\n</li>\n<li>Some names are a bit &quot;opaque&quot;.\n<ul>\n<li><code>_registration_hook</code> could be <code>_register_interface_subclass</code></li>\n<li><code>comparable</code> could be <code>is_valid_interface_subclass</code></li>\n</ul>\n</li>\n<li>In <code>comparable()</code>, returning a string-ified &quot;error message&quot; is an awkward signaling mechanism. You should structure this data somehow, and only string-ify it for presentation to the user. Otherwise it will makes this library difficult to work with. See below.</li>\n<li>In <code>subclasshook()</code>, you probably don't want <code>&quot;&quot;.join</code>. Perhaps you want <code>&quot;\\n&quot;.join</code> or similar?</li>\n<li>You can (and should) type-hint <code>InterfaceMeta</code> and its associated functions.</li>\n<li>Use <code>warnings.warn()</code> instead of <code>print()</code>.</li>\n<li>I'm not sure I understand how <code>for_id()</code> is supposed to be used, nor do I understand the <code>get_classification()</code> function in the demo. Is it meant to be some kind of dynamic implementation lookup?</li>\n<li>What is a &quot;classification&quot; supposed to be, anyway? This doesn't look like it's related to the design of your interface system, but it's part of your demo and I don't understand it.</li>\n</ul>\n<h2>Don't use strings to convey structured information</h2>\n<p>The stringly-typed output from <code>comparable()</code> is not great. You might want to build a more-structured hierarchy of interface-subclassing failures, which is only string-ified &quot;on-demand&quot; by the user.</p>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\nimport inspect\nfrom typing import TypeVar, Sequence\n\n\n_Interface = TypeVar('_Interface', bound='Interface')\n\n\n@dataclass\nclass ImplementationSubclassingError(TypeError):\n &quot;&quot;&quot;Base class for errors in an implementation of an Interface.&quot;&quot;&quot;\n parent: _Interface\n subclass: Type[_Interface]\n\n\n@dataclass\nclass AttributeMissing(ImplementationSubclassingError):\n attribute_name: str\n\n def __str__(self) -&gt; str:\n return (\n f&quot;Attribute {self.attribute_name} of {self.parent.__name__} is &quot;\n f&quot;not implemented in {self.subclass.__name__}.&quot;\n )\n\n\n@dataclass\nclass SignatureMismatch(ImplementationSubclassingError):\n method_name: str\n parent_argspec: inspect.Argspec\n subclass_argspec: inspect.Argspec\n \n def __str__(self) -&gt; str:\n return (\n f&quot;Signature of {self.subclass.__name__}.{self.method_name} &quot;\n f&quot;does not match &quot;\n f&quot;signature of {self.parent.__name__}.{self.method_name}.&quot;\n )\n\n\nclass ImplementationInvalid(TypeError):\n # Re-use the &quot;args&quot; attribute from BaseException\n errors: Sequence[ImplementationSubclassingError, ...]\n\n def __init__(*errors: ImplementationSubclassingError):\n self.errors = errors\n super().__init__(*errors)\n\n def __str__(self) -&gt; str:\n return &quot;\\n&quot;.join(map(str, self.errors))\n</code></pre>\n<p>This kind of setup gives you a programmable and introspectable system, which <em>also</em> results in nice error messages for the user.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T06:31:02.877", "Id": "529636", "Score": "0", "body": "Very good points, thanks! I will go through it thoroughly, and accept over weekend. Now that you subclassed TypeError, I got an idea if I interfaces should somehow include exception information as well... or be themselves \"interface-able\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T17:14:34.833", "Id": "529689", "Score": "0", "body": "Added answers to the questions in the question. The `for_id` is central here. The name is probably not good, but here some background is explained: https://softwareengineering.stackexchange.com/questions/351389/dynamic-dispatch-from-a-string-python . The \"id\" can be obtained from the class being registered in many different ways. Here the simplest way is used - class name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T20:37:13.820", "Id": "529707", "Score": "0", "body": "In that case, I'd suggest removing the layer of indirection; just let the user do the lookup in a dict! Unless you need to perform some additional validation/processing before or after the dict lookup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T06:48:44.003", "Id": "529729", "Score": "0", "body": "Hmmm. I like this idea, but then I do not want users to modify the dict, also I want a cleaner syntax for access. So `FormalParserInterface.implementations.get(\"SpecificImplementationId\")` gets the get... or then `FormalParserInterface.implementations[\"SpecificImplementationId\"]` when try-except can be used - something like this? I was also thinking of more advanced cases than the dict allows, but can be good for starters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:47:51.117", "Id": "529750", "Score": "0", "body": "Yeah, that is a matter of taste. Your lookup function is fine, maybe it just needs a better name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T14:23:14.413", "Id": "529757", "Score": "1", "body": "For the record, I asked how to make interface metaclass to be more mypy-friendly and received quite simple suggestion for that: https://stackoverflow.com/questions/69417027/how-to-typecheck-class-with-method-inserted-by-metaclass-in-python - that is, `for_id` and `all_classes` can be there in the metaclass (at least I do not see any reason not to)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T11:27:57.903", "Id": "529782", "Score": "0", "body": "Thank you for the review! When time allows, I will make a single-file Python package out of this (link to repo at the end of the question). Some items implemented right away, others on todo list (I do not think structured exceptions add value at the moment), type-hinting also confuses as I do not see future-proof way for type-hinting - the old way will be deprecated, but I can't leave 3.8 behind yet. Also I enhanced getting ids to any attribute (not just `__name__`) and also there can be several ids for one class. I have use cases for that." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T19:17:13.073", "Id": "268551", "ParentId": "268544", "Score": "2" } } ]
{ "AcceptedAnswerId": "268551", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:16:12.663", "Id": "268544", "Score": "3", "Tags": [ "python-3.x", "interface", "meta-programming" ], "Title": "Lightweight interface implementation in Python 3 using abstract classes" }
268544
<p>I have a function which takes one argument, a fraction, and returns two numbers - an <strong>integer</strong> and a <strong>power of two</strong>.</p> <ul> <li>So, when you divide the the <strong>integer</strong> by 2 raised to power <strong>power of two</strong>, you get the original number. For example, When I run <code>get_whole_number(Math.PI)</code>, I get <strong><code>884279719003555</code> and <code>48</code></strong> since <code>884279719003555/(2**48)</code> is close to <code>Math.PI</code>.</li> <li><code>get_whole_number(0.5)</code> =&gt; <code>1, 1</code></li> </ul> <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>function get_whole_number(number, exponent=0) { if(number%1 == 0) return [number, exponent]; exponent++; number *= 2; if(exponent &gt;= 150) return [Math.round(number), exponent]; return get_whole_number(number, exponent); }; console.time("timer"); let x = get_whole_number(0.1); console.timeEnd("timer"); console.log(x);</code></pre> </div> </div> </p> <p><strong>Is this a good way of writing such a function? Or will it be better if I use bitwise operations rather than <code>modulo</code> and <code>round()</code>?</strong></p> <p>Note: numbers which are irrational in binary will not be represented 100% exactly with this notation, but they are close enough.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T11:50:29.337", "Id": "529662", "Score": "0", "body": "You are hopefully aware that floating point numbers are merely an approximation. Floating point deviations will be enlarged and so on. A typed language might be better, should you run into problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T21:14:11.983", "Id": "531219", "Score": "0", "body": "@JoopEggen \" floating point numbers are merely an approximation.\" --> Detail: All finite floating point numbers are _exact_. It is the code we use that often results in an answer that is an approximation to the math one. Done right, OP's goal is possible with an exactly correct answer when starting with a floating point number. Of course not all textual decimal numbers have a FP encoding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T21:37:05.510", "Id": "531222", "Score": "0", "body": "@chux the set of all floating point numbers does neither correspond with decimal representations, nor is closed to a large degree for all operations. I agree, one could come to some solution. But it is like bookkeeping with Roman numbers: ii+ii=iv; xii/iv=iii." } ]
[ { "body": "<ul>\n<li><p><code>get_whole_number</code> looks like a misnomer. The function does not <em>get a whoe number</em>. Rather, it deconstructs the float into a mantissa and exponent, and returns both. <code>deconstruct_float</code> could be better. Even better is to reuse the names for the <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged &#39;c&#39;\" rel=\"tag\">c</a> standard library, e.g. <code>frexp, frexpf, frexpl</code> (I don't know wether <a href=\"/questions/tagged/javascript\" class=\"post-tag\" title=\"show questions tagged &#39;javascript&#39;\" rel=\"tag\">javascript</a> may tell a <code>float</code> from <code>double</code> from <code>long double</code>).</p>\n</li>\n<li><p><a href=\"/questions/tagged/javascript\" class=\"post-tag\" title=\"show questions tagged &#39;javascript&#39;\" rel=\"tag\">javascript</a> does not support tail recursion optimization. <code>if(exponent &gt;= 150)</code> means that the recursion could be up to 150 levels deep. Better eliminate it manually:</p>\n<pre><code> function get_whole_number(number, exponent=0) {\n while (number%1 != 0 &amp;&amp; exponent &lt; 150) (\n exponent++;\n number *= 2;\n }\n\n if(exponent &gt;= 150) {\n number = Math.round(number);\n }\n return [number, exponent];\n };\n</code></pre>\n</li>\n<li><p>Assuming IEEE-574 format, check out <a href=\"https://blog.codefrau.net/2014/08/deconstructing-floats-frexp-and-ldexp.html\" rel=\"nofollow noreferrer\">this article</a> for the right implementation.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T23:04:52.320", "Id": "268553", "ParentId": "268546", "Score": "1" } }, { "body": "<h2>JavaScript style notes</h2>\n<ul>\n<li>In JS we use <code>camelCase</code> when creating variable names. Avoid using <code>snake_case</code></li>\n<li>Put spaces between operators.</li>\n<li>Delimit all code blocks with <code>{}</code>.</li>\n<li>Dont add <code>;</code> at end of function.</li>\n<li>Use strict equality <code>===</code> rather than <code>==</code></li>\n</ul>\n<p>The name <code>number</code> does not convay the functions intent as well as it could. Maybe the name <code>fraction</code> whould be better.</p>\n<h2>Bug</h2>\n<p>If I call the function incorrectly <code>getWholeNumber(10, 5)</code> it returns the wrong result <code>[10, 5]</code>.</p>\n<p>Should be <code>[10, 0]</code></p>\n<h2>JavaScript and Recursion</h2>\n<p>JavaScript has a limited call stack space (and no tail calling). Any recursive function greatly increases the risk of throwing a call stack overflow error.</p>\n<p>Avoid recursion when possible.</p>\n<h3>Recursion overheads</h3>\n<p>Most often using a loop will also give a significant performance increase over recursion as there is no need to capture the function's state and push and pull it from the call stack.</p>\n<p>The rewrite does a performance comparison. The performance difference will depend on the number you are processing. The example uses square root of 2 with 52 iterations to complete. The non-recursive function is ~ twice as fast</p>\n<h2>Rewrite</h2>\n<p>The rewrite include a performance comparison that runs a recursive and while loop version to compare performance.</p>\n<p>The function <code>getWholeNumber</code> is a rewrite of your original code with a fix for the bug. It can not start with the wrong value of exponent.</p>\n<p>The function <code>wholeNumber</code> uses a while loop rather than recursion.</p>\n<p>The Performance test runs the function many times in batches. The tests are complex and not part of the answer apart from just providing a reliable comparison.</p>\n<p>On faster devices the test may restart several time as it calibrates to the unknown timer resolution.</p>\n<p>See comments for more details on how the performance test works.</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>// Recursive version\nfunction getWholeNumber(fraction) {\n return getWholeNumber(fraction, 0);\n function getWholeNumber(fraction, exponent) {\n if (fraction % 1 === 0) { return [fraction, exponent] }\n exponent++;\n fraction *= 2;\n if (exponent &gt;= 150) { return [Math.round(fraction), exponent] }\n return getWholeNumber(fraction, exponent);\n }\n}\n\n// Using while loop,\nfunction wholeNumber(fraction) {\n var exponent = 0;\n for (; exponent &lt; 150; exponent++) {\n if (fraction % 1 === 0) { return [fraction, exponent] }\n fraction *= 2;\n }\n return [Math.round(fraction), exponent];\n}\n\n\n\n\n\n\n/* Performance testing code */\nconst frac = Math.SQRT2; // Test input value\nconst tests = 100; // Number of cycles. Time is measured over cycle\nvar testCycles = 50; // Tests per cycle\nconst timerResolution = 0.02; // In ms resolution of performance now time.\n // This can be as low as 0.001ms. However FireFox can be up to\n // 0.1ms and Chrome 0.02ms\nconst coolDownTime = 100; // ms between test cycles\n // If you hear fans speeding up during test increase \n // cool down time. CPU may be throttled when cooling fans \n // start up and could introduce a performance bias. \nconst warmupCount = 20; // This lets the optimize get a good look at the running\n // code before we start timing the function\nconst times = [0, 0]; // Holds total times in ms;\nvar restart = false;\nvar cycles = 0; // Counts cycles. \n\nrestarter(); // Starts performance test and\nfunction restarter() { // restarts if there is a time resolution error\n container.classList.toggle(\"error\", false);\n restart = false;\n cycles = -warmupCount;\n times[0] = times[1] = 0;\n test();\n}\nfunction resolutionError(time) {\n const timeFix = Math.max(timerResolution * 0.2, time);\n testCycles = Math.ceil(testCycles * (timerResolution / timeFix)) + 20;\n restart = true; \n log.textContent = \"Timer resolution ERROR!!!. Cycles reset to: \" + testCycles;\n logA.textContent = \"Time \" + time + \"ms per \" + testCycles + \" calls\";\n container.classList.toggle(\"error\", true);\n}\n\nfunction runTest(func, val) { \n var i = 0;\n const now = performance.now();\n for(; i &lt; testCycles; i++) { func(val) }\n const time = performance.now() - now;\n if (time &lt; timerResolution) { resolutionError(time) } \n return time;\n}\nfunction test() {\n if (cycles &lt; tests) { \n if (cycles === 0) { times[0] = times[1] = 0 }\n if (Math.random() &lt; 0.5) { // Avoid optimizor and CPU throttling bias \n // by changing call order\n times[0] += runTest(wholeNumber, frac);\n times[1] += runTest(getWholeNumber, frac);\n } else {\n times[1] += runTest(getWholeNumber, frac);\n times[0] += runTest(wholeNumber, frac);\n }\n\n if (restart) {\n logB.textContent = \"Timer resolution Error\";\n setTimeout(restarter, 1000); \n return;\n } \n if (cycles &lt; 0) {\n log.textContent = \"Warm-up count down: \" + cycles;\n } else {\n log.textContent = ((cycles / tests) * 100).toFixed(1) + \"% complete\";\n logA.textContent = \"While loop time: \" + times[0].toFixed(1) + \"ms\";\n logB.textContent = \"Recursive time: \" + times[1].toFixed(1) + \"ms\";\n }\n cycles ++;\n setTimeout(test, coolDownTime);\n } else {\n log.textContent = \"Completed \" + (cycles * testCycles) + \" tests\";\n logA.textContent = \"While loop total time: \" + times[0].toFixed(1) + \"ms Mean: \" + \n (times[0] / (tests * testCycles)).toFixed(5) + \"ms per call\";\n logB.textContent = \"Recursive total time: \" + times[1].toFixed(1) + \"ms Mean: \" + \n (times[1] / (tests * testCycles)).toFixed(5) + \"ms per call\";\n\n console.log(\"While loop result: \" + wholeNumber(frac));\n console.log(\"Recursive loop result: \" + getWholeNumber(frac));\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#container {\n width: 80%;\n border: 2px solid green;\n padding: 4px;\n}\n.error {\n border-color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"container\"&gt;\n&lt;code id=\"log\" &gt;&lt;/code&gt;&lt;br&gt;\n&lt;code id=\"logA\"&gt;&lt;/code&gt;&lt;br&gt;\n&lt;code id=\"logB\"&gt;&lt;/code&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T17:35:02.017", "Id": "529692", "Score": "0", "body": "*Should be [10, 0]* - that would be wrong because you passed `10` with binary exponent `5` into the function, which is `320` and not `10`. Explanation: `10*2**5 = 320 ≠ 10*2**0`. I really like the idea of the for loop increasing the exponent though, I didn't think of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T17:42:09.223", "Id": "529693", "Score": "0", "body": "And as for semicolons after function declarations, it was a mistake, because I'm used to declaring functions as expressions, which is a statement. I appreciate that normal declaration however is not a statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T18:45:49.083", "Id": "529696", "Score": "0", "body": "@AlphaHowl Using the comment as correct with [10,5] correctly returning [10,5] The result of `get_whole_number(2.5, 2)` returns [5,3]` one expects [10,0] With either expectation (answer or comment) the `exponent` is being incorrectly handled if given in some situations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:15:28.123", "Id": "529743", "Score": "0", "body": "yeah, you're right. Originally though, I only created the argument `exponent=0` just so that the recursion would work. It was not designed to be passed into the function at the first recursion (ie by the user), only after that by the function itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:19:46.117", "Id": "529745", "Score": "0", "body": "Also, I would like to ask one last question: is there an advantage of using pascal case or camel case over snake case? Does it cause any errors, or is it just a standard expectation of other programmers who may want to read my code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:26:23.203", "Id": "529746", "Score": "0", "body": "I had a read of some sites, notably [this one](https://betterprogramming.pub/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841), where it says *There is no best method of combining words. The main thing is to be consistent*, and *This style [snake_case], when capitalized, is often used as a convention in declaring constants in many languages. When lower cased, it is used conventionally in declaring database field names*. I prefer snake case for functions and important variables, and I am consisten with this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T18:32:57.870", "Id": "529761", "Score": "0", "body": "@AlphaHowl You can use any naming style you wish. `camelCase` is the style used by the JS API's." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T16:26:26.893", "Id": "268573", "ParentId": "268546", "Score": "1" } }, { "body": "<p>This is only from a <em>floating point</em> point-of-view.</p>\n<hr />\n<p>The 150 in <code>if(exponent &gt;= 150)</code> is a unqualified magic number.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"nofollow noreferrer\">binary64</a> can encode values with greater exponent needs like 1.0*2<sup>-1074</sup>. Perhaps use:</p>\n<pre><code>if (exponent &gt;= 1074)\n</code></pre>\n<hr />\n<p>I suggest testing with the usual edge case suspects:</p>\n<pre><code>0.0 \n-0.0 // minus 0\n2.2250738585072014E-308 // Smallest non-zero normal\n4.9406564584124654E-324 // Smallest non-zero\n1.7976931348623157E+308 // Max\n-1.7976931348623157E+308 // Min\nNaN // Some not-a-number (tricky to set this one up)\n</code></pre>\n<p>Perhaps some random numbers too.</p>\n<pre><code>42.0 // The answer to everything\n-4442 // AKA 867-5309\n</code></pre>\n<hr />\n<blockquote>\n<p>Note: numbers which are irrational in binary will not be represented 100% exactly with this notation, but they are close enough.</p>\n</blockquote>\n<p>Note that all binary64 finite values are <em>rational</em>.</p>\n<p>I think OP wanted something like: &quot;numbers which are not exactly repeatable in binary will not ... &quot;</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Irrational_number\" rel=\"nofollow noreferrer\">irrational</a> has a differnt meaning.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:56:45.887", "Id": "269269", "ParentId": "268546", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:25:23.717", "Id": "268546", "Score": "0", "Tags": [ "javascript", "floating-point" ], "Title": "Convert a fraction into a whole number and a binary exponent (eg 3.125 => 25, 3)" }
268546
<p>I came upon <a href="https://www.youtube.com/watch?v=5xuvqBjRkok" rel="nofollow noreferrer">this</a> Youtube video and the problem they discussed piqued my interest, so I decided to take a stab at it. Below is the question:</p> <blockquote> <p>Given an array of unique characters <code>arr</code> and a string <code>str</code>, implement a function, <code>getShortestUniqueSubstring </code> that finds the smallest substring of <code>str</code> containing all the characters in <code>arr</code>. Return <code>&quot;&quot;</code> (empty string) if such a substring doesn't exist.</p> <p>Come up with an asymptotically optimal solution and analyze the time and space complexities.</p> <p><strong>Example:</strong></p> <pre><code>input: arr = ['x','y','z'], str = &quot;xyyzyzyx&quot;` output: &quot;zyx&quot;` </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><p><strong>[time limit]</strong> 5000ms</p> </li> <li><p><strong>[input] array.character</strong> <code>arr</code></p> <ul> <li>1 &lt;= <code>arr.Length</code> &lt;= 30</li> </ul> </li> <li><p><strong>[input] string</strong> <code>str</code></p> <ul> <li>1 &lt;= <code>str.Length</code> &lt;= 500</li> </ul> </li> </ul> </blockquote> <p>Below is my implementation (in C#):</p> <pre><code>using System; using System.Collections.Generic; public class Program { public static void Main() { char[] arr = new char[] {'x','y','z'}; string str = &quot;xyyzyzyx&quot;; Console.WriteLine(GetShortestUniqueSubstring(arr, str)); char[] arr2 = new char[] {'a','b','c', 'd'}; string str2 = &quot;bbacabdaccdabad&quot;; Console.WriteLine(GetShortestUniqueSubstring(arr2, str2)); } public static string GetShortestUniqueSubstring(char[] chars, string str) { int expectedAsciiSum = 0; Dictionary&lt;char, int&gt; charAndCodeDict = new Dictionary&lt;char, int&gt;(); for(int i=0; i &lt; chars.Length; i++) { char c = chars[i]; int asciiCode = (int)c; expectedAsciiSum+= asciiCode; charAndCodeDict.Add(c, asciiCode); } int asciiSum=0; string result=&quot;&quot;; foreach(char c in str) { if (charAndCodeDict.TryGetValue(c, out int currentCode)){ charAndCodeDict.Remove(c); asciiSum+=currentCode; result=c+result; if(asciiSum == expectedAsciiSum){ return result; } } } return result; } } </code></pre> <p>You will notice that I have omitted some sanity check(s) and error handling (e.g. checking if an key already exists in <code>charAndCodeDict</code> before adding), because in this context, I am strictly adhering to the constraints listed in the question. In a production environment, I would obviously add the appropriate checks and/or throw <code>Exceptions</code> when needed.</p> <p>Now, I am no computer scientist, but it looks to me like the time complexity is roughly <code>O(n+m)</code> where <code>n</code> == number of characters in <code>arr</code> and <code>m</code> == the number characters in <code>str</code>. Lookups to any dictionary are completed in constant time (<code>O(1)</code>), so that shouldn't impact speed, although, the memory allocation and building of it would.</p> <p>Is there anything that can be done to make my implementation more efficient? Aside from that, if there is a more efficient way of doing this that takes a completely different approach, please do let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T04:45:41.687", "Id": "529623", "Score": "0", "body": "In your code, `arr = new char[] {'x','y','z'}; str = \"xxyyzz\";` results in `zyx`. I don't see how `zyx` (or `xyz` after fixing a trivial bug) can be a substring of `xxyyzz`." } ]
[ { "body": "<h2>Algorithm issue 1</h2>\n<p>Your code is not correct. You're not getting the substrings. You're getting a list of the first occurrence of each character, and pasting those values together (in reverse order, for some reason) as if they were a substring.</p>\n<p>Try the following test case:</p>\n<pre><code>char[] arr1 = new char[] {'x','y','z'};\nstring str1 = &quot;zzyyxxzy&quot;; \nConsole.WriteLine(GetShortestUniqueSubstring(arr1, str1));\n</code></pre>\n<p><em>I'm going to refer to this test case repeatedly.</em></p>\n<p>The found substring should be <code>zzyyx[xzy]</code>, but your result is <code>xyz</code>.</p>\n<p>Notice what happens when I change <code>str</code> from <code>[zzyy]xxzy</code> to <code>[yyzz]xxzy</code>. The result is now <code>xzy</code>. That doesn't make sense. I changed something that is not part of the substring that should (allegedly) be returned, yet the returned (alleged) substring is somehow different now. What gives?</p>\n<p>What you missed here is that <strong>substrings are contiguous</strong>. They do not allow breaks or gaps.</p>\n<p>If you follow the code example I gave, you will see that the <code>xyz</code> result is based off of input string <code>[z]z[y]y[x]xzy</code>, and you concatenate these occurrences in reverse order.</p>\n<p>An easy way to troubleshoot this is to log the index of every &quot;hit&quot; you find. I adjusted your code to track this:</p>\n<pre><code>int asciiSum=0;\nstring result=&quot;&quot;; \nint counter = 0; // HERE\nforeach(char c in str) \n{ \n counter++; // HERE\n\n if (charAndCodeDict.TryGetValue(c, out int currentCode)){\n charAndCodeDict.Remove(c); \n asciiSum+=currentCode;\n result=c+result;\n \n // HERE\n Console.WriteLine($&quot;Hit: Character '{c}' in position {counter}&quot;);\n \n if(asciiSum == expectedAsciiSum){\n return result;\n }\n }\n}\n</code></pre>\n<p>For the input example I provided:</p>\n<blockquote>\n<p>Hit: Character 'z' in position 1<br />\nHit: Character 'y' in position 3<br />\nHit: Character 'x' in position 5<br />\nxyz</p>\n</blockquote>\n<p>The result would only be a substring if all logged positions were sequential, which they are not.</p>\n<p>I'll leave the exercise on how to fix this up to you. Use the logging I added here as a quick way to confirm that your code works as expected.</p>\n<hr />\n<h2>Algorithm issue 2</h2>\n<p>Your code only works when <code>chars</code> contains no duplicate characters, but that's an unnecessary constraint. The question does not exclude the possibility of duplicates, and they should factor into your algorithm. E.g. <code>new char[] {'x','y','z', 'z' }</code> should yield a four-or-more-letter substring with 1 x, 1 y and 2 z characters (and any additional characters if part of the shortest available substring).</p>\n<hr />\n<h2>LINQ</h2>\n<p>LINQ helps clean up code that deals with iterations, and makes it far more readable.</p>\n<p>For example, your dictionary-building logic can be replaced with:</p>\n<pre><code>var charAndCodeDict = chars\n .Distinct()\n .ToDictionary(\n c =&gt; c, // Key = the character itself \n c =&gt; (int)c // Value = the character as an int\n );\n\nint expectedAsciiSum = chars.Sum(c =&gt; (int)c);\n</code></pre>\n<p>I added extra line breaks to make it easier to parse the methods and their arguments.</p>\n<p>Explanation:</p>\n<ul>\n<li>LINQ operates on collections, but <code>string</code> inherently gets treated as a <code>char[]</code> so it does count as a collection.</li>\n<li><code>Distinct</code> removes duplicates, which is important to avoid conflicts when generating a dictionary (colliding keys).</li>\n<li><code>ToDictionary</code> needs two parameters: how to select the key, and how to select the value. This logic is applied to each element in the input array, and <code>ToDictionary</code> then returns the compiled dictionary from all these cases.</li>\n<li><code>Sum</code> adds all of the selected values together and returns, well, the sum.</li>\n</ul>\n<p>You might find it complex because you're not used to LINQ, but once you know what each of the LINQ methods do (there's about 10 commonly used ones), it really helps trim down the character count and ease the readability.</p>\n<hr />\n<h2>String concatenation</h2>\n<pre><code>result=c+result;\n</code></pre>\n<p><code>+</code> is not a good way to concatenate strings. It works but it becomes horribly inefficient when used repeatedly.</p>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings\" rel=\"nofollow noreferrer\">There are better ways to concatenate strings</a>. Especially when dealing with more than one or two <code>+</code> concatenations, you should really look at the others.</p>\n<p>In this case, I would recommend either using a <code>StringBuilder</code>, or simply tracking a <code>char[]</code> and only joining it into a string at the end of the method (not during each iteration for every character).</p>\n<hr />\n<h2>Submethods</h2>\n<p>Your <code>GetShortestUniqueSubstring</code> has two distinct sections: generating a dictionary, and processing the input string. These are two separate things and could/should have been separated into their own method.</p>\n<p>Note that this applies because your dictionary-building logic is more than a simple one liner. If you used my LINQ example, this point would be rendered moot, <strong>unless</strong> there is a reusability argument that still suggests putting this dictionary-building logic into a method of its own.</p>\n<hr />\n<h2>Overall syntax</h2>\n<p>Overall, your syntax is good. Relatively clear naming (maybe a bit too lengthy at times, but it's better than being too terse).</p>\n<p>The only thing that stands out are the <a href=\"https://blog.codinghorror.com/new-programming-jargon/\" rel=\"nofollow noreferrer\">egyptian brackets</a> you're using, which is not idiomatic in C#. In C#, the opening bracket goes on a new line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T19:27:27.150", "Id": "529966", "Score": "0", "body": "Some good points. I have addressed some of your comments/concerns in my answer below." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T10:56:41.123", "Id": "268562", "ParentId": "268547", "Score": "4" } }, { "body": "<p>I ended up getting really busy, so I wasn't able to respond as quickly as I had hoped. Saying that, @flater pointed out that I wasn't generating actual substrings, which is true, and I attribute that to my misinterpretation of the question. Realizing this prompted me to re-write the algorithm entirely (which I almost believe is worth asking a separate question about, but I decided to just add it as an answer), which I will outline below:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace AlgoTest\n{\n public class Program\n {\n public static void Main()\n {\n //Base Case test\n char[] arr = new char[] { 'x', 'y', 'z' };\n string str = &quot;xyyzyzyx&quot;;\n Console.WriteLine(GetShortestUniqueSubstring(arr, str));\n\n //Longer String Test\n char[] arr2 = new char[] { 'a', 'b', 'c', 'd' };\n string str2 = &quot;bbacabdaccdabad&quot;;\n Console.WriteLine(GetShortestUniqueSubstring(arr2, str2));\n\n //Duplicate chars test\n char[] arr3 = new char[] { 'd', 'a', 'c', 'c' };\n Console.WriteLine(GetShortestUniqueSubstring(arr3, str2));\n\n //Duplicate chars that CANNOT be found in str2\n char[] arr4 = new char[] { 'b', 'b', 'a', 'd', 'd' };\n Console.WriteLine(GetShortestUniqueSubstring(arr4, str2));\n\n Console.ReadKey();\n }\n\n public static string GetShortestUniqueSubstring(char[] chars, string str)\n {\n int charsLen = chars.Length;\n\n int expectedAsciiSum = 0;\n IDictionary&lt;char, int&gt; charAndCodeDict = new Dictionary&lt;char, int&gt;();\n for (int i = 0; i &lt; charsLen; i++)\n {\n char c = chars[i];\n int asciiCode = (int)c;\n expectedAsciiSum += asciiCode;\n\n if (!charAndCodeDict.ContainsKey(c))\n {\n charAndCodeDict.Add(c, asciiCode);\n }\n }\n\n return GetShortestSubstring(charsLen, expectedAsciiSum, charAndCodeDict, str);\n }\n\n private static string GetShortestSubstring(int maxCharLen, int expectedAsciiSum, IDictionary&lt;char, int&gt; charAndCodeDict, string str, int startPos = 0)\n {\n StringBuilder builder = new StringBuilder();\n\n int strLen = str.Length;\n int totalSearchChars = startPos + strLen;\n\n int counter = 0;\n int asciiSum = 0;\n for (int i = startPos; i &lt; strLen; i++)\n {\n counter++;\n\n /*\n if the distance between the totalSearchChars and the\n current position in the string is less than the maxCharLen,\n then the total number of remaining characters left to check \n (i.e. i to (strLen - 1)) cannot be a substring\n */\n if ((totalSearchChars - i) &gt;= maxCharLen)\n {\n char c = str[i];\n\n /*\n In some cases, the 'asciiSum' of several characters could amount\n to the 'expectedAsciiSum', even if some of the characters that make\n up the 'asciiSum' are not found in the original char array,\n so we need to that check the current char (i.e. c) exists first\n */\n if (charAndCodeDict.TryGetValue(c, out int currentCode))\n {\n if (counter &lt;= maxCharLen)\n {\n asciiSum += currentCode;\n builder.Append(c);\n\n if (counter == maxCharLen)\n {\n if (asciiSum == expectedAsciiSum)\n {\n return builder.ToString();\n }\n\n counter = 0;\n asciiSum = 0;\n builder.Clear(); \n }\n }\n }\n else\n {\n counter = 0;\n asciiSum = 0;\n builder.Clear();\n }\n }\n else\n {\n return GetShortestSubstring(maxCharLen, expectedAsciiSum, charAndCodeDict, str, startPos + 1);\n }\n }\n\n return builder.ToString();\n }\n\n }\n}\n</code></pre>\n<p>You will notice that I split the search for the actual sub string into a separate recursive function called <code>GetShortestSubstring</code>. This was done to support the separation of concerns as well as to allow recursion. Essentailly, <code>GetShortestSubstring</code> does the follolwing:</p>\n<ol>\n<li>Loops through the <code>str</code> starting from the leftmost position (i.e. <code>startPos</code>) and, counting each iteration.</li>\n<li>Checks if the distance between the <code>totalSearchChars</code> and the current position in the string (i.e. <code>i</code>), is &gt;= the total number of characters in the original <code>arr</code> (i.e. <code>maxCharLen</code>). If not, then total number of characters left to check, will be less than the <code>maxCharLen</code>, which could never match a substring derived from the <code>arr</code>, so we need to start over searching from the <code>startPos + 1</code> using recursion.</li>\n<li>Looks in the <code>charAndCodeDict</code> to see if the current character (i.e. <code>c</code>) matches any of the ones found in the original <code>arr</code> and returns its ascii code. If <code>c</code> is not found, then reset the <code>counter</code>, <code>asciiSum</code>, and <code>builder</code>.</li>\n<li>Checks that the current iteration count (i.e. <code>counter</code>) is &lt; the <code>maxCharLen</code> and if so increments the <code>asciiSum</code> and appends <code>c</code> to the <code>builder</code>.</li>\n<li>If <code>counter == maxCharLen</code> then check to see if the <code>asciiSum == expectedAsciiSum</code> and if so return the underlying sting from the <code>builder</code>, otherwise reset the <code>counter</code>, <code>asciiSum</code>, and <code>builder</code>, and continue the loop.</li>\n</ol>\n<p>The problem actually does explicitly state that <code>arr</code> should not contain duplicates in the first line:</p>\n<blockquote>\n<p>Given an array of unique characters <code>arr</code></p>\n</blockquote>\n<p>However, I do agree this is an unnecessary constraint. As for comments regarding <code>LINQ</code> (which I am very familiar with), I disagree in this context. I believe than an algorithm should be reproducible in virtually any programming language, and I prefer to keep the implementation as explicit (and language/platform agnostic) as possible. Additionally, (and in this context) <code>LINQ</code> would merely be syntatic sugar in place of standard <code>for</code> loops, which are faster (albeit more verbose) anyway. Speaking of speed, I also agree that concatenations performed in a loop are better done with an instance of a <code>StringBuilder</code> (especially when the <code>arr</code> is sufficiently large), regardless of the overhead of encountered upon instantiation. Notice also that I changed the placing of my brackets to conform to more idiomatic C# syntax. I do not normally use <a href=\"https://blog.codinghorror.com/new-programming-jargon/\" rel=\"nofollow noreferrer\">Egyption Brackets</a>, but I used them in my question to shorten the code block to prevent viewers from having to scroll unnecessarily. The one idiomatically placed bracket in the second <code>foreach</code> is evidence of an oversight in my futile attempt to reduce the size of the code block.</p>\n<p>Even with the re-write, I am still not convinced that this is the most efficient implementation....and it also doesn't look as pretty (specifically the variable resets). Any suggestions to make this more efficient (and &quot;prettier&quot; short of using <code>LINQ</code>) are welcome.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T19:26:09.870", "Id": "268701", "ParentId": "268547", "Score": "0" } } ]
{ "AcceptedAnswerId": "268701", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T17:32:55.440", "Id": "268547", "Score": "2", "Tags": [ "c#", "performance", "algorithm", "strings" ], "Title": "Algorithmic Efficiency: GetShortestUniqueSubstring implementation" }
268547
<p>After finally having enough of the hacky batch-based workflow for a project, I tried &quot;porting&quot; it to Maven. This is my first time using a build tool for Java, so there's probably a lot of room for improvement.</p> <h3>General setup</h3> <pre><code>B:\WORKSPACE\COM.MSGPROGRAMS.AUDIRAS │ .classpath │ .project │ icon.ico // icon used for the exe │ LICENSE │ LICENSE-mp3agic │ pom.xml │ README.md │ RELEASE.txt │ UPDATES.txt │ ├───.settings │ // eclipse data │ ├───src │ ├───main │ │ ├───java │ │ │ └───com/msgprograms/audiras │ │ │ └─ // source, not relevant │ │ │ │ │ └───resources │ │ icon.png // icon used for the tray icon │ │ lang_deu.txt │ │ lang_eng.txt │ │ streams.txt │ │ │ ├───packaging │ │ jpack-appimg-args.txt │ │ jpack-installer-args.txt │ │ │ └───test │ └─── // not relevant │ └───target ├───appimg ├───appimg-work ├───installer-work ├───jar ├───packaging └─── // omitted standard dirs, these are the dirs that are used while creating the installer at some point Audiras-2.0.0.msi // installer to be uploaded somewhere </code></pre> <h3>pom.xml</h3> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.msgprograms&lt;/groupId&gt; &lt;artifactId&gt;com.msgprograms.audiras&lt;/artifactId&gt; &lt;version&gt;2.0.0&lt;/version&gt; &lt;name&gt;com.msgprograms.audiras&lt;/name&gt; &lt;url&gt;https://github.com/msg-programs/Audiras&lt;/url&gt; &lt;description&gt;Minimalistic internet radio recorder&lt;/description&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;maven.compiler.source&gt;16&lt;/maven.compiler.source&gt; &lt;maven.compiler.target&gt;16&lt;/maven.compiler.target&gt; &lt;java.version&gt;16&lt;/java.version&gt; &lt;!-- properties for jpackage to read --&gt; &lt;appName&gt;Audiras&lt;/appName&gt; &lt;appVendor&gt;msg-programs&lt;/appVendor&gt; &lt;mainClass&gt;com.msgprograms.audiras.RadioMain&lt;/mainClass&gt; &lt;winUpgradeUUID&gt;d8cd072d-c607-44aa-b2aa-53bf096aba9a&lt;/winUpgradeUUID&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.mpatric&lt;/groupId&gt; &lt;artifactId&gt;mp3agic&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;!-- jpackage arg files. need to be filtered first --&gt; &lt;directory&gt;${project.basedir}/src/packaging&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;targetPath&gt;${project.build.directory}/packaging&lt;/targetPath&gt; &lt;/resource&gt; &lt;resource&gt; &lt;!-- default resource dir needs to be re-added --&gt; &lt;directory&gt;${project.basedir}/src/main/resources&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;!-- output to directory. jpackage can't read singular files for input arg --&gt; &lt;outputDirectory&gt;${project.build.directory}/jar&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-install-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;!-- don't install locally --&gt; &lt;skip&gt;true&lt;/skip&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;io.github.wiverson&lt;/groupId&gt; &lt;artifactId&gt;jtoolprovider-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;!-- first pass in package phase. --&gt; &lt;!-- create the files that will be installed (&quot;application image&quot;) --&gt; &lt;!-- use appimg-work as temp, result goes into appimg --&gt; &lt;execution&gt; &lt;id&gt;jpack-appimg&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;java-tool&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;toolName&gt;jpackage&lt;/toolName&gt; &lt;failOnError&gt;true&lt;/failOnError&gt; &lt;args&gt;@${project.build.directory}\packaging\jpack-appimg-args.txt&lt;/args&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;execution&gt; &lt;!-- second pass in install phase. --&gt; &lt;!-- build an installer (&quot;application package&quot;) --&gt; &lt;!-- use installer-work as temp, result goes into the build dir --&gt; &lt;id&gt;jpack-installer&lt;/id&gt; &lt;phase&gt;install&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;java-tool&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;toolName&gt;jpackage&lt;/toolName&gt; &lt;failOnError&gt;true&lt;/failOnError&gt; &lt;args&gt;@${project.build.directory}\packaging\jpack-installer-args.txt&lt;/args&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;com.coderplus.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;copy-rename-maven-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;!-- copy licenses and other files into app image --&gt; &lt;!-- run between package and install phase of jpackage --&gt; &lt;id&gt;copy-files&lt;/id&gt; &lt;phase&gt;verify&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;fileSets&gt; &lt;fileSet&gt; &lt;sourceFile&gt;${project.basedir}\LICENSE&lt;/sourceFile&gt; &lt;destinationFile&gt;${project.build.directory}\appimg<span class="math-container">\${appName}\LICENSE.txt&lt;/destinationFile&gt; &lt;/fileSet&gt; &lt;fileSet&gt; &lt;sourceFile&gt;${project.basedir}\LICENSE-mp3agic&lt;/sourceFile&gt; &lt;destinationFile&gt;${project.build.directory}\appimg\$</span>{appName}\LICENSE-mp3agic.txt&lt;/destinationFile&gt; &lt;/fileSet&gt; &lt;fileSet&gt; &lt;sourceFile&gt;${project.basedir}\RELEASE.txt&lt;/sourceFile&gt; &lt;destinationFile&gt;${project.build.directory}\appimg<span class="math-container">\${appName}\RELEASE.txt&lt;/destinationFile&gt; &lt;/fileSet&gt; &lt;fileSet&gt; &lt;sourceFile&gt;${project.basedir}\UPDATES.txt&lt;/sourceFile&gt; &lt;destinationFile&gt;${project.build.directory}\appimg\$</span>{appName}\UPDATES.txt&lt;/destinationFile&gt; &lt;/fileSet&gt; &lt;/fileSets&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-clean-plugin&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.2&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.8.0&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0-M5&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.2&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-install-plugin&lt;/artifactId&gt; &lt;version&gt;2.5.2&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;io.github.wiverson&lt;/groupId&gt; &lt;artifactId&gt;jtoolprovider-plugin&lt;/artifactId&gt; &lt;version&gt;1.0.34&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;com.coderplus.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;copy-rename-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p><a href="https://github.com/wiverson/jtoolprovider-plugin" rel="nofollow noreferrer">jtoolprovider docs</a>. It's a straightforward way of running java tools such as jlink, jdeps or jpackage via Maven.</p> <h3>jpack-installer-args.txt</h3> <pre><code>--type msi --app-version ${project.version} --copyright &quot;(C) ${appVendor}&quot; --description &quot;${project.description}&quot; --name ${appName} --dest ${project.build.directory} --temp ${project.build.directory}\installer-work --vendor ${appVendor} --app-image ${project.build.directory}\appimg\${appName} --win-dir-chooser --win-menu --win-menu-group ${appVendor} --win-upgrade-uuid ${winUpgradeUUID} </code></pre> <h3>jpack-appimg-args.txt</h3> <pre><code>--type app-image --name ${appName} --dest ${project.build.directory}\appimg --temp ${project.build.directory}\appimg-work --input ${project.build.directory}\jar --icon ${project.basedir}\icon.ico --main-jar ${project.build.directory}\jar\${project.build.finalName}.jar --main-class ${mainClass} </code></pre> <h3>Building the installer</h3> <ol> <li>Build the jar into target/jar (phase compile)</li> <li>Use the jar to build an app image into target/appimg (phase package)</li> <li>Move other files such as licenses and update infos into the app image (phase verify)</li> <li>Use the app image to build an installer into target (phase install)</li> </ol> <br> <hr /> <br> Any feedback is welcome, be it regarding Maven projects in general or my installer building in particular.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T18:24:03.763", "Id": "268549", "Score": "1", "Tags": [ "java", "maven" ], "Title": "Building a native package using Maven" }
268549
<p>I am attempting to write a light script to deal with multiple package installation in Octave. The available packages can be checked in <a href="https://octave.sourceforge.io/packages.php" rel="nofollow noreferrer">Octave Forge</a> or <a href="https://en.wikipedia.org/wiki/GNU_Octave#Packages" rel="nofollow noreferrer">wikipedia</a>. For example, if the packages <code>data-smoothing</code>, <code>fuzzy-logic toolkit</code>, <code>image</code>, <code>image-acquisition</code>, <code>parallel</code>, <code>statistics</code> and <code>video</code> are needed to be installed, list these package names into <code>Packages</code> collection, such as:</p> <pre><code>Packages{1} = &quot;data-smoothing&quot;; Packages{2} = &quot;fuzzy-logic toolkit&quot;; Packages{3} = &quot;image&quot;; Packages{4} = &quot;image-acquisition&quot;; Packages{5} = &quot;parallel&quot;; Packages{6} = &quot;statistics&quot;; Packages{7} = &quot;video&quot;; </code></pre> <p>Then pass it into <code>InstallPackages</code> function.</p> <pre><code>InstallPackages(Packages); </code></pre> <p><strong>The experimental implementation</strong></p> <pre><code>function [] = InstallPackages(Packages) for i = 1:size(Packages, 2) try fprintf(&quot;Package %s is about to be installed!\n&quot;, Packages{1, i}); pkg('install', '-forge', Packages{1, i}); catch (exception) fprintf(&quot;Package %s installation failed!\n&quot;, Packages{1, i}); end endfor end </code></pre> <p>All suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T00:43:47.447", "Id": "529712", "Score": "1", "body": "You don’t need `eval`, you can just do `pkg('install', '-forge', Packages{1, i})`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T23:46:01.533", "Id": "529903", "Score": "0", "body": "@Cris Luengo Thank you for the suggestion. Already updated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T23:48:53.533", "Id": "268554", "Score": "0", "Tags": [ "strings", "error-handling", "installer", "octave" ], "Title": "Batch installing packages script in Octave" }
268554
<p>The <code>sep</code> function separates <code>string</code> by the characters of <code>seps</code>, but it escapes the separates that are in quotes, like:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; sep(&quot;a b c d 'e f' g h&quot;, ' ') ['a', 'b', 'c', &quot;'e f'&quot;, 'g', 'h'] </code></pre> <pre class="lang-py prettyprint-override"><code>def sep(string: str, *seps: str): res = [] cur = &quot;&quot; s = False for c in string: if c == &quot;'&quot;: s = not s # Q if not s and c in seps: res.append(cur); cur = &quot;&quot; else: cur += c res.append(cur) return res </code></pre> <p>I'm using this function for a while and it works great, but it gets really slow on long strings. Of course, because it loops through the whole string. I've trying to make it fast but I failed. So I want to know how the performance of my code can be improved.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:38:00.557", "Id": "529667", "Score": "3", "body": "Have you looked at profiling your function as starting point? https://docs.python.org/3/library/profile.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T15:18:44.393", "Id": "529681", "Score": "0", "body": "@Cam No before I didn't, just now I did what it says in the document. But what data should I include in the question from the result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T21:29:53.693", "Id": "529710", "Score": "1", "body": "What is the expected output of `sep(\"a b'c' d\", ' ')`? Note: no space after the `b`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T02:48:32.700", "Id": "529718", "Score": "0", "body": "@RootTwo It gives the expected answer, `['a', \"b'c'\", 'd']`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:32:46.177", "Id": "529747", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>There are a couple of different ways you might want to explore if you're looking for optimization opportunities here.</p>\n<p>To start off, consider that if you have <code>&quot;a b c d 'e f' g h&quot;</code> as an input string, you can save yourself a potentially hefty amount of effort simply skipping over the entire quoted substring. In other words, if you start with <code>text = &quot;a b c d 'e f' g h&quot;</code> and you split it using the single quote as the separator, you immediately break off all of the pieces you don't need to process.</p>\n<pre><code>&gt;&gt;&gt; text = &quot;a b c d 'e f' g h&quot;\n&gt;&gt;&gt; text.split(&quot;'&quot;)\n['a b c d ', 'e f', ' g h']\n</code></pre>\n<p>From this point, all you really need to do is keep track of whether you're dealing with a quoted substring or not. If you are, just add it to the list of substrings (I added the single quotes around them like you did, although I'm not really sure what the purpose of that is). If you're not, go ahead and split the string using the separators like you normally would.</p>\n<p>This is what I came up with. I actually started out with a super-complicated solution when I thought of the quoted-substring shortcut.</p>\n<pre><code>from string import whitespace\nfrom typing import List, Text\n\n\ndef separate_substrings(input_string: Text, *separators: Text) -&gt; List[Text]:\n &quot;&quot;&quot;Split an input string based on the specified separators.\n \n The `separate_substrings` function correctly handles quoted substrings\n within the input string, returning the entire contents of a quote as a\n single quoted lexeme.\n\n Parameters\n ----------\n input_string : Text\n The `input_string` parameter contains the entire contents which are to\n be lexed.\n \n separators : text\n The `separators` argument is a list of delimiters which mark the end of\n one lexeme and the start of another.\n \n &quot;&quot;&quot;\n # If the user forgets to specify the separators, the separators object will\n # be empty, and this will trigger a ValueException. To save everyone trouble\n # and heartache, if the separators object is empty, we will simply return\n # the input string as is.\n if not len(separators):\n # Just go ahead and return the input string as is without doing anything\n # to the input string first.\n return [input_string]\n\n # Initialize the partitions sequence container object.\n partitions: List[Text] = []\n\n # Determine whether the first non-separator character in the input string\n # is a quote character. This will determine how we alternate between\n # subgroups within the input string.\n for character in input_string:\n # Since the first thing we did was trim the input string, there should\n # be no need to skip whitespace. We're always looking out for trouble,\n # though, so you never know.\n if character in whitespace:\n # Move on to the next character in the input string until we hit\n # a non-whitespace character.\n continue\n \n # Make a note of wether the first character we hit is a quote.\n in_quote = True if character == &quot;'&quot; else False\n\n # Now that we've settled that, we can break out of this loop.\n break\n\n # You already know that the quote character is the\n # delimiter demarcating substrings, so simply split the\n # input string using the same quote character.\n substrings: List[Text] = input_string.split(&quot;'&quot;)\n\n # Iterate over the substrings of the input string and process all of the\n # input string partitions that are not quoted substrings.\n for substring in substrings:\n # Trim each substring before processing so we don't get stuck with zero-\n # length strings in-between elements here and there.\n substring = substring.strip()\n\n # Check whether we actually need to do anything for this substring. If\n # we're in a quoted substring, we can skip this step.\n if not in_quote:\n # First, split the substring using whitespace as the delimiter.\n for element in substring.split(*separators):\n # Add each individual element within the substring to the\n # input string partitions container.\n partitions.append(element)\n # If we are in a quoted substring, all we need to do is add it to the\n # input string partitions sequence container object.\n else:\n # Add the substring to the input string partitions container. I'm\n # not really sure why the quotes are necessary in and of themselves\n # (haven't they done their job by the mere fact that we didn't split\n # that substring?), but the question specifically included quotes\n # in the output, so here we go.\n partitions.append(f&quot;'{substring}'&quot;)\n \n # Flip the sentinel value to make sure we do/don't process the next\n # substring, as necessary.\n in_quote = not in_quote\n\n # Now simply return the sequence container containing\n # the substring partitions.\n return partitions\n</code></pre>\n<p>With that initial heuristic out of the way, I think the next obvious step is to refactor the function as a generator. The resulting list could be absolutely massive depending on the size of your input string, and processing the entire thing to build a list means you basically need everything in memory at the same time.</p>\n<p>This is a reworked version of my implementation from above, except I refactored it as a generator function.</p>\n<pre><code>from string import whitespace\nfrom typing import Generator, List, Text\n\n\ndef separate_substrings(input_string: Text, *separators: Text) -&gt; Generator:\n &quot;&quot;&quot;Split an input string based on the specified separators.\n \n The `separate_substrings` function correctly handles quoted substrings\n within the input string, returning the entire contents of a quote as a\n single quoted lexeme.\n\n Parameters\n ----------\n input_string : Text\n The `input_string` parameter contains the entire contents which are to\n be lexed.\n \n separators : text\n The `separators` argument is a list of delimiters which mark the end of\n one lexeme and the start of another.\n \n &quot;&quot;&quot;\n # If the user forgets to specify the separators, the separators object will\n # be empty, and this will trigger a ValueException. To save everyone trouble\n # and heartache, if the separators object is empty, we will simply return\n # the input string as is.\n if not len(separators):\n # Just go ahead and yield the input string as is without actually doing\n # anything to it.\n yield input_string\n\n # Determine whether the first non-separator character in the input string\n # is a quote character. This will determine how we alternate between\n # subgroups within the input string.\n for character in input_string:\n # Since the first thing we did was trim the input string, there should\n # be no need to skip whitespace. We're always looking out for trouble,\n # though, so you never know.\n if character in whitespace:\n # Move on to the next character in the input string until we hit\n # a non-whitespace character.\n continue\n \n # Make a note of wether the first character we hit is a quote.\n in_quote = True if character == &quot;'&quot; else False\n\n # Now that we've settled that, we can break out of this loop.\n break\n\n # You already know that the quote character is the\n # delimiter demarcating substrings, so simply split the\n # input string using the same quote character.\n substrings: List[Text] = input_string.split(&quot;'&quot;)\n\n # Iterate over the substrings of the input string and process all of the\n # input string partitions that are not quoted substrings.\n for substring in substrings:\n # Trim each substring before processing so we don't get stuck with zero-\n # length strings in-between elements here and there.\n substring = substring.strip()\n\n # Check whether we actually need to do anything for this substring. If\n # we're in a quoted substring, we can skip this step.\n if not in_quote:\n # First, split the substring using whitespace as the delimiter.\n for element in substring.split(*separators):\n # Return each individual element within the substring.\n yield element\n\n # If we are in a quoted substring, all we need to do is add it to the\n # input string partitions sequence container object.\n else:\n # Return the entire quoted substring. I'm not really sure why the\n # quotes are necessary in and of themselves (haven't they done their\n # job by the mere fact that we didn't split that substring?), but\n # the question specifically included quotes in the output, so here\n # we go.\n yield f&quot;'{substring}'&quot;\n \n # Flip the sentinel value to make sure we do/don't process the next\n # substring, as necessary.\n in_quote = not in_quote\n</code></pre>\n<p>The interface is a little less intuitive this way, but now that you don't need the entire input string or the list of lexemes in memory, the pros massively outweigh the cons, I think.</p>\n<pre><code># Here's our trusty ol' sample input string.\ntext = &quot;a b c d 'e f' g h&quot;\n\n# The return value of the function is now an iterator, not a list. \nseparator_iterator = separate_substrings(text, &quot; &quot;)\n\n# We don't even need to build the list of results, though, we can\n# still iterate over the substrings, no problem.\nfor substring in separator_iterator:\n print(substring)\n\n# Still, you could build a list if you wanted to.\nseparator_iterator = separate_substrings(text, &quot; &quot;)\nlexemes = list(separator_iterator)\n</code></pre>\n<p>As expected, <code>lexemes</code> would contain <code>['a', 'b', 'c', 'd', &quot;'e f'&quot;, 'g', 'h']</code>.</p>\n<p>From here, I think it's hard to say without knowing more about your specific environment, use case, and experience. My first thought was to go for an asynchronous generator implementation, but in all honesty I don't have enough experience with Python's async and asyncio tooling to pull it off in a reasonable amount of time. Still, I found a lot of really interesting avenues for exploration there.</p>\n<p>Something you might do, for instance, is use an async iterator to split the input string and push the substrings onto a <code>multiprocessing</code> <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Queue\" rel=\"noreferrer\">Queue</a>, from which a <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool\" rel=\"noreferrer\">Pool</a> of independent processes gets their next substring and begins to process it.</p>\n<p>Since the quoted substrings won't need to be split further, it might be a waste to pass them to the process pool, so you might forward them to the next point in the pipeline.</p>\n<p>Another thing you might consider is using threads rather than processes. The <a href=\"https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor\" rel=\"noreferrer\">ThreadPoolExecutor</a> class is a subclass of the same <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor\" rel=\"noreferrer\">Executor</a> class from which <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor\" rel=\"noreferrer\">ProcessPoolExecutor</a> inherits, so making the switch is actually not horrible. I honestly don't know if there would be a benefit one way or the other, to be totally honest with you, but it's what I was going to try and compare when I realized I just didn't have time.</p>\n<p>I think the biggest takeaway from the original version though is that you're forcing the interpreter to use a ton of RAM it really doesn't need, and you're not really taking advantage of your computer's ability to run multiple threads on multiple processors at the same time.</p>\n<p>I'm really not sure how much more efficient the quoted substring heuristic is, really, but I think it's safe to say that at the very least, it is extremely dependent on the particular input string you're working with (specifically how many quoted substrings it contains, and how long they are), and thus it's probably not a game changer, but hey, you never know, I suppose.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T07:04:00.950", "Id": "529733", "Score": "0", "body": "It is slow on short strings but the speed increases dramatically as length of string and number of quotes increases, it also seems to be really efficient on saving time where it can. Thanks for the great answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T17:20:33.947", "Id": "268576", "ParentId": "268557", "Score": "5" } }, { "body": "<h1>Review</h1>\n<h2>Structure</h2>\n<p>Placing multiple statements on one line using the semicolon <code>;</code> or putting statements after the colon <code>:</code> in flow-control statements is to be eschewed. Don't do it.</p>\n<h2>Type hints</h2>\n<p>If you are going to use typehints, and you should, you should use the typehints for both parameters and return values. <code>sep()</code> has no return type. By inspection, it returns a list of strings, so the return type should be <code>list[str]</code> (or prior to Python 3.9, <code>from typing import List</code> and use <code>List[str]</code>)</p>\n<h2>Naming</h2>\n<p>Your names <code>cur</code>, and <code>res</code> are very terse, but are acceptable (barely).</p>\n<p>The variable <code>s</code> however is unacceptable. What is <code>s</code>? What does it mean? Lets examine the one and only comment where it is used: <code># Q</code>. Well, that was completely and utterly unhelpful.</p>\n<p>A much better name for <code>s</code> would be <code>within_quote</code>.</p>\n<h2>Resulting code</h2>\n<pre class=\"lang-py prettyprint-override\"><code>def sep(string: str, *seps: str) -&gt; list[str]:\n\n result = []\n current = &quot;&quot;\n within_quote = False\n\n for ch in string:\n if ch == &quot;'&quot;:\n within_quote = not within_quote\n if not within_quote and ch in seps:\n result.append(current)\n current = &quot;&quot;\n else:\n current += ch\n\n result.append(current)\n return result\n</code></pre>\n<p>This is immediately more readable.</p>\n<h1>Alternate implementation</h1>\n<p>The following regular-expression solution is close to the same behaviour as your code. It deviates when multiple spaces occur, or quoted terms are not surrounded by spaces. For you example case, however, it returns identical results.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\ndef sep(subject: str, *seps: str) -&gt; list[str]:\n separators = re.escape(&quot;&quot;.join(seps))\n pattern = f&quot;(?:'[^']+')|(?:[^{separators}]+)&quot;\n return re.findall(pattern, subject)\n\nif __name__ == '__main__':\n result = sep(&quot;a b c d 'e f' g h&quot;, ' ')\n print(repr(result))\n</code></pre>\n<p>Depending on your actual input requirements, it may or may not be sufficient for your needs.</p>\n<h1>Time comparisons</h1>\n<p>On strings with between 1 and one million terms, where a term is either a random &quot;word&quot; or a quoted string of 2-4 random words, and a random word is 1 to 7 random lowercase letters, I get the following time comparisons:</p>\n<p><a href=\"https://i.stack.imgur.com/YkLXS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YkLXS.png\" alt=\"log-log time comparison\" /></a></p>\n<p>Once above strings of 10 words, my solution and Fernandez's solution are both faster than the original. While mine beats Fernandez's in conciseness, their solution is clearly faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T19:23:16.933", "Id": "529699", "Score": "1", "body": "Isn't a regular expression solution likely to exacerbate the performance issue reported by the OP ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T20:15:37.930", "Id": "529705", "Score": "0", "body": "@Anonymous I don't believe so. Instead of processing characters one-at-a-time in Python, the RE engine, written in C, will be processing the characters. Additionally, there is no `cur += c` character-by-character accumulation, nor any `res.append(cur)` adding items to a list one-at-a-time accumulation. The RE engine efficiently returns fully realized Python objects, so no accumulation of partial results with associated memory allocation and freeing is required at the Python interpreter level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T20:23:47.287", "Id": "529706", "Score": "3", "body": "Would be interesting to see a `timeit`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T03:45:07.083", "Id": "529720", "Score": "0", "body": "I did a `timeit`, with arguments `(\"a b c d 'e f' g h\", ' ')`, my function takes `4.300000000002219e-06` or `0.0000043` secs and your function takes `0.0001331` secs, means your function is **more then `x100` slow**" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T06:48:56.603", "Id": "529730", "Score": "0", "body": "@Walidsiddik That is only one sample. Have you tried how it scales up with thr length of the input?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T06:55:15.770", "Id": "529731", "Score": "0", "body": "@m-alorda just tried a string of 351 length and 42 quotes in it, it's still takes 'x100' time, it also seems to be more slower as length increases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T10:56:34.260", "Id": "529742", "Score": "0", "body": "@WalidSiddik I now got curious to test the execution times myself, as I would have expected the `re` module to do better than a simple `for` loop. In this [trinket.io](https://trinket.io/python3/fadc3a7bb7) snippet you can see it actually does. If you are just running one test, with a few characters, the time it takes to prepare the regexp processor (which is constant) outweights the actual processing time. But with larger input, you can actually see the advantage. Also, for some reason, the solution offered by Jose Fernando seems to be way better when running in trinket.io than in my machine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T21:45:58.440", "Id": "529980", "Score": "1", "body": "I've just added a time comparison to my post for a broad range of input. Since multiple tests are being done, the regex engine startup overhead is not a factor (as pointed out by @MiguelAlorda). I've used random word lengths, since the inefficiency of `cur += c` is not obvious when only single character words are tested. I'm not seeing **100x slower** ... rather I see **4x faster**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T05:42:54.700", "Id": "529993", "Score": "0", "body": "@AJNeufeld I see your comparison and believe yours is faster. My test can be wrong." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T18:15:24.120", "Id": "268577", "ParentId": "268557", "Score": "4" } } ]
{ "AcceptedAnswerId": "268576", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T05:04:06.063", "Id": "268557", "Score": "6", "Tags": [ "python", "performance", "strings" ], "Title": "A string separator that doesn't separate if in quotes" }
268557
<p>In my application, I'm using <code>std::wstring_convert</code> to convert <code>std::string</code> into <code>std::u32string</code>. As this is very frequently done, I want to use a custom allocator to improve performance (and to learn more about C++).</p> <p>Therefore, I wrote a custom allocator which allocates 2 blocks of memory with a fixed size of 300 (seems sufficient for my cases) at construction of std::wstring_convert. What do you think about this allocator?</p> <pre><code>#include &lt;memory&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;codecvt&gt; #include &lt;locale&gt; template&lt;class T&gt; struct MemorySlot { std::shared_ptr&lt;T&gt; ptr; bool used; }; template&lt;class T&gt; class StringConverterAllocator { public: using value_type = T; using char_type = T; StringConverterAllocator(){ for (auto&amp; memorySlot : memorySlots) { auto deleter = [](T* ptr){::operator delete(ptr, ALLOCATED_SIZE * sizeof(T));}; memorySlot.ptr = std::shared_ptr&lt;T&gt;(reinterpret_cast&lt;T*&gt;(::operator new(ALLOCATED_SIZE * sizeof(T))), deleter); memorySlot.used = false; } } template&lt;class U&gt; explicit StringConverterAllocator(const StringConverterAllocator&lt;U&gt;&amp; src){ assert(sizeof(U) == sizeof(T)); for (std::size_t i = 0; i &lt; memorySlots.size(); ++i) { memorySlots[i].ptr = src.memorySlots[i].ptr; memorySlots[i].used = src.memorySlots[i].used; } } T* allocate(std::size_t n) { if (n &lt;= ALLOCATED_SIZE) { for (auto&amp; memorySlot : memorySlots) { if (!memorySlot.used) { memorySlot.used = true; return memorySlot.ptr.get(); } } } return reinterpret_cast&lt;T*&gt;(::operator new(n * sizeof(T))); } void deallocate(T* p, std::size_t n) { for (auto&amp; memorySlot : memorySlots) { if (memorySlot.ptr.get() == p) { memorySlot.used = false; return; } } return ::operator delete(p, n * sizeof(T)); } private: static constexpr std::size_t ALLOCATED_SIZE = 300; std::array&lt;MemorySlot&lt;T&gt;, 2&gt; memorySlots; }; typedef std::wstring_convert&lt;std::codecvt_utf8&lt;char32_t&gt;, char32_t, StringConverterAllocator&lt;char32_t&gt;, StringConverterAllocator&lt;char&gt;&gt; WStringConvertA; typedef std::basic_string&lt;char32_t, std::char_traits&lt;char32_t&gt;, StringConverterAllocator&lt;char32_t&gt;&gt; U32StringA; //identical to std::u32string but with a custom allocator ///////////////////////////////// //////////////////// TESTING PART ///////////////////////////////// void* operator new(std::size_t sz) { std::cout&lt;&lt;&quot; - New operator called&quot;&lt;&lt;std::endl; return std::malloc(sz); } int main() { { std::cout&lt;&lt;&quot;Without allocator:&quot;&lt;&lt;std::endl; std::cout&lt;&lt;&quot; - Init phase:&quot;&lt;&lt;std::endl; std::wstring_convert&lt;std::codecvt_utf8&lt;char32_t&gt;, char32_t&gt; stringConvert; std::cout&lt;&lt;&quot; - Execution phase:&quot;&lt;&lt;std::endl; std::u32string u32Text = stringConvert.from_bytes(&quot;myString...&quot;); std::u32string copyText = u32Text; } { std::cout&lt;&lt;&quot;With allocator:&quot;&lt;&lt;std::endl; std::cout&lt;&lt;&quot; - Init phase:&quot;&lt;&lt;std::endl; WStringConvertA stringConvert; std::cout&lt;&lt;&quot; - Execution phase:&quot;&lt;&lt;std::endl; U32StringA u32Text = stringConvert.from_bytes(&quot;myString...&quot;); U32StringA copyText = u32Text; } return 0; } </code></pre>
[]
[ { "body": "<p><code>assert(sizeof(U) == sizeof(T));</code><br />\nTry <code>static_assert</code> instead since these types are known at compile time!</p>\n<p><code>typedef std::wstring_convert&lt;std::codecvt_utf8&lt;char32_t&gt;, char32_t, StringConverterAllocator&lt;char32_t&gt;, StringConverterAllocator&lt;char&gt;&gt; WStringConvertA;</code><br />\nPrefer <code>using</code> to legacy <code>typedef</code>.</p>\n<pre><code> for (std::size_t i = 0; i &lt; memorySlots.size(); ++i) {\n memorySlots[i].ptr = src.memorySlots[i].ptr;\n memorySlots[i].used = src.memorySlots[i].used;\n }\n</code></pre>\n<p>Why not just use one assignment <code>memorySlots = src.memorySlots</code> ?</p>\n<p>You didn't define the normal copy constructor too. I recall that a template that matches isn't <em>the</em> copy constructor... I'll have to check what C++17 or later says about it.</p>\n<hr />\n<p>Your <code>allocate</code> and <code>deallocate</code> are coding loops instead of using std algorithms.</p>\n<hr />\n<p>I worry that the <code>shared_ptr</code>, which uses atomic primitives to be thread safe, will eat away the performance benefit you get from writing a custom allocator. How good is the built-in memory allocator (depends on the OS)? It might be doing something like that already with look-aside pools and thread-local cacheing.</p>\n<hr />\n<p>Standard advice you'll see all over CodeReviews:</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T15:16:50.053", "Id": "529680", "Score": "0", "body": "Thank you very much ! Indeed, I should find a better solution to avoid shared_ptr usage. What is the problem with coding loops ? Do you think it is better to use std::for_each ? What is the advantage ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T19:00:51.733", "Id": "529697", "Score": "0", "body": "Generally I agree with you about `endl`, however, there is the odd case where you want to write the new line character and then flush the output buffer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T14:07:58.097", "Id": "529837", "Score": "0", "body": "@pacmaninbw yes, and since its very presence will trip up code reviewers forever forward, when you mean that write it as a call to `flush`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T14:15:15.363", "Id": "529839", "Score": "0", "body": "@user249967 The answer to that fills numerous hour-long seminars, including presentations by Strustrup himself. To start with, consider the cognitive load when reading it; one has to figure out what the code _does_, examining in the low-level statements. It's a higher level to just write _find_, _fill_, _move_, or whatnot. Second, such detailed code could contain mistakes, and the library code may be carefully optimized. I don't find `std::for_each` to be particularly handy though, since it doesn't do anything other than the loop itself -- and C++ now has a range-based for loop natively." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T14:28:22.293", "Id": "529841", "Score": "0", "body": "For your `allocate` and `deallocate` I don't mean using `for_each` instead of a built-in `for` loop. I mean not writing a loop at all, but using `std::find`. The first one is `std::ranges::find (memorySlots, true, &MemorySlot::used)`. The second one is `std::ranges::find (memorySlots, p, &MemorySlot::ptr)`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:03:51.290", "Id": "268568", "ParentId": "268563", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T12:06:45.887", "Id": "268563", "Score": "2", "Tags": [ "c++", "performance", "c++17" ], "Title": "C++ allocator for std::wstring_convert" }
268563
<p>I was trying to emulate python's <code>timeit</code> in C++. My main aim for this is to measure the performance of small functions of C++ code that I write and print some basic stats like avg., min, max.</p> <h3>Code:</h3> <p><code>ctimeit.h</code>:</p> <pre><code>#ifndef CTIMEIT_H #define CTIMEIT_H #include &lt;chrono&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; #include &lt;limits&gt; namespace ctimeit { using GetTime = std::chrono::high_resolution_clock; using std::chrono::duration_cast; std::string format_time(int64_t); template &lt;size_t N = 1000, typename Callable, typename... Args&gt; void timeit(Callable func, Args&amp;&amp;... Funcargs) { /* * Measure the average execution time of `func` which takes `Funcargs` * after `N` executions. */ double total_time{0}; int64_t min_exec_time{std::numeric_limits&lt;int64_t&gt;::max()}, max_exec_time{0}; for (size_t i = 0; i &lt; N; ++i) { auto start = GetTime::now(); func(std::forward&lt;Args&gt;(Funcargs)...); auto end = GetTime::now(); auto run_time = duration_cast&lt;std::chrono::nanoseconds&gt;(end - start).count(); min_exec_time = std::min(min_exec_time, run_time); max_exec_time = std::max(max_exec_time, run_time); total_time += run_time; } std::cout &lt;&lt; &quot;Average time taken : &quot; &lt;&lt; format_time(total_time / N) &lt;&lt; &quot; (&quot; &lt;&lt; N &lt;&lt; &quot; runs)\n&quot; &lt;&lt; &quot;Max time taken : &quot; &lt;&lt; format_time(max_exec_time) &lt;&lt; &quot;\n&quot; &lt;&lt; &quot;Min time taken : &quot; &lt;&lt; format_time(min_exec_time) &lt;&lt; &quot;\n&quot;; } std::string format_time(int64_t run_time) { /* * For setting the scale of execution time. */ std::string formats[]{&quot;ns&quot;, &quot;µs&quot;, &quot;ms&quot;, &quot;s&quot;}; float scaling[]{1, 1e3, 1e6, 1e9}; int pow = std::floor(std::log10(run_time)); int idx = std::max(0, pow / 3); return std::to_string(run_time / scaling[idx]) + formats[idx]; } } // namespace ctimeit #endif // CTIMEIT_H </code></pre> <hr /> <p><strong>Output:</strong></p> <pre class="lang-none prettyprint-override"><code>std::cout&lt;&lt;&quot;-------SomeFunc---------\n&quot;; timeit(SomeFunc, v); //default N i.e 1000 std::cout&lt;&lt;&quot;-------anotherFunc with N arg---------\n&quot;; timeit&lt;100&gt;(anotherFunc, 10, 20, 40.f); -------SomeFunc--------- Average time taken : 904.073975µs (1000 runs) Max time taken : 4.574131ms Min time taken : 834.716003µs -------anotherFunc with N arg--------- Average time taken : 45.000000ns (100 runs) Max time taken : 137.000000ns Min time taken : 39.000000ns </code></pre> <p>Any suggestions to improve my code or if there's anything wrong I'm doing in measuring the execution time?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:01:42.357", "Id": "529664", "Score": "1", "body": "The example output (with exact nanoseconds) suggests that you're trying to show more precision than your platform provides." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:10:40.770", "Id": "529665", "Score": "0", "body": "@TobySpeight Yes, I think I'm passing `total_time/N` which is `double` to `format_time` which takes `int64_t`, losing all the precision. And `scaling` array is in `float` too that's why the output has less precision. Thank you I would have completely missed these details if not for your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T15:23:23.630", "Id": "529682", "Score": "0", "body": "Related: https://codereview.stackexchange.com/questions/58055/stopwatch-template" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:18:50.537", "Id": "529744", "Score": "0", "body": "If you actually want to time your code well, use an external profiler. They do a much better job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T09:37:34.597", "Id": "529779", "Score": "0", "body": "I'd definitely recommend reading up on [significant figures](https://en.wikipedia.org/wiki/Significant_figures) and suggest you modify how you output your numbers during the next revision of your program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T15:55:40.763", "Id": "529845", "Score": "0", "body": "@Mast Thank you for the suggestion." } ]
[ { "body": "<p>I'm guessing <code>int64_t</code> is intended to be <code>std::int64_t</code>? Don't assume that all compilers declare these types in the global namespace as well as <code>std</code>. If <code>std::int64_t</code> is present, it's declared in <code>&lt;cstdint&gt;</code>, so be sure to include that. Your code could be more portable if you used e.g. <code>std::uint_fast64_t</code> - or in this case, <code>std::chrono::nanoseconds::rep</code>.</p>\n<p><code>std::size_t</code> is consistently misspelt, too.</p>\n<hr />\n<p>Accumulating values into a <code>double</code> is likely to lose precision. I'd be inclined to keep the total as a duration, rather than converting to numeric type.</p>\n<hr />\n<blockquote>\n<pre><code> int idx = std::max(0, pow / 3);\n return std::to_string(run_time / scaling[idx]) + formats[idx];\n</code></pre>\n</blockquote>\n<p>Although we've taken care here not to run off the beginning of the array, we haven't taken the same care with the end (kiloseconds). We probably want</p>\n<pre><code>const std::array formats = {&quot;ns&quot;, &quot;µs&quot;, &quot;ms&quot;, &quot;s&quot;};\nauto idx = std::clamp(pow / 3, 0, static_cast&lt;int&gt;(formats.size() - 1));\n</code></pre>\n<p>Also, be careful using names such as <code>pow</code> which are also in the C standard library. That can hamper quick comprehension by your code's readers.</p>\n<p>This utility function <code>format_time()</code> probably deserves its own unit tests, to ensure that extremes are handled well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:49:55.537", "Id": "529668", "Score": "5", "body": "I really wouldn't categorize the issue of the type names not necessarily being in the global namespace in a conforming implementation as a _spelling_ error. It's a mistake in not knowing that it's not guaranteed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T05:45:58.930", "Id": "529724", "Score": "0", "body": "Thank you @Toby. I was under the false impression that `int64_t` are available in the global scope. Great review! `std::array formats = {\"ns\"...}` what would be the type of array is it `array<std:string>` or `array<const char *>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T23:11:48.987", "Id": "529770", "Score": "0", "body": "@Ch3steR several implementations make it available in the root namespace. This is allowed, but it is not guaranteed and thus must not be relied upon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T06:50:22.487", "Id": "529917", "Score": "0", "body": "That would be an array of `const char*` (since `auto s = \"ns\"` deduces to `const char*`). If you wanted `std::string`, there's a suffix operator in `std::literals`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T17:45:02.620", "Id": "530032", "Score": "0", "body": "The types are or are not required to be in the global namespace depending on which header was used to introduce them. Looking at the headers included by OP's code, I don't think those names are guaranteed to be available *anywhere*. `#include <inttypes.h>` would guarantee they exist in the global namespace, where the code expects to find them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:33:04.777", "Id": "530035", "Score": "0", "body": "@ben that's true, though in that case, I would advise using the C++ header `<cinttypes>`, for the usual reasons. And I note the code includes C++ header `<cmath>`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T13:17:34.010", "Id": "268565", "ParentId": "268564", "Score": "6" } }, { "body": "<p>Your code is unfortunately using a very naive method to measure the execution time of a function. I'll discuss a few of the issues and how to solve them below.</p>\n<h1>Avoid <code>std::chrono::high_resolution_clock</code></h1>\n<p>While the name sounds like it's what you want, there is unfortunately no guarantee whether this clock follows the wall clock or the monotonic clock. This means that if you are unfortunate enough that your NTP daemon is making an adjustment to the wall clock time while your benchmark is running, the results will be incorrect. <a href=\"https://en.cppreference.com/w/cpp/chrono/steady_clock\" rel=\"noreferrer\"><code>std::chrono::steady_clock</code></a> is the best clock from the C++ standard to use to avoid surprises.</p>\n<p>Even then, this might not be the best clock to measure the time your <em>process</em> spends executing functions. Consider that your operating system might have to handle interrupts or schedule other tasks on the same CPU core your benchmark is running on. Most operating systems have some clocks that will only count while your process is running. These are not standardized, but on POSIX systems you could consider using <a href=\"https://man7.org/linux/man-pages/man2/clock_gettime.2.html\" rel=\"noreferrer\"><code>clock_gettime()</code></a> with CLOCK_PROCESS_CPUTIME_ID.</p>\n<h1>Measuring time costs time</h1>\n<p>Calling <code>GetTime::now()</code> itself costs time; it might involve having to make system calls depending on the operating system. If you are going to take the time twice for each time you call <code>func()</code>, and if <code>func()</code> is a relatively fast function, you might start measuring the performance of <code>GetTime::now()</code> instead of the performance of <code>func()</code>. I did some tests where I ran your original code and a modified version that moves the calls to <code>GetTime::now()</code> out of the loop. The result for a function that does a few calculations was:</p>\n<ul>\n<li>Your code: 48 ns</li>\n<li>Modified code: 28 ns</li>\n</ul>\n<p>This is a difference of 20 ns, which corresponds exactly with some measurements of how long <code>clock_gettime(CLOCK_REALTIME)</code> takes on my machine.</p>\n<p>Another way to avoid the issue is to keep measuring time like you do now, but run the loop twice: once while calling <code>func()</code>, another time while calling a function that does nothing. Subtract the two to get the time actually spent inside <code>func()</code>, without including the overhead of time measurent and function call overhead.</p>\n<h1>Be aware of clock granularity</h1>\n<p>Clocks are not infinitely precise. On Linux on x86 processors, the <code>steady_clock</code> and <code>high_resolution_clock</code>s typically have a resolution of 1 ns. If you are measuring a function that takes just a few nanoseconds, this means you will have roundoff errors each time you measure the time. Those roundoff errors accumulate in your loop. This is another reason to just take the time before and after the loop to get a good average.</p>\n<p>Also consider that there are systems where the clocks have a lower resolution. For example, if you are on a platform where the system clock's resolution is only one microsecond, but the function you are trying to measure only takes 500 nanoseconds, you really need to run the function multiple times between time measurements.</p>\n<h1>Avoid casting durations too early</h1>\n<p>This is already mentioned by Toby Speight, just use <code>GetTime::duration</code> as the type for <code>run_time</code>, <code>total_time</code>, <code>min_exec_time</code> and <code>max_exec_time</code>. This type has the right precision for durations measured using the <code>GetTime</code> clock. (Maybe also just rename this to <code>clock</code>, otherwise it sounds like a function.)</p>\n<p>Only convert to a floating point number right before printing the measured durations, so basically have <code>format_time()</code> take a duration as a parameter.\nThe exception is the average time; you want to convert the total time to a floating point number before dividing by <code>N</code>.</p>\n<h1>Do a warm-up before taking actual measurements</h1>\n<p>Calling a function for the first time might take longer than calling the same function a subsequent time, because the first time it might not have been loaded into the CPU's caches, the CPU's branch predictor might not know how to predict it, any memory allocations might be expensive in the beginning, any file I/O might not hit the page cache yet, and so on. You need a warm-up run to ensure all these things have &quot;warmed up&quot;. This will take more than just calling the function once. I suggest you run the whole loop twice, and only use the statistics from the second time you run the loop. You might even consider running the loop many times, and only stopping when the results have stabilized.</p>\n<h1>Automatically scale the number of loop iterations</h1>\n<p>Consider running a loop with just a small number of iterations first to get a rough estimate of how long the function takes. Then decide for how long you want to run the benchmark, something between 1 and 10 seconds is a reasonable default. Then you can automatically choose the number of iterations based on the desired runtime of the benchmark divided by the estimated time the function takes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T05:49:02.133", "Id": "529725", "Score": "0", "body": "More than I expected. Thank you for such a detailed review and on where I can improve. I was wondering why `max time taken` is significantly higher than `avg.`, good to know why. Great review I'll try to incorporate all the mention points. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T09:42:06.927", "Id": "529737", "Score": "0", "body": "On granularity: _\"Also consider that there are systems where the clocks have a lower resolution [...] you really need to run the function multiple times between time measurements.\"_ Actually not really; imagine a task that takes 1 hour and you try to measure its duration using a device with a resolution of 1 day. If sampled repeatedly and randomly, in the majority of measurements the task will appear to start and end on the same day with duration = 0. However 1 in 24 times, it will run through midnight, appearing to take 24 hours. Averaging the measurements, the 1 hour duration is still found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T11:47:42.643", "Id": "529749", "Score": "1", "body": "@Greedo That only works if you do exactly a multiple of 24 measurements in that scenario. But it's much more likely you don't do the right amount of measurements for the measured average to be the actual average. To minimize the error in the measurement, just measure the duration of the whole loop instead of summing the durations of each individual iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T13:07:59.043", "Id": "529754", "Score": "0", "body": "@G.Sliepen Imagine you sample 1000 times, 41 take 24 hours, 959 take 0 then the average is 0.98 hours which is not exactly 1 but that's fine - you can quantify the uncertainty of this estimate using the student-t distribution. The problem with doing them back to back is the central limit theorem - if you want to know the distribution of values, not just the average (so max/min like OP uses, or maybe StDev or shape of distribution) then squashing everything together you lose that info and runtimes appear more gaussian than they really were. This will make max/min closer to the mean than reality" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T13:21:44.343", "Id": "529755", "Score": "0", "body": "... so yeah, if your measurement resolution gives some uncertainty to a single measurement, then by taking `n` in a loop and measuring only once, you can divide that uncertainty by `sqrt(n)`, like measuring many sheets of paper in a stack with a ruler rather than one by one. However you lose information about variation in thickness of the paper, as this gets averaged out. You can estimate it by measuring several stacks and working out the StDev, then scaling that up by `sqrt(n)`, however this assumes the paper thickness is gaussian and there's no way to validate this because that info is lost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T13:25:00.653", "Id": "529756", "Score": "0", "body": "@G.Sliepen I think, IIUC :). I've been working with execution timing and uncertainties a lot recently. Too much to discuss in the comments though" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T15:25:11.570", "Id": "268570", "ParentId": "268564", "Score": "9" } }, { "body": "<p>There's a glaring bug in how you forward arguments</p>\n<pre><code>template &lt;size_t N = 1000, typename Callable, typename... Args&gt;\nvoid timeit(Callable func, Args&amp;&amp;... Funcargs) {\n // ...\n for (size_t i = 0; i &lt; N; ++i) {\n // ...\n func(std::forward&lt;Args&gt;(Funcargs)...);\n // ...\n}\n</code></pre>\n<p>Consider this</p>\n<pre><code>timeit([](std::string s){ s += s; }, std::string(&quot;Lorem ipsum dolor sit amet&quot;));\n</code></pre>\n<p>You move the string in the first iteration, and henceforth the string is in a valid but unspecified state, usually just empty. Either way, that's not what you want. A quick fix is</p>\n<pre><code>template &lt;typename... Args, typename Callable, typename Tuple, size_t... Is&gt;\nvoid forward_apply(Callable func, Tuple&amp; args, std::index_sequence&lt;Is...&gt;) {\n func(std::forward&lt;Args&gt;(get&lt;Is&gt;(args))...);\n}\n\ntemplate &lt;size_t N = 1000, typename Callable, typename... Args&gt;\nvoid timeit(Callable func, Args&amp;&amp;... Funcargs) {\n // ...\n for (size_t i = 0; i &lt; N; ++i) {\n auto args = std::tuple(Funcargs...);\n // ...\n forward_apply&lt;Args&amp;&amp;...&gt;(func, args, std::index_sequence_for&lt;Args...&gt;{});\n // ...\n}\n</code></pre>\n<p>where you make a copy of the arguments without timing them, and then forward them as specified by the argument types.</p>\n<p>At this point, <code>timeit</code> has rather convoluted semantics. What if the arguments aren't copyable? Should <code>Callable</code> be copied and forwarded similarly to the arguments? A solution provided by the standard library is to use <code>std::reference_wrapper</code> to opt <em>out</em> of copying. However, the complexity for both users and implementer gets even greater.</p>\n<p>You could limit the scope of what <code>timeit</code> is supposed to do</p>\n<pre><code>template &lt;size_t N = 1000, typename Callable&gt;\nvoid timeit(Callable&amp;&amp; func) {\n // ...\n for (size_t i = 0; i &lt; N; ++i) {\n // ...\n func();\n // ...\n}\n</code></pre>\n<p>The semantics is simple: <code>timeit</code> repeatedly calls <code>operator()</code> on the <code>func</code> object passed in, and it's up to the user to decide what to do with arguments. It is however impossible to omit argument copying time in such a design.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T05:54:53.733", "Id": "529727", "Score": "0", "body": "Great point about `Callable` being not copyable. Should I make `Callable` a `forwarding reference` too? would that be good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T08:18:38.923", "Id": "529734", "Score": "1", "body": "Thank you for the review again. Since I started learning C++ recently it took some time to understand everything. It made me think maybe redesigning my whole approach might not be a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T09:23:33.543", "Id": "529735", "Score": "0", "body": "Maybe a solution to keep this simple is to just not pass `Funcargs` to `timeit()`. Instead, let the caller pass a lambda which has captured the arguments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T10:05:01.030", "Id": "529738", "Score": "0", "body": "@G.Sliepen I considered that, but then it means you always benchmark whatever you do with the arguments. If the user doesn't want to include the copying time, they can't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T10:10:21.387", "Id": "529740", "Score": "0", "body": "@Ch3steR Whether to forward `Callable` is a design choice. You could require that `Callable::operator()` not modify its state, which is what your current version means. You could also do what I did with the arguments (copy and forward). Or you could use `std::reference_wrapper` to opt out of copying. If it were me though, I'd choose the first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T10:18:07.380", "Id": "529741", "Score": "0", "body": "@G.Sliepen On second thought, that sounds fine. This function isn't ever going to be a full featured benchmarking suite anyways." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T05:06:29.217", "Id": "268590", "ParentId": "268564", "Score": "4" } } ]
{ "AcceptedAnswerId": "268570", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T12:13:39.403", "Id": "268564", "Score": "7", "Tags": [ "c++", "benchmarking" ], "Title": "Measuring execution time of a function" }
268564
<p>I am not a Ruby developer but cold-reading existing Jekyll plugins I implemented one to bundle files in a zip archive and <a href="https://github.com/PhilLab/jekyll-zip-bundler" rel="nofollow noreferrer">open sourced it on GitHub</a>.</p> <p>What do I need to fix to make it look more Ruby-native and/or Jekyll-native?</p> <pre class="lang-rb prettyprint-override"><code># Copyright 2021 by Philipp Hasper # MIT License # https://github.com/PhilLab/jekyll-zip-bundler require &quot;jekyll&quot; require 'zip' #~ gem 'rubyzip', '~&gt;2.3.0' module Jekyll # Valid syntax: # {% zip archiveToCreate.zip file1.txt file2.txt %} # {% zip archiveToCreate.zip file1.txt file2.txt %} # {% zip archiveToCreate.zip file1.txt folder/file2.txt 'file with spaces.txt' %} # {% zip {{ variableName }} file1.txt 'folder/file with spaces.txt' {{ otherVariableName }} %} # {% zip {{ variableName }} {{ VariableContainingAList }} %} class ZipBundlerTag &lt; Liquid::Tag VARIABLE_SYNTAX = %r![^{]*(\{\{\s*[\w\-\.]+\s*(\|.*)?\}\}[^\s{}]*)!mx def initialize(tagName, markup, tokens) super # Split by spaces but only if the text following contains an even number of ' # Based on https://stackoverflow.com/a/11566264 # Extended to also not split between the curly brackets of Liquid @files = markup.strip.split(%r!\s(?=(?:[^'}]|'[^']*'|{{[^}]*}})*$)!) end def render(context) files = [] # Resolve the given parameters to a file list @files.each do |file| matched = file.strip.match(VARIABLE_SYNTAX) if matched # This is a variable. Look it up. resolved = context[file] if resolved.respond_to?(:each) # This is a collection. Flatten it before appending resolved.each do |file| files.push(file) end else files.push(resolved) end elsif file.strip.length &gt; 0 files.push(file.strip) end end # First file is the target zip archive path if files.length &lt; 2 abort &quot;zip tag must be called with at least two files&quot; end # Generate the file in the cache folder cacheFolder = &quot;.jekyll-cache/zip_bundler/&quot; zipfile_path = cacheFolder + files[0] FileUtils.makedirs(File.dirname(zipfile_path)) files_to_zip = files[1..-1] # Create the archive. Delete file, if it already exists File.delete(zipfile_path) if File.exists?(zipfile_path) Zip::File.open(zipfile_path, Zip::File::CREATE) do |zipfile| files_to_zip.each do |file| # Two arguments: # - The name of the file as it will appear in the archive # - The original file, including the path to find it zipfile.add(File.basename(file), file) end end puts &quot;Created archive #{zipfile_path}&quot; # Add the archive to the site's static files site = context.registers[:site] site.static_files &lt;&lt; Jekyll::StaticFile.new(site, site.source + &quot;/&quot; + cacheFolder, File.dirname(files[0]), File.basename(zipfile_path)) # No rendered output &quot;&quot; end end end Liquid::Template.register_tag(&quot;zip&quot;, Jekyll::ZipBundlerTag) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:16:57.760", "Id": "531957", "Score": "1", "body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<h1>Consistency</h1>\n<p>Sometimes you use <code>snake_case</code>, sometimes you use <code>camelCase</code> for methods and local variables. Sometime you use single-quoted strings and sometimes you use double-quoted strings.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing <em>IFF</em> you actually <em>want</em> to convey some extra information.</p>\n<p>For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a <em>good</em> reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).</p>\n<h1>Single-quoted strings</h1>\n<p>If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>require &quot;jekyll&quot;\n</code></pre>\n<p>should instead be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>require 'jekyll'\n</code></pre>\n<p>Note that on the very next line, you use</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>require 'zip'\n</code></pre>\n<p>That is inconsistent and it trips up the reader, because they are left wondering what the difference is between <code>zip</code> and <code>jekyll</code>. Why did you choose to enclose one in single quotes and one in double quotes? What does that mean? What are you trying to tell us?</p>\n<p>Note that it is perfectly fine to use double quoted strings if you otherwise needed to use escapes, e.g. if you had some something like</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts &quot;Philipp's Jekyll plugin&quot;\n</code></pre>\n<p>that reads much better than</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts 'Philipp\\'s Jekyll plugin'\n</code></pre>\n<p>So in this case, double quotes would be preferred.</p>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a <a href=\"https://bugs.ruby-lang.org/issues/8976\" rel=\"nofollow noreferrer\">magic comment</a> you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>Freeze objects assigned to constants</h1>\n<p>As mentioned above, you should prefer as much as possible to use purely functional code, immutable data, and immutable bindings.</p>\n<p>Here, you assign a mutable value to a constant:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = %r![^{]*(\\{\\{\\s*[\\w\\-\\.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)!mx\n</code></pre>\n<p>This could be somewhat confusing because while the object is assigned to a <em>constant</em>, the <em>object itself</em> can still be changed. It is better to <a href=\"https://ruby-doc.org/core/Object.html#method-i-freeze\" rel=\"nofollow noreferrer\"><code>freeze</code></a> objects assigned to constants:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = %r![^{]*(\\{\\{\\s*[\\w\\-\\.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)!mx.freeze\n</code></pre>\n<h1>Prefer <code>/</code> for <code>Regexp</code> literals</h1>\n<p>It is generally preferred to use <code>/</code> to delimit <code>Regexp</code> literals unless you need to use <code>/</code> within your <code>Regexp</code> literal:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w\\-\\.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/mx.freeze\n</code></pre>\n<h1>Superfluous escape in the <code>Regexp</code> literal</h1>\n<p>There is no need to escape the <code>.</code> character in a character class: it has no special meaning inside a character class.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w\\-.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/mx.freeze\n</code></pre>\n<p>Also, you don't need to escape <code>-</code> in a character class if it is the first or last character in the class:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w.-]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/mx.freeze\n</code></pre>\n<h1>Superfluous option in the <code>Regexp</code> literal</h1>\n<p>You are using the <a href=\"https://ruby-doc.org/core/Regexp.html#class-Regexp-label-Free-Spacing+Mode+and+Comments\" rel=\"nofollow noreferrer\"><code>x</code> eXtended mode option</a>, which allows you to write the <code>Regexp</code> in multiple lines and add comments to it … but you are not actually doing any of that. So, it is just extra fluff that can be removed</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w.-]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/m.freeze\n</code></pre>\n<h1>Prefer predicate methods over relational operators</h1>\n<p>You should prefer &quot;speaking&quot; predicate methods such as <a href=\"https://ruby-doc.org/core/Numeric.html#method-i-negative-3F\" rel=\"nofollow noreferrer\"><code>Numeric#negative?</code></a> over relational operators such as <code>&lt; 0</code>.</p>\n<p>So, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>elsif file.strip.length &gt; 0\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>elsif file.strip.length.positive?\n</code></pre>\n<h1>Prefer predicate methods over explicit length checks</h1>\n<p>As mentioned above, you should prefer predicates over relational operators. But in this specific case, we can even do one better, we can use <a href=\"https://ruby-doc.org/core/String.html#method-i-empty-3F\" rel=\"nofollow noreferrer\"><code>String#empty?</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>elsif file.strip.length.positive?\n</code></pre>\n<p>can just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>elsif !file.strip.empty?\n</code></pre>\n<h1>Space after <code>#</code> in comments</h1>\n<p>There should be one space after the <code>#</code> in a comment:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>#~ gem 'rubyzip', '~&gt;2.3.0'\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># ~ gem 'rubyzip', '~&gt;2.3.0'\n</code></pre>\n<p>Actually, it looks like you just commented out a line of code. You can just delete it. If you want it back, that's what Version Control Systems are for.</p>\n<h1>No empty line after opening keyword</h1>\n<p>There should be no empty line after the opening <code>module</code>, <code>class</code>, <code>def</code>, <code>do</code>, <code>while</code>, <code>until</code>, <code>if</code>, <code>unless</code>, <code>case</code>, etc.</p>\n<p>Which means there should be no empty line here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class ZipBundlerTag &lt; Liquid::Tag\n\n VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w.-]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/m.freeze\n</code></pre>\n<p>it should just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class ZipBundlerTag &lt; Liquid::Tag\n VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w.-]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/m.freeze\n</code></pre>\n<h1>Modifier <code>if</code></h1>\n<p>If the body of a conditional expression is only a single expression, you can use the modifier form of the conditional.</p>\n<p>For example, you can use that here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>if files.length &lt; 2\n abort 'zip tag must be called with at least two files'\nend\n</code></pre>\n<p>could be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>abort 'zip tag must be called with at least two files' if files.length &lt; 2\n</code></pre>\n<h1>Use of deprecated / removed methods</h1>\n<p><a href=\"https://ruby-doc.org/core-2.7.4/File.html#method-c-exists-3F\" rel=\"nofollow noreferrer\"><code>File::exists?</code></a> is deprecated, and has been for many years. Its documentation literally reads, in its entirety:</p>\n<blockquote>\n<p>Deprecated method. Don't use.</p>\n</blockquote>\n<p>In fact, in current versions of Ruby, the method actually does not exist anymore. This means that in current versions of Ruby, your code will fail with a <a href=\"https://ruby-doc.org/core/NoMethodError.html\" rel=\"nofollow noreferrer\"><code>NoMethodError</code></a> exception!</p>\n<p>You should use <a href=\"https://ruby-doc.org/core/File.html#method-c-exist-3F\" rel=\"nofollow noreferrer\"><code>File::exist?</code></a> instead.</p>\n<h1>Prefer string interpolation over concatenation</h1>\n<pre class=\"lang-ruby prettyprint-override\"><code>site.source + '/' + cacheFolder\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>&quot;#{site.source}/{cacheFolder}&quot;\n</code></pre>\n<p>Although in this particular case, since you are actually constructing a path, you could also use one of the methods dedicated to that purpose, like <a href=\"https://ruby-doc.org/core/File.html#method-c-join\" rel=\"nofollow noreferrer\"><code>File::join</code></a>.</p>\n<p>You already use similar methods for finding the name of the directory and the base name.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect almost all of the style violations I pointed out above (plus some more), and also was able to autocorrect most of the ones it detected.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit &quot;save&quot;.</p>\n<p>In particular, running Rubocop on your code, it detects 29 offenses, of which it can automatically correct 19.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\n# Copyright 2021 by Philipp Hasper\n# MIT License\n# https://github.com/PhilLab/jekyll-zip-bundler\n\nrequire 'jekyll'\nrequire 'zip'\n# ~ gem 'rubyzip', '~&gt;2.3.0'\n\nmodule Jekyll\n # Valid syntax:\n # {% zip archiveToCreate.zip file1.txt file2.txt %}\n # {% zip archiveToCreate.zip file1.txt file2.txt %}\n # {% zip archiveToCreate.zip file1.txt folder/file2.txt 'file with spaces.txt' %}\n # {% zip {{ variableName }} file1.txt 'folder/file with spaces.txt' {{ otherVariableName }} %}\n # {% zip {{ variableName }} {{ VariableContainingAList }} %}\n class ZipBundlerTag &lt; Liquid::Tag\n VARIABLE_SYNTAX = /[^{]*(\\{\\{\\s*[\\w\\-.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)/mx.freeze\n\n def initialize(tagName, markup, tokens)\n super\n # Split by spaces but only if the text following contains an even number of '\n # Based on https://stackoverflow.com/a/11566264\n # Extended to also not split between the curly brackets of Liquid\n @files = markup.strip.split(/\\s(?=(?:[^'}]|'[^']*'|{{[^}]*}})*$)/)\n end\n\n def render(context)\n files = []\n # Resolve the given parameters to a file list\n @files.each do |file|\n matched = file.strip.match(VARIABLE_SYNTAX)\n if matched\n # This is a variable. Look it up.\n resolved = context[file]\n if resolved.respond_to?(:each)\n # This is a collection. Flatten it before appending\n resolved.each do |file|\n files.push(file)\n end\n else\n files.push(resolved)\n end\n elsif file.strip.length.positive?\n files.push(file.strip)\n end\n end\n\n # First file is the target zip archive path\n abort 'zip tag must be called with at least two files' if files.length &lt; 2\n # Generate the file in the cache folder\n cacheFolder = '.jekyll-cache/zip_bundler/'\n zipfile_path = cacheFolder + files[0]\n FileUtils.makedirs(File.dirname(zipfile_path))\n\n files_to_zip = files[1..-1]\n\n # Create the archive. Delete file, if it already exists\n File.delete(zipfile_path) if File.exist?(zipfile_path)\n Zip::File.open(zipfile_path, Zip::File::CREATE) do |zipfile|\n files_to_zip.each do |file|\n # Two arguments:\n # - The name of the file as it will appear in the archive\n # - The original file, including the path to find it\n zipfile.add(File.basename(file), file)\n end\n end\n puts &quot;Created archive #{zipfile_path}&quot;\n\n # Add the archive to the site's static files\n site = context.registers[:site]\n site.static_files &lt;&lt; Jekyll::StaticFile.new(site, &quot;#{site.source}/#{cacheFolder}&quot;, File.dirname(files[0]),\n File.basename(zipfile_path))\n # No rendered output\n ''\n end\n end\nend\n\nLiquid::Template.register_tag('zip', Jekyll::ZipBundlerTag)\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Inspecting 1 file\nW\n\nOffenses:\n\nzip_bundler.rb:21:20: C: Naming/MethodParameterName: Only use lowercase characters for method parameter.\n def initialize(tagName, markup, tokens)\n ^^^^^^^\nzip_bundler.rb:21:20: C: Naming/VariableName: Use snake_case for variable names.\n def initialize(tagName, markup, tokens)\n ^^^^^^^\nzip_bundler.rb:29:5: C: Metrics/AbcSize: Assignment Branch Condition size for render is too high. [&lt;11, 36, 10&gt; 38.95/17]\n def render(context) ...\n ^^^^^^^^^^^^^^^^^^^\nzip_bundler.rb:29:5: C: Metrics/CyclomaticComplexity: Cyclomatic complexity for render is too high. [9/7]\n def render(context) ...\n ^^^^^^^^^^^^^^^^^^^\nzip_bundler.rb:29:5: C: Metrics/MethodLength: Method has too many lines. [32/10]\n def render(context) ...\n ^^^^^^^^^^^^^^^^^^^\nzip_bundler.rb:29:5: C: Metrics/PerceivedComplexity: Perceived complexity for render is too high. [11/8]\n def render(context) ...\n ^^^^^^^^^^^^^^^^^^^\nzip_bundler.rb:39:31: W: Lint/ShadowingOuterLocalVariable: Shadowing outer local variable - file.\n resolved.each do |file|\n ^^^^\nzip_bundler.rb:53:7: C: Naming/VariableName: Use snake_case for variable names.\n cacheFolder = '.jekyll-cache/zip_bundler/'\n ^^^^^^^^^^^\nzip_bundler.rb:54:22: C: Naming/VariableName: Use snake_case for variable names.\n zipfile_path = cacheFolder + files[0]\n ^^^^^^^^^^^\nzip_bundler.rb:73:75: C: Naming/VariableName: Use snake_case for variable names.\n site.static_files &lt;&lt; Jekyll::StaticFile.new(site, &quot;#{site.source}/#{cacheFolder}&quot;, File.dirname(files[0]),\n ^^^^^^^^^^^\n\n1 file inspected, 10 offenses detected\n</code></pre>\n<p>It is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.</p>\n<p>In my editor, I actually have multiple linters and static analyzers integrated so that they automatically always analyze my code, and also as much as possible automatically fix it while I am typing. This can sometimes be annoying (e.g. I get 76 notices for your original code, lots of which are duplicates because several different tools report the same problem), but it is in general tremendously helpful. It can be overwhelming when you open a large piece of code for the first time and you get dozens or hundreds of notices, but if you start a new project, then you can write your code in a way that you never get a notice, and your code will usually be better for it.</p>\n<p>However, even by simply hitting &quot;Save&quot;, my editor applies a series of automatic fixes which brings the number of notices down to 48. Running Rubocop as described above, further reduces this to 38, and as mentioned, lots of these are duplicates because I have multiple different linters and analyzers configured. I would say about 16 are unique.</p>\n<h1>Use <code>snake_case</code> for local variables</h1>\n<p>Methods, local variables, instance variables, class variables, global variables, and parameters should use <code>snake_case</code> naming convention. You are jumping back and fort between <code>camelCase</code> and <code>snake_case</code>, for example here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>cacheFolder = '.jekyll-cache/zip_bundler/'\nzipfile_path = cacheFolder + files[0]\n</code></pre>\n<p>This should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>cache_folder = '.jekyll-cache/zip_bundler/'\nzipfile_path = cache_folder + files[0]\n</code></pre>\n<p>With a good editor or IDE, you should be able to fix this fairly easily with the <em>Rename Variable Refactoring</em>.</p>\n<p>This brings the number of Rubocop offenses down to 5 and the number of notices in my editor down to 26.</p>\n<h1>The hard stuff</h1>\n<p>Note that all we did so far was either done automatically for us by the editor or Rubocop's auto-correct feature, or we were blindly following instructions such as renaming variables. We did not yet have to think at all.</p>\n<p>However, if we look at the remaining notices we get from Rubocop and the other linters and analyzers, it is clear that we will have to apply some brains to get rid of them:</p>\n<p><a href=\"https://i.stack.imgur.com/0KYCW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0KYCW.png\" alt=\"List of notices for the zip_bundler.rb file\" /></a></p>\n<h1>Duplicate code</h1>\n<p>Some of these are still fairly easy to get rid of, in particular the ones about duplicate code.</p>\n<p>For example, <code>files[0]</code> is really the target. You even have a comment that says so:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># First file is the target zip archive path\n</code></pre>\n<p>So, let's just make that clear:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>target = files.first\n</code></pre>\n<p>And now we can replace all occurrences of <code>files[0]</code> with <code>target</code>, which not only gets rid of the notices in the editor, but also makes the code more intention-revealing.</p>\n<p>The same applies to the <code>file.strip</code>. We could simply assign something like <code>stripped_file = file.strip</code> and replace all the mentions of <code>file.strip</code> with <code>stripped_file</code>. But in my opinion, it would be even better to fix the problem at the source, and make sure that the <code>@files</code> variable only contains pre-stripped files.</p>\n<p>So, we change the <code>initialize</code> method to</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@files = markup.strip.split(/\\s(?=(?:[^'}]|'[^']*'|{{[^}]*}})*$)/).map(&amp;:strip)\n</code></pre>\n<p>Note: it might also be possible to tweak the <code>Regexp</code> so that there is nothing to strip in the first place.</p>\n<p>The same applies to the <code>file.empty?</code> check. We can either remove empty strings right here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@files = markup.strip.split(/\\s(?=(?:[^'}]|'[^']*'|{{[^}]*}})*$)/).map(&amp;:strip).reject(&amp;:empty?)\n</code></pre>\n<p>or maybe tweak the <code>Regexp</code> in order to not produce empty strings in the first place.</p>\n<h1>Better design</h1>\n<p>Unfortunately, getting rid of most of the other notices and offenses requires a level of domain knowledge of Liquid that I do not have.</p>\n<p>For example, I don't know what kinds of collections can appear at this point:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>if resolved.respond_to?(:each)\n # This is a collection. Flatten it before appending\n resolved.each do |file|\n files.push(file)\n end\n</code></pre>\n<p>If these collections respond to <code>to_ary</code>, then we can replace the whole loop with a <code>map</code> + <code>flatten</code>, something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>target, files = @files.map do |file|\n next file unless file.match(VARIABLE_SYNTAX)\n\n # This is a variable. Look it up.\n context[file]\nend.flatten\n</code></pre>\n<h1>Splitting code</h1>\n<p>You have already put in some comments explaining the individual steps. As a very general rule, whenever you write a comment, you should take that as an opportunity to take a step back and think about <em>why</em> you are writing that comment in the first place.</p>\n<p>In particular,</p>\n<ul>\n<li>if you are writing the comment because the code is too complex, then make the code simpler and the comment is no longer needed</li>\n<li>if you are writing the comment to explain what something is, then give it a better name (or give it a name in the first place if it doesn't have one) and the comment is no longer needed</li>\n<li>if you are writing the comment to point out logical breaks in the code, then split the code at that point and the comment is no longer needed</li>\n<li>if you are writing the comment to explain what the code does, then really the code should explain what the code does instead, and the comment should not be needed</li>\n</ul>\n<p>The main reason to have a comment is to explain <em>why</em> a piece of code does something in a certain way that may be non-obvious.</p>\n<p>So, looking at the comments that delineate the separate steps, maybe we can split the code at those points and actually make each step a separate method.</p>\n<p>It would look somewhat like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def render(context)\n # First file is the target zip archive path\n target, files = resolve_parameters(context)\n\n abort 'zip tag must be called with at least two files' if files.empty?\n\n zipfile_path = CACHE_FOLDER + target\n\n klass = self.class\n klass.create_directory(zipfile_path)\n klass.create_archive(files, zipfile_path)\n klass.register_files(context, target, zipfile_path)\n\n # No rendered output\n ''\nend\n\nprivate\n\ndef resolve_parameters(context)\n target, files = @files.map do |file|\n next file unless file.match(VARIABLE_SYNTAX)\n\n # This is a variable. Look it up.\n context[file]\n end\n\n [target, files]\nend\n\nprivate_class_method def self.create_directory(zipfile_path)\n FileUtils.makedirs(File.dirname(zipfile_path))\nend\n\nprivate_class_method def self.create_archive(files, zipfile_path)\n File.delete(files, zipfile_path) if File.exist?(zipfile_path)\n Zip::File.open(zipfile_path, Zip::File::CREATE) do |zipfile|\n files.each do |file|\n # Two arguments:\n # - The name of the file as it will appear in the archive\n # - The original file, including the path to find it\n zipfile.add(File.basename(file), file)\n end\n end\n puts &quot;Created archive #{zipfile_path}&quot;\nend\n\nprivate_class_method def self.register_files(context, target, zipfile_path)\n # Add the archive to the site's static files\n site = context.registers[:site]\n site.static_files &lt;&lt; Jekyll::StaticFile.new(site, File.join(site.source, CACHE_FOLDER), File.dirname(target),\n File.basename(zipfile_path))\nend\n</code></pre>\n<p>As mentioned above, I don't have enough domain knowledge in Jekyll or Liquid to make any suggestions about a fundamentally better design. Maybe there are some helper methods that could be used. For example, I cannot imagine that you have to parse variables yourself. (But I was wrong, the documentation actually explicitly says that you have to do that.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T13:58:40.593", "Id": "531944", "Score": "0", "body": "Thanks for this very extensive answer! I have applied most of the suggestions and added a CI to check for them (https://github.com/PhilLab/jekyll-zip-bundler/pull/1/files). I did not fully do the code splitting part because my personal tolerance towards method length is a little higher. But I definitely will keep these stricter constraints in mind in the future." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T18:52:08.353", "Id": "268860", "ParentId": "268574", "Score": "3" } }, { "body": "<p>Jörg already provided some good suggestions. The only thing I would add is that your <code>render</code> function contains all of your business logic and is quite difficult to understand. It could benefit from splitting it up a bit into helper methods. However, the render function accepts the context parameter which makes this a bit difficult. Therefore I would suggest to extract a (nested) class which gets the context and files as attributes.</p>\n<p>Something like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class ZipBundlerTag &lt; Liquid::Tag\n def initialize(tagName, markup, tokens)\n super\n # Split by spaces but only if the text following contains an even number of '\n # Based on https://stackoverflow.com/a/11566264\n # Extended to also not split between the curly brackets of Liquid\n @files = markup.strip.split(%r!\\s(?=(?:[^'}]|'[^']*'|{{[^}]*}})*$)!)\n end\n\n def render(context)\n ZipBundlerTagRender.new(context, @files).create\n end\nend\n</code></pre>\n<p>and then you can do something like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class ZipBundlerTagRender\n CACHE_FOLDER = &quot;.jekyll-cache/zip_bundler/&quot;.freeze\n VARIABLE_SYNTAX = %r![^{]*(\\{\\{\\s*[\\w\\-\\.]+\\s*(\\|.*)?\\}\\}[^\\s{}]*)!mx\n\n def initialize(context, params)\n @context = context\n @params = params\n @site = context.registers[:site]\n end\n\n def create\n FileUtils.makedirs(File.dirname(zipfile_path))\n File.delete(zipfile_path) if File.exists?(zipfile_path)\n create_archive!\n site.static_files &lt;&lt; Jekyll::StaticFile.new(site, site.source + &quot;/&quot; + CACHE_FOLDER, File.dirname(files[0]), File.basename(zipfile_path))\n end\n\n private\n\n attr_reader :context, :params, :site\n\n def create_archive\n Zip::File.open(zipfile_path, Zip::File::CREATE) do |zipfile|\n files_to_zip.each do |file|\n zipfile.add(File.basename(file), file)\n end\n end\n end\n\n def files_to_zip\n files[1..-1]\n end\n\n def zipfile_path\n CACHE_FOLDER + files[0]\n end\n\n def file_names\n @file_names ||= fetch_file_names\n end\n\n def fetch_file_names\n params.map do |file|\n if file.strip.match(VARIABLE_SYNTAX)\n files.push(context[file])\n elsif file.strip.length &gt; 0\n files.push(file.strip)\n end\n end.flatten\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T14:04:06.180", "Id": "531946", "Score": "0", "body": "Thanks for this answer which really highlights how to modularize the code better. I have improved the code at https://github.com/PhilLab/jekyll-zip-bundler but I did not introduce a second class and not all of the separate helper methods. Given the simplicity of the plugin's task, it personally felt better being able to just read from top to bottom without frequently jumping between methods. However, if I will need to extend (or unit test) the plugin, I might introduce the code splits you proposed. This was definitely helpful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T21:15:28.927", "Id": "268866", "ParentId": "268574", "Score": "3" } } ]
{ "AcceptedAnswerId": "268860", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T16:44:32.173", "Id": "268574", "Score": "4", "Tags": [ "ruby", "plugin", "jekyll" ], "Title": "Jekyll plugin which bundles files into a zip archive" }
268574
<p>I have this handler for my API endpoint <code>/api/universities</code>. My main concern is the overall quality of the code and the efficiency of my use of <code>append()</code>. I haven't been able to come up with a better way of storing the responses and returning them without using a slice &amp; <code>append()</code>. Any comments are appreciated. The tech in use is the official MongoDB Golang driver and <code>GoFiber</code> framework.</p> <pre class="lang-golang prettyprint-override"><code>func GetUniversities(c *fiber.Ctx) error { ctx, cancel := context.WithTimeout(context.Background(), TIMEOUT) defer cancel() var universities []models.University filter := bson.M{} opts := options.Find() if s := c.Query(&quot;s&quot;); s != &quot;&quot; { filter = bson.M{ &quot;name&quot;: bson.M{ &quot;$regex&quot;: primitive.Regex{ Pattern: s, Options: &quot;i&quot;, }, }, } } cursor, err := database.MI.UniColl.Find(ctx, filter, opts) if err != nil { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{ &quot;message&quot;: &quot;University not found&quot;, &quot;error&quot;: err, }) } defer cursor.Close(ctx) for cursor.Next(ctx) { var uni models.University cursor.Decode(&amp;uni) universities = append(universities, uni) } return c.Status(fiber.StatusOK).JSON(fiber.Map{ &quot;timestamp&quot;: time.Now().UTC(), &quot;data&quot;: universities, }) } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T21:09:35.237", "Id": "268580", "Score": "0", "Tags": [ "performance", "json", "go", "mongodb" ], "Title": "API handler to retrieve universities from MongoDB" }
268580