body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am making a Tic-tac-toe game and I have the basic board but I am repeating the code and it is very badly written. I am wondering how I can use better practices to write the DOM elements that I need.</p> <p>I am referring to the function boardController.buildBoard() which can be found here:</p> <p><a href="https://github.com/robbiesoho/TTTJS/blob/master/assets/js/script.js" rel="nofollow noreferrer">https://github.com/robbiesoho/TTTJS/blob/master/assets/js/script.js</a></p> <p>There are nine buttons and here are the first two</p> <pre><code>const boxOne = document.createElement('div'); boxOne.classList.add('boxOne'); const buttonOne = document.createElement('button') buttonOne.classList.add("button") buttonOne.setAttribute('type', 'button'); buttonOne.addEventListener('click', () =&gt; { boxOne.classList.add('token'); boxOne.textContent = playerController.activePlayer; boardController.board[0] = playerController.activePlayer; gameController.afterButtonIsPressed(); gameController.winnerAction; }); const boxTwo = document.createElement('div'); boxTwo.classList.add('boxTwo'); const buttonTwo = document.createElement('button') buttonTwo.classList.add("button") buttonTwo.setAttribute('type', 'button'); buttonTwo.addEventListener('click', () =&gt; { boxTwo.classList.add('token'); boxTwo.textContent = playerController.activePlayer; boardController.board[1] = playerController.activePlayer; gameController.afterButtonIsPressed(); gameController.winnerAction; }); </code></pre> <p>I am new to JS and know only enough to know that this is not a good way to write this. Thank you in advance</p>
[]
[ { "body": "<h2>Factor repeated code into a function</h2>\n\n<p>Any code that is all part of \"doing one thing\" can be naturally captured in a function definition and function call. Any details that differ between the two situations can be made into arguments to the function.</p>\n\n<pre><code>const boxOne = createBox( 'boxOne' );\nconst buttonOne = createButton( boxOne, 0 );\nconst boxTwo = createBox( 'boxTwo' );\nconst buttonTwo = createButton( boxTwo, 1 );\n\nfunction createBox( name ){\n var box = document.createElement('div');\n box.classList.add( name );\n return box;\n}\nfunction createButton( box, idx ){\n var button = document.createElement('button')\n button.classList.add(\"button\")\n button.setAttribute('type', 'button');\n button.addEventListener('click', () =&gt; {\n box.classList.add('token');\n box.textContent = playerController.activePlayer;\n boardController.board[idx] = playerController.activePlayer;\n\n gameController.afterButtonIsPressed();\n gameController.winnerAction;\n });\n return button;\n}\n</code></pre>\n\n<p>This doesn't just apply to code that is repeated. Any block of code where you find yourself writing a comment about what it is doing could probably be expressed as a function. The function's name can express the idea of the comment. And by removing the bulk of code to a different location, it can make the main-line code easier (faster) to read. In the code here for example, the two lines</p>\n\n<pre><code> gameController.afterButtonIsPressed();\n gameController.winnerAction;\n</code></pre>\n\n<p>would make for a nice small function. And a single line call to it probably wouldn't need to be set off by a paragraph break. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T18:59:10.303", "Id": "242653", "ParentId": "242649", "Score": "2" } } ]
{ "AcceptedAnswerId": "242653", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T15:54:00.667", "Id": "242649", "Score": "2", "Tags": [ "javascript", "dom" ], "Title": "Creating multiple DOM buttons in JavaScript (I am not DRYing)" }
242649
<p>I just finished up this script that crawls hundreds of local git repos for csv files and then stores them into a database. I've tried to follow a "functional" paradigm for this script but am kind of confused with all the side-effects (printing, writing to db, shell subprocess). Definitely looking for a classic code-review with some comments regarding my logic, style, commenting, etc.</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python """Script to stuff all historical data into Nightly.db.""" import sqlite3 import glob import os import subprocess import re import pandas as pd from typing import List, Tuple, Callable def generate_reader(repo_path: str) -&gt; Tuple[Callable[[str], pd.DataFrame], Callable[[str], List]]: """ Closure to maintain state of each repository. A replacement for a mini-class containing state information for each git-repo. This closure returns a tuple of functions. Args: repo_path (str) - absolute path to git-repo. Return: Tuple of functions """ rep_hash = repo_hash(repo_path) rep_date = repo_date(repo_path) def read_and_annotate(file_path: str) -&gt; pd.DataFrame: """Return a data-frame with identifying columns.""" delim_data = (pd.read_csv(file_path, usecols=[i for i in range(0, 12)], error_bad_lines=False, warn_bad_lines=False, memory_map=True) .assign(repo_root=repo_path, repo_hash=rep_hash, repo_date=rep_date, full_path=file_path)) # Let's only grab a few columns for now return delim_data[["repo_root", "repo_hash", "repo_date", "full_path", "simulation_alive_time"]] def repo_paths(pattern: str) -&gt; List: """ Return list of files matching glob pattern. Args: pattern (str) - glob pattern for files of interest. Return: List of absolute file-paths. """ return glob.glob(f"{repo_path}/assessment/**/{pattern}", recursive=True) return (read_and_annotate, repo_paths) def repo_hash(repo_path: str) -&gt; str: """ Return the current commmit hash of a repo. This function runs a shell subprocess to fetch the most-recent commit-hash from the git-repo provided. Args: repo_path (str): absolute path to git-repo Return: str - commit hash """ # Use universal_newlines to get a string instead of bytes proc = subprocess.Popen(['git', 'ls-remote', repo_path, 'HEAD'], shell=False, stdout=subprocess.PIPE, universal_newlines=True) return re.match(r'(\S+)', proc.communicate()[0]).group(0) def repo_date(repo_path: str) -&gt; str: """ Return the date-code of given file-path. This function uses a regexp to fetch the date-code (e.g. 20200305) from the provided repository path. Args: repo_path (str) - path to relevant git repository Return: str - unformatted date code """ return re.search(r'[0-9]{8}', repo_path).group() def crawl_repo(repo_path: str) -&gt; None: """ Wrapper function to write csv data into Nightly.db. This function will handle looping through a repo's respective csv files. It will also handle KeyErrors and OSErrors coming from the underlying pandas `read_csv()` function. Args: repo_path (str) - path to git repo containing csv files. Return: None - this function just launches the `write_to_db()` function. """ reader, path_finder = generate_reader(repo_path) for data in path_finder("*_metrics.csv"): try: result = reader(data) except KeyError as e: reader_error(repo_path, data, e) continue except OSError as e: permission_error(repo_path, data, e) continue else: reader_success(result, repo_path, data) write_to_db(result) return None def write_to_db(df): """ Write a pandas dataframe to Nightly.db. Args: df (DataFrame) - pandas dataframe of csv file. Return: None """ conn = sqlite3.connect("Nightly.db") df.to_sql('PERF', conn, if_exists='append', index=False) conn.commit() conn.close() return None def stdout_printer(rp: str, fp: str, msg: str) -&gt; None: """ Generalized printer function. This function provides the base for all user consumed output in the script. Args: rp (str) - absolute path to git repo fp (str) - absolute path to current csv file msg (str) - custom message to output to the user Return: None """ output = f""" {'-' * 72} repo_path: {rp} file_path: {os.path.basename(fp)} {msg} {'-' * 72} """ print(output) return None def permission_error(rp: str, fp: str, e: Exception) -&gt; None: """ Handle bad permissions on csv file. There are a few csv files that currently have permissions that prevent pandas from reading in the data. This function outputs the error and logs the offending file path. Args: rp (str) - absolute path to git repo fp (str) - absolute path to current csv file e (Exception) - thrown by a try/catch block. Return: None """ stdout_printer(rp, fp, f"Exception: {str(e)}") log_to_file(fp, 'bad_permissions.txt') return None def reader_error(rp: str, fp: str, e: Exception) -&gt; None: """ Handle bad permissions on csv file. There are a few csv files that currently don't have the proper column names we need causing pandas to throw a KeyError. This function outputs the error and logs the offending file path. Args: rp (str) - absolute path to git repo fp (str) - absolute path to current csv file e (Exception) - thrown by a try/catch block. Return: None """ stdout_printer(rp, fp, f"Exception: {str(e)}") log_to_file(fp, 'key_error.txt') return None def reader_success(df, rp: str, fp: str) -&gt; None: """ Output information pertaining to a successful data read-in. If pandas read-in is successful, we'll output the head of the dataframe. Args: df (DataFrame) - data-frame of csv file. rp (str) - absolute path to git repo. fp (str) - absolute path to csv file Return: None """ data_preview = (df.head() .to_string(col_space=3, justify='match-parent', max_colwidth=10, index=False, line_width=82) .replace('\n', '\n\t')) stdout_printer(rp, fp, f"Data:\n\t{data_preview}") return None def log_to_file(fp: str, file_name: str) -&gt; None: """ Write file-path that caused exception to specified file. This impure function will log problematic file-paths that can be further examined. Args: fp (str): problematic file-path to log. file_name (str): name of log file Return: None """ with open(file_name, 'a') as log: log.write(f"{fp}\n") return None def main(): conn = sqlite3.connect("Nightly.db") c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS PERF (repo_root text, \ repo_hash text, repo_date text, \ full_path text, simulation_alive_time numeric)') conn.commit() conn.close() bison_git_dirs = glob.glob("/projects/bison/git/bison_[0-9]*") for repo in bison_git_dirs: crawl_repo(repo) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>I don't think you are doing functional programming in a good way here. If you have to jump through too many hoops to inject state into your functions, and have functions that have side-effects and explicitly <code>return None</code>, then this is probably not functional programming.</p>\n\n<p>The easiest solution would probably be to write a <code>Repo</code> class, that consolidates all functions regarding to one repository:</p>\n\n<pre><code>class Repo:\n def __init__(self, path):\n self.path = path\n\n @property\n def hash(self):\n proc = subprocess.Popen(['git', 'ls-remote', self.path, 'HEAD'],\n shell=False, stdout=subprocess.PIPE,\n universal_newlines=True)\n return re.match(r'(\\S+)', proc.communicate()[0]).group(0)\n\n @property\n def date(self):\n return re.search(r'[0-9]{8}', self.path).group()\n\n def files(self, pattern):\n return glob.glob(f\"{self.path}/assessment/**/{pattern}\", recursive=True)\n\n def read_csv_annotated(self, path) -&gt; pd.DataFrame:\n \"\"\"Read a CSV file and annotate it with information about the repo.\"\"\"\n try:\n df = pd.read_csv(path, usecols=[i for i in range(0, 12)],\n error_bad_lines=False, warn_bad_lines=False,\n memory_map=True)\n except OSError as e:\n permission_error(repo_path, data, e)\n return\n df = df.assign(repo_root=self.path,\n repo_hash=self.hash,\n repo_date=self.date,\n full_path=path)\n\n # Let's only grab a few columns for now\n try:\n return df[[\"repo_root\", \"repo_hash\", \"repo_date\", \"full_path\",\n \"simulation_alive_time\"]]\n except KeyError as e:\n reader_error(repo_path, data, e)\n</code></pre>\n\n<p>The actual writing to the DB should be left as the job of the consumer of this output:</p>\n\n<pre><code>def create_table(file_name):\n conn = sqlite3.connect(file_name)\n c = conn.cursor()\n c.execute('CREATE TABLE IF NOT EXISTS PERF (repo_root text, \\\n repo_hash text, repo_date text, \\\n full_path text, simulation_alive_time numeric)')\n conn.commit()\n conn.close()\n\n\nif __name__ == \"__main__\":\n create_table(\"Nightly.db\")\n bison_git_dirs = glob.glob(\"/projects/bison/git/bison_[0-9]*\")\n for repo in map(Repo, bison_git_dirs):\n for csv_file in repo.files(\"*_metrics.csv\"):\n write_to_db(repo.read_csv_annotated(csv_file))\n</code></pre>\n\n<p>Of course, if you really want to not use classes, that is also possible, but the latter part is still true. Only in functional programming you probably want an interface such that it works like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n create_table(\"Nightly.db\")\n bison_git_dirs = glob.glob(\"/projects/bison/git/bison_[0-9]*\")\n dfs = (annotate_df(read_file(csv_file), repo_info(repo_path))\n for repo_path in bison_git_dirs\n for csv_file in csv_files(repo_path))\n for df in dfs:\n write_to_db(df)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:29:05.573", "Id": "476204", "Score": "0", "body": "Thanks for the comments. For the code you provided, how would I then handle `read_csv_annotated` throwing an exception and then passing `None` into `write_to_db()` and breaking the code. I just want to skip and log that file if an exception is thrown." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:41:40.050", "Id": "476205", "Score": "0", "body": "@dylanjm Just handle the exceptions in `read_csv` and the resulting `None` in `annotate_df` and in `write_to_db`, if you are talking about the second code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T19:39:31.990", "Id": "242656", "ParentId": "242651", "Score": "0" } } ]
{ "AcceptedAnswerId": "242656", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T17:31:13.583", "Id": "242651", "Score": "1", "Tags": [ "python", "python-3.x", "sql", "functional-programming" ], "Title": "Functional Python Script to write a large amount of CSVs to database" }
242651
<p>I am working to solve a problem where I need to determine if a <code>Point</code> lies on a line connecting two other <code>Points</code>. For example, if I have <code>Point a, b, c</code>, I want to determine if <code>c</code> is on the line segment connecting <code>a</code> and <code>b</code>. In my code, I have a point, <code>me</code> (a in the example) and two lists of points, <code>hits</code> (b in the example) and <code>reachable</code> (c in the example). For each point in hits, I want to determine if there is any point in reachable that is on the line segment that connects me and the point in hits. If there is a point on that line segment, then numHits needs to be decremented. Here is my code:</p> <pre><code>Point me; //Point a from the example above ArrayList&lt;Point&gt; hits = new ArrayList&lt;&gt;(); //a list of Point b's from the example above ArrayList&lt;Point&gt; reachable = new ArrayList&lt;&gt;(); //a list of point c's from the example above for(Point hit : hits) { for(Point p : reachable) { if(!hit.equals(p) &amp;&amp; !me.equals(p)) { //find the equation of a line from me to hit if(hit.x - me.x == 0) { //if the line has an undefined slope... if the line is vertical if( (((p.y &lt;= hit.y) &amp;&amp; (p.y &gt;= me.y)) || ((p.y &gt;= hit.y) &amp;&amp; (p.y &lt;= me.y))) &amp;&amp; p.x - me.x == 0) { //if there is any occupied point on that line in between me and the hit, that point blocks the hit numHits--; break; } } else { //create a line from me to the hit... if there is any occupied point on that line in between me and the hit, that point blocks the hit double deltaY = hit.y - me.y; double deltaX = hit.x - me.x; double m = deltaY / deltaX; //slope double b = me.y - (double)(m*me.x); //y intercept if((double) p.y == ((double)(m * p.x) + b)) { //if this point is on the same line if( ((p.x &lt;= hit.x &amp;&amp; p.x &gt;= me.x) &amp;&amp; (p.y &lt;= hit.y &amp;&amp; p.y &gt;= me.y)) || ((p.x &lt;= hit.x &amp;&amp; p.x &gt;= me.x) &amp;&amp; (p.y &gt;= hit.y &amp;&amp; p.y &lt;= me.y)) || ((p.x &gt;= hit.x &amp;&amp; p.x &lt;= me.x) &amp;&amp; (p.y &gt;= hit.y &amp;&amp; p.y &lt;= me.y)) || ((p.x &gt;= hit.x &amp;&amp; p.x &lt;= me.x) &amp;&amp; (p.y &lt;= hit.y &amp;&amp; p.y &gt;= me.y))) { //if the point is in between me and the hit numHits--; break; } } } } } } </code></pre> <p>My code works to determine if there is any point in <code>reachable</code> between <code>me</code> and each point in <code>hits</code>, it just gets incredibly slow the larger <code>hits</code> and <code>reachable</code> get. For example, if hits has a size of 780,000 and reachable has a size of 1,500,000 the code takes a very long time to run. I was wondering how I may be able to optimize this to run more quickly. I'm not sure if the bottleneck issue lies in the loops themselves or in the code within the loops. Any help or optimization ideas are greatly appreciated. Thank you!</p>
[]
[ { "body": "<p>It is normally good to break code into several methods.\nEverything that is inside your</p>\n\n<p><code>if(!hit.equals(p) &amp;&amp; !me.equals(p))</code> </p>\n\n<p>should be moved to a separate method taking as input those 3 points a,b and c</p>\n\n<p>When coding problems of a mathematical flavor it is often very useful to support your code with some kind of theory.</p>\n\n<p>In this case you might want to look up the mathematical terms \"dot product\" and \"cross product\". Once you understand those it becomes easy to implement your function.</p>\n\n<p>And remember to make several functions (dotProduct() and crossProduct()) so you can reuse code later.</p>\n\n<p>When it comes to performance you need to look at your algorithm.\nThere is no need to test all pairs of points (hit, p).\nMaybe you should make a small method that computes the angle of a vector from me to p? If angle is the same they hit, otherwise they miss. </p>\n\n<p>So the question becomes given a list of angles for points in hits and a list of angles in reachable, do they contain a common angle?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:35:30.197", "Id": "242661", "ParentId": "242652", "Score": "5" } }, { "body": "<p>I have some suggestions.</p>\n\n<p>Those will not help to make the code faster but cleaner.</p>\n\n<h1>Extract some of the logic to methods.</h1>\n\n<p>By doing that you will make the code shorter and easier to read. Also, you will be able to remove the comments if the methods name is descriptive enough.</p>\n\n<p>Examples :</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private static boolean isOnSameLine(double py, int px, double m, double b) {\n return py == ((m * px) + b);\n }\n\n private static boolean isUndefinedSlope(int hitx, int mex) {\n return hitx - mex == 0;\n }\n</code></pre>\n\n<h1>Invert the logic to remove <a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">arrow code</a></h1>\n\n<p>In your code, you can invert the <code>if</code> condition to remove one layer of bracket.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (hit.equals(p) || me.equals(p)) {\n continue;\n}\n//[...]\n</code></pre>\n\n<h1>Extract the expression to variables when used multiple times.</h1>\n\n<p>In your code, you have multiple instances where you could extract the evaluations into variables.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int py = p.y;\nint hitx = hit.x;\nint mex = me.x;\n</code></pre>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n int numHits = 0;\n Point me = new Point(); //Point a from the example above\n ArrayList&lt;Point&gt; hits = new ArrayList&lt;&gt;(); //a list of Point b's from the example above\n ArrayList&lt;Point&gt; reachable = new ArrayList&lt;&gt;(); //a list of point c's from the example above\n\n for (Point hit : hits) {\n for (Point p : reachable) {\n if (hit.equals(p) || me.equals(p)) {\n continue;\n }\n\n\n //find the equation of a line from me to hit\n int py = p.y;\n int hitx = hit.x;\n int mex = me.x;\n\n if (isUndefinedSlope(hitx, mex)) {\n if (isOccupiedPointBetweenMeAndHit(me, hit, p, py, hitx, mex)) {\n numHits--;\n break;\n }\n } else {\n //create a line from me to the hit... if there is any occupied point on that line in between me and the hit, that point blocks the hit\n double deltaY = hit.y - me.y;\n double deltaX = hitx - mex;\n\n double m = deltaY / deltaX; //slope\n double b = me.y - (m * mex); //y intercept\n\n if (isOnSameLine(py, p.x, m, b)) {\n if (isPointBetweenMeAndHit(hitx, mex, hit.y, me.y, py, p.x)) { //if the point is in between me and the hit\n numHits--;\n break;\n }\n }\n }\n }\n }\n}\n\nprivate static boolean isOccupiedPointBetweenMeAndHit(Point me, Point hit, Point p, int py, int hitx, int mex) {\n return (((py &lt;= hitx) &amp;&amp; (py &gt;= me.y)) || ((py &gt;= hit.y) &amp;&amp; (py &lt;= me.y))) &amp;&amp; p.x - mex == 0;\n}\n\nprivate static boolean isPointBetweenMeAndHit(int hitx, int mex, int hity, int mey, int py, int px) {\n return (px &lt;= hitx &amp;&amp; px &gt;= mex &amp;&amp; py &lt;= hity &amp;&amp; py &gt;= mey) ||\n (px &lt;= hitx &amp;&amp; px &gt;= mex &amp;&amp; py &gt;= hity &amp;&amp; py &lt;= mey) ||\n (px &gt;= hitx &amp;&amp; px &lt;= mex &amp;&amp; py &gt;= hity &amp;&amp; py &lt;= mey) ||\n (px &gt;= hitx &amp;&amp; px &lt;= mex &amp;&amp; py &lt;= hity &amp;&amp; py &gt;= mey);\n}\n\nprivate static boolean isOnSameLine(double py, int px, double m, double b) {\n return py == ((m * px) + b);\n}\n\nprivate static boolean isUndefinedSlope(int hitx, int mex) {\n return hitx - mex == 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:34:08.137", "Id": "242667", "ParentId": "242652", "Score": "3" } }, { "body": "<p>(just rewriting, @mlb solution)</p>\n\n<h2>Let solve the Algorithm then improve the code</h2>\n\n<p><span class=\"math-container\">$$ \\text{Let }X = \\{x_0, x_1, x_2, ... x_p\\} \\text{ points.}$$</span> \n<span class=\"math-container\">$$ \\text{Let }S = \\{ \\text{all the pairs }(x_i, x_j): i \\neq j, (x_i, x_j) \\in X\\times X\\} $$</span></p>\n\n<p><span class=\"math-container\">$$\\text{A point }x_m\\text{ lies on some segment on } s \\in S: \\text{ if }\n\\exists i,j,k: (x_i,x_j) \\in S\\text{ , }(x_i, x_k) \\in S\\text{ , and }(x_i, x_j) \\| (x_i, x_k)$$</span>\nIn that case, m can be all the three index. We don't know yet. To solve that issue, points need to be sorted.</p>\n\n<p>To detect if two segments are parallels, you have some options. \na) just take the difference between the points and normalize.\nb) calculate the slope of the two segments. They should be the same.</p>\n\n<h2>Now, the efficient solution</h2>\n\n<p><span class=\"math-container\">$$\\text{First of all, the solution is }O(N^2)\\text{, } $$</span>\n<span class=\"math-container\">$$\\text{because creating segments from all the points is }O(N^2).$$</span></p>\n\n<p>To keep that complexity, operations over segments should be done in constant time.</p>\n\n<p>The idea is keep track of all \"lines\" that a segment lies on. For each new segment, we verify if the line was already found in our map.</p>\n\n<p>A line is defined by a point and the slope. To be consistent, let us take the point at x coordinate equals to 0. The point would the format (y, 0). There is an edge case when slopes is orthogonal to x-coordinate. In that case, we can take y=0.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Line {\n private final Double slope;\n private final Double y_0;\n // override equals and hashcode\n // override the constructor\n}\n</code></pre>\n\n<p>Also, creates a class Point that implements Comparable. One point is less than other point if comes before (x coordinate is less than) and below (as second criteria, y coordinate is less than) the other point.</p>\n\n<p>Sort all the points.</p>\n\n<p>Now, you can build a map Map(Line, List(Point)) and verify for each segment if the same line was already add to the map.</p>\n\n<p>All the points between the last element of the List and the first element of the List are points between other two points.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T08:35:05.137", "Id": "476531", "Score": "0", "body": "It seems you are trying to solve a more general question than the poster. As far as I understood he has only n segments (from me to hits) and want to count all points in reachable that is on one of these segments. The solution should be O(n log n). Using a HashMap could make it faster in practice depending on the hashcode. I would use either HashMap or sorting, not both." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T01:05:18.380", "Id": "476677", "Score": "0", "body": "you may be right but I cannot be sure. the OP problem statement is way different from OP solution. We need to have the original requirement to be sure. \nBy OP solution, an efficient solution would be O(n + m). [I will write the code]" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T01:11:04.517", "Id": "242724", "ParentId": "242652", "Score": "1" } } ]
{ "AcceptedAnswerId": "242661", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T17:57:47.980", "Id": "242652", "Score": "4", "Tags": [ "java", "performance", "time-limit-exceeded", "memory-optimization" ], "Title": "How can I optimize my code that uses nested for loops?" }
242652
<p>Given a range of integers, count the number of ways each single integer can be used in unique sets of three operands that all add up to a given sum.</p> <p>For a technical interview I was asked to solve a puzzle (Without coding). The puzzle was given a 3X3 grid with unique integers 1-9 each filling a location on the grid, arrange the numbers so that each set of 3 numbers in a line (Vertical, horizontal and diagonal) all add up to 15. I wanted to know what the occurrence of numbers are for all possible unique sets of 3 unique integers. That would go a long way to help solve the problem. Because different locations of the grid will have different set needs. The sides of the grid will need 2 sets that all contain the same number. The corners need 3 sets that all contain the same number. The center will need 4 sets that all contain the same number. There is only 1 center, 4 sides, and 4 corners. I suspected that there was only number that would support 4 sets of 3 unique numbers, I suspected that number was 5. I wanted to write a program to show a count the occurrence of every number across all unique sets of 3 numbers between 1 and 9, to help me solve the puzzle. </p> <p>This is what I came up with in C#:</p> <pre><code> /// &lt;summary&gt; /// Given a range of integers, count the number of ways each single integer can be used in unique sets of three /// operands that all add up to a given sum. /// &lt;/summary&gt; /// &lt;param name="sum"&gt;The sum that each set of three operands should equal.&lt;/param&gt; /// &lt;param name="OperandMinimum"&gt;The highest integer in the range of integers included as possible opperands.&lt;/param&gt; /// &lt;param name="OperandMaximum"&gt;The lowest integer in the range of integers included as possible opperands.&lt;/param&gt; /// &lt;returns&gt;A Dictionary of the count (value) of ways a single integer (key) can occur in unique sets of three operands /// that all add up to a given sum.&lt;/returns&gt; public static Dictionary&lt;int,int&gt; getCountofOpperandOccurancesIn_ThreeUniqueOperandsForSingleSum(int sum, int OperandMinimum = 1, int OperandMaximum = 9) { Dictionary&lt;int, int&gt; SumOfOperands = new Dictionary&lt;int, int&gt;(); List&lt;int[]&gt; ListOfThreeOperands = GetAllGroupsOfThreeUniqueOperandsForSingleSum(sum, OperandMinimum = 1, OperandMaximum = 9); foreach(int[] operandsGroup in ListOfThreeOperands) { foreach(int operand in operandsGroup) { if (SumOfOperands.ContainsKey(operand)) { SumOfOperands[operand]++; } else { SumOfOperands.Add(operand, 1); } } } return SumOfOperands; } /// &lt;summary&gt; /// Get three unique operands for a single sum such that operand1 + operand2 + operand3 = sum /// where all operands are unique and within a range of adgacent integer values. /// &lt;/summary&gt; /// &lt;param name="sum"&gt;The sum that all int array groups of three returned are equal to.&lt;/param&gt; /// &lt;param name="OperandMinimum"&gt;The maximum value of all unique operators that can be included as part of the int array groups returned.&lt;/param&gt; /// &lt;param name="OperandMaximum"&gt;The minimum value of all unique operators that can be included as part of the int array groups returned.&lt;&lt;/param&gt; /// &lt;returns&gt;A list of int array groups where all operands in a group are unique and together form a sum passed to the method.&lt;/returns&gt; public static List&lt;int[]&gt; GetAllGroupsOfThreeUniqueOperandsForSingleSum(int sum, int OperandMinimum = 1, int OperandMaximum = 9) { List&lt;int[]&gt; ListOfThreeOperands = new List&lt;int[]&gt;(); for (int FirstOperand = OperandMinimum; FirstOperand &lt;= OperandMaximum; FirstOperand++){ for (int SecondOperand = OperandMinimum; SecondOperand &lt;= OperandMaximum; SecondOperand++){ if (SecondOperand == FirstOperand) { break; } for (int third = OperandMinimum; third &lt;= OperandMaximum; third++){ if (third == FirstOperand || third == SecondOperand) { break; } if (FirstOperand + SecondOperand + third == sum) { ListOfThreeOperands.Add( new int[] { FirstOperand, SecondOperand, third }); } } } } return FilterForUniqueOperands(ListOfThreeOperands); } public static List&lt;int[]&gt; FilterForUniqueOperands(List&lt;int[]&gt; OperandList) { List&lt;int[]&gt; filteredList = new List&lt;int[]&gt;(); for (int i= 0; i&lt; OperandList.Count; i++) { if (filteredList.Count &lt;= 0) { filteredList.Add(OperandList[i]); } else { bool IsPresent = false; foreach (int[] operandGroup in filteredList) { if (IsAllValuesPersentInEach(OperandList[i], operandGroup)) { IsPresent = true; break; } } if (!IsPresent) { filteredList.Add(OperandList[i]); } } } return filteredList; } public static bool IsAllValuesPersentInEach(int[] A, int[] B) { if (A.Length != B.Length || A.Length &lt;= 0 || B.Length &lt;= 0) { throw new Exception("Arrays A and B must contain the same number of values Greater than 0"); } bool IsAllValuesPersent = true; foreach( int valPresent in A) { if (!B.Contains(valPresent)) { IsAllValuesPersent = false; } } return IsAllValuesPersent; } </code></pre> <p>The results of the algorithm (shown below) have shown me that 5 has to be the middle number and the side numbers must be 1,3,7, and 9. This allowed me to solve the puzzle in 8 unique ways.</p> <pre><code>Number - occurrence count 1 - 2 2 - 3 3 - 2 4 - 3 5 - 4 6 - 3 7 - 2 8 - 3 9 - 2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:11:32.313", "Id": "476196", "Score": "1", "body": "15 is not chosen randomly here. It is the only number for which you can arrange the grid so that all rows and columns and diagonals equal that number. Because sum of all those numbers is 45. Lets say a,b,c from interval 1-9 and a<c and a+b+c=15. If b Is 5 then a<b<c is always true. For any other b, this is not always true. Therefore 5 must be in the middle :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T04:48:13.653", "Id": "476241", "Score": "1", "body": "Since b=5, then a+c=10 which is even. And so a and c must both be even or both be odd. If we put odd number in one corner and its opposite then we need 6 more even numbers to fill the rest, but we only have 4. Therefore corners must be even. Just to confirm, if I put 2 even numbers in a corner and its opposite, then i need 4 odd and 2 even numbers to fill the rest, which is what I have. The 8 possibilities are just rotations (x4) and reflection over a central axis (x2)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T16:09:28.177", "Id": "476307", "Score": "0", "body": "@slepic I see how all you have said is true, but I find your first comment slightly confusing. Could you connect your conclusions to your statements? For example when you say \"therefore 5 must be in the middle\", I know that is true but I am not sure how it directly connects to your statements. I ask because I am intrigued and I want to understand you proof a little better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:21:03.487", "Id": "476320", "Score": "0", "body": "Sry I deleted my second try because it didnt feel any clearer. Ill try to find a way to explain it somewhat simpler And get Back to you..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:10:08.253", "Id": "476333", "Score": "0", "body": "@slepic I think you can build on what you have rather than starting from scratch. I think I need to see a connection between \" If b Is 5 then a<b<c is always true. For any other b, this is not always true.\" and \"Therefore 5 must be in the middle\". I accept all that, but I want to see how they connect logically. I can put it as a question: Why must a number be in the middle if it is the only number b where a<b<c is always true?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T06:07:20.617", "Id": "476518", "Score": "0", "body": "Alright i think the best explanation i can give you is that there is limited amount of numbers to choose from. Number 5 Is in Middle of 1-9. If you put anything else in the center, you won't have enough numbers left to create balance. If you put smaller than 5 in center you Will be missing that small number And one side of table Will get too heavy. If you put larger then 5 in Middle, you Will be missing that big number to place somewhere else And one side of the table will remain too light. It's just all about symmetry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T06:11:30.220", "Id": "476519", "Score": "1", "body": "Btw you can turn this into a set of 9 equations with 9 unknowns, do some substitutions And figure out that 5 must be in center regardless of some conditions (ie it doesnt matter if all those numbers are different to each other or not, 5 must be in center anyway)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T16:17:41.583", "Id": "476822", "Score": "0", "body": "@slepic Brilliant." } ]
[ { "body": "<p>I think perhaps, you're being to literal with this. </p>\n\n<p>First off, when you are grouping your data by digits and getting the count of each one, a simple <code>int[]</code> will do. In this case to keep things simple a 10 element array will give you indexes from 1-9.</p>\n\n<p>Also consider, if you start at 9, the difference is 6 divide by 2 will result in 3 and 3 as the other 2 digits necessary. Now you must have unique digits so you increase one by 1 and decrease the other by 1. Now you start at 4 and 2. Now keep increasing and decreasing until the high one reaches the start number or the low one reaches 0. Each time you increase and decrease increment the elements at the indexes for the start, and the 2 other digits. When this loop finishes decrease the start number, until the start number reaches 5. At this point you've found all the unique combinations that add to 15. 5 works as a limit since 15/3=5. add one and subtract 1 and you get 4,5,6 any number you consider that is less than 6 will already have been considered.</p>\n\n<p>It could look like this:</p>\n\n<pre><code>static int[] Sum15Dist()\n{\n var dist = new int[10];\n const int target = 15;\n int start = 9;\n while(start &gt; 5)\n {\n int intA = (int)Math.Ceiling((target - start)/2.0);\n int intB = target - start - intA;\n if(intA == intB)\n {\n ++intA;\n --intB;\n }\n while(intB &gt; 0 &amp;&amp; intA &lt; start)\n {\n ++dist[start];\n ++dist[intA++];\n ++dist[intB--];\n }\n --start;\n }\n return dist;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T22:53:30.180", "Id": "242669", "ParentId": "242654", "Score": "1" } } ]
{ "AcceptedAnswerId": "242669", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T19:04:16.043", "Id": "242654", "Score": "0", "Tags": [ "c#" ], "Title": "given ints 1-9 count the ways unique sets of 3 add up to a given sum" }
242654
<p>I had posted this on StackOverflow — someone pointed me here.</p> <p>My code is working, but it's incredibly verbose and I know that it can be made more compact. I just don't know how :-)</p> <p>I'm building an audio portfolio. When a button is clicked, a sequence of events happens. When another button is clicked, all other active buttons are killed and the sequence for that specific button runs.</p> <p>The buttons are invisible and are placed on a visualisation of a switch. When clicked, an image of the switch flicked into its "activated" state has its class of "display: none" removed. That should give the user the impression that actually flicking a switch starts playing audio.</p> <p>Like so:</p> <pre><code>$(function(){ // FIRST BUTTON $('.button01').click(function() { if ($('.switch01').hasClass('activated')){ // So if button.button01 is clicked and img.switch01 has class "activated" // Kill all audio $('audio').each(function(){ this.pause(); this.currentTime = 0; }); // Turn this switch off $('.switch01').removeClass('activated'); // Kill all info cards showing the playback controls $('.audio-info-card').addClass('d-none'); } else { // If button.button01 is clicked and img.switch01 DOESN'T have class "activated" // Turn all other switches off $('.switch02, .switch03').removeClass('activated'); // Kill all info cards $('.audio-info-card').addClass('d-none'); // Activate this switch and info card $('.switch01').addClass('activated'); $('.audio-info-card#card01').removeClass('d-none'); // Kill all audio $('audio').each(function(){ this.pause(); this.currentTime = 0; }); // Start this audio $('#audio01-player')[0].play(); } }); // SECOND BUTTON $('.button02').click(function() { if ($('.switch02').hasClass('activated')){ // So if button.button02 is clicked and img.switch02 has class "activated" // Kill all audio $('audio').each(function(){ this.pause(); this.currentTime = 0; }); // Turn this switch off $('.switch02').removeClass('activated'); // Kill all info card showing the playback controls $('.audio-info-card').addClass('d-none'); } else { // If button.button02 is clicked and img.switch02 DOESN'T have class "activated" // Turn all other switches off $('.switch01, .switch03').removeClass('activated'); // Kill all info cards $('.audio-info-card').addClass('d-none'); // Activate this switch and info card $('.switch02').addClass('activated'); $('.audio-info-card#card02').removeClass('d-none'); // Kill all audio $('audio').each(function(){ this.pause(); this.currentTime = 0; }); // Start this audio $('#audio02-player')[0].play(); } }); </code></pre> <p>There are 16 buttons. I realize this code is stupid but JS / jQuery isn't my strong suit :-D</p> <p>Fortunately, the code works, but any help making this simpler would be greatly appreciated!</p>
[]
[ { "body": "<h2>Factor out detailed code into subfunctions</h2>\n\n<p>One relatively mechanical thing you could do is transform all of the commented blocks into functions. For a small section, something like this</p>\n\n<pre><code> // Kill all audio\n $('audio').each(function(){ this.pause(); this.currentTime = 0; });\n\n // Turn this switch off\n $('.switch01').removeClass('activated');\n\n // Kill all info cards showing the playback controls\n $('.audio-info-card').addClass('d-none');\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code> killAllAudio();\n turnSwitchOff( '.switch01' );\n killAllInfoCards();\n\n //...\n\nfunction killAllAudio(){\n $('audio').each(function(){ this.pause(); this.currentTime = 0; });\n}\n\nfunction turnSwitchOff( switch ){\n $(switch).removeClass('activated');\n}\n\n// Kill all info cards showing the playback controls\nfunction killAllInfoCards(){\n $('.audio-info-card').addClass('d-none');\n}\n</code></pre>\n\n<p>After this, your top-level algorithm should be much clearer. At the top level it should almost look like pseudocode, except the comments are all calls to subfunctions which do one small named task. </p>\n\n<p>Factoring out code into subfunctions also helps you see \"more code\" by abstracting away small details. With shorter functions, you can see more of them on the screen at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:04:36.730", "Id": "476201", "Score": "0", "body": "Thanks, I'll give that a try!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:22:48.260", "Id": "476442", "Score": "0", "body": "This helped — makes everything more legible indeed. Next step is to combine functions because code still is far from DRY." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T19:50:18.470", "Id": "242658", "ParentId": "242655", "Score": "1" } } ]
{ "AcceptedAnswerId": "242658", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T19:19:02.920", "Id": "242655", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "How can I clean up (DRY) this verbose jQuery code?" }
242655
<p>I'm looking for someone to tell me how I could refactor/change/improve my JS, I'm still learning and really want my code to be the best it can be for when it comes time for me getting a job in the industry. Would really appreciate a professional's help.</p> <p>It's just a fairly simple todo list...</p> <p>Here is the JS</p> <pre><code>let ul = document.getElementById('list'); let input = document.querySelector("input"); let toggle = document.querySelector('.fa-plus'); toggle.addEventListener('click', function() { toggle.classList.toggle('rotated'); input.classList.toggle('hide'); }); input.addEventListener('keydown', function(e) { if (e.keyCode === 13 &amp;&amp; input.value !== '') { addTodo(); }; }); let deleted = () =&gt; { let spans = document.querySelectorAll('span'); for (let span of spans) { span.addEventListener('click', function() { this.parentNode.parentNode.removeChild(this.parentNode); }); }; }; let addTodo = () =&gt; { let listItem = document.createElement('li'); listItem.innerHTML = '&lt;span&gt;&lt;i class="far fa-trash-alt"&gt;&lt;/i&gt;&lt;/span&gt; ' + input.value; listItem.addEventListener("click", function() { this.classList.toggle("lineThrough"); }); ul.appendChild(listItem); deleted(); input.value = ''; }; </code></pre> <p>Here is the link to the project on codepen - <a href="https://codepen.io/ruaridouglas/pen/mdeaaKV" rel="nofollow noreferrer">https://codepen.io/ruaridouglas/pen/mdeaaKV</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T05:07:31.267", "Id": "476243", "Score": "3", "body": "Welcome to CodeReview@SE. If you knew nothing about the task, and were just given this source code: How would you know what it is to do, and if it works as intended?" } ]
[ { "body": "<p>You declare all your variables with <code>let</code>. You aren't using <code>var</code>, so that's good - but it's <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">better to prefer</a> <code>const</code> over <code>let</code> unless you have no choice but to reassign the variable later. (I recently did a check of one of my scripts and found 414 uses of <code>const</code> compared to 16 uses of <code>let</code> - that's the sort of proportion you want to be aiming towards.) Code is most readable when any reader can immediately understand that a variable is never going to be reassigned from its initial value.</p>\n<p>This is a bit opinion-based, but I would prefer to avoid IDs in HTML when possible: they not only automatically create properties on the global object (which can result in strange bugs), but also, only one element with a particular ID can exist in the document at a given time. So, for example, if you were tasked to refactor the code so that multiple lists can be interacted with on a page, you would have to make changes.</p>\n<p>(Actually, in new code, I get the feeling that the &quot;industry standard&quot; is to usually avoid vanilla DOM manipulation like this at all - usually, a framework like React is used instead, allowing for the functional composition of components. Eg, if you had a working <code>TodoList</code>, changing to a page with two of them would be as simple as <code>&lt;div&gt;&lt;TodoList /&gt;&lt;/div&gt;&lt;div&gt;&lt;TodoList /&gt;&lt;/div&gt;</code>)</p>\n<p>You do</p>\n<pre><code>&lt;input onblur=&quot;this.placeholder = 'What do you want to do?'&quot; onfocus=&quot;this.placeholder = ''&quot; placeholder=&quot;What do you want to do?&quot; type=&quot;text&quot;&gt;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/a/59539045\">Never, ever</a> use inline handlers. They have numerous problems (such as executing inside a few confusing <code>with</code> blocks) and have no place in modern code. To attach an event listener to an element, use <code>addEventListener</code> instead.</p>\n<p>But here, you don't need Javascript at all: you can use CSS instead:</p>\n<pre><code>input:focus::placeholder {\n color: transparent;\n}\n</code></pre>\n<p>You sometimes use <code>function</code>s, and you sometimes use arrow functions. Code is best when its style is <em>consistent</em> - I'd recommend picking one and sticking with it everywhere. (I'd prefer arrow functions, since they're always expressions rather than hoisted and reassignable declarations, and because they're usually more concise, and because they make it clear that <code>this</code> is not being captured in the new function.)</p>\n<p>You use <code>KeyboardEvent.keyCode</code>, but it's <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode\" rel=\"noreferrer\">deprecated</a>. As MDN puts it:</p>\n<blockquote>\n<p>This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.</p>\n</blockquote>\n<p>I'd prefer to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\" rel=\"noreferrer\"><code>key</code></a> property instead, which is not only supported, but it's also a whole lot more intuitive when you can simply perform a comparison against a <em>character as a string</em> rather than have to refer to a table mapping keycode numbers to their characters. So, this:</p>\n<pre><code>if (e.keyCode === 13 &amp;&amp; input.value !== '') {\n</code></pre>\n<p>can be replaced with:</p>\n<pre><code>if (e.key === 'Enter' &amp;&amp; input.value !== '') {\n</code></pre>\n<p>The <code>deleted</code> function here:</p>\n<pre><code>let deleted = () =&gt; {\n let spans = document.querySelectorAll('span');\n for (let span of spans) {\n span.addEventListener('click', function() {\n this.parentNode.parentNode.removeChild(this.parentNode);\n });\n };\n};\n</code></pre>\n<p>can be improved. First, its name isn't particularly informative - it's good for a function's name to represent what it does. What this function does is it adds an event listener to each <code>&lt;span&gt;</code> in the document, which deletes the span's ancestor when clicked. A better name would be <code>deleteTodosOnTrashClick</code>.</p>\n<p>But, it selects <em>all</em> <code>&lt;span&gt;</code>s in the document. So, if you had, say, a header with a <code>&lt;span&gt;</code> in addition to the todo list, if the header's span was clicked on, the header would be removed. It would be better to remove only the <code>&lt;span&gt;</code>s which are children of the todo list:</p>\n<pre><code>const spans = ul.querySelectorAll('span');\n</code></pre>\n<p>But you're also adding an event listener to <em>every</em> span, <em>every</em> time a new todo is added. Since these spans are being created dynamically, it would be even better to add an event listener to <em>just</em> the created <code>&lt;span&gt;</code>, at the moment that it's created:</p>\n<pre><code>const addTodo = () =&gt; {\n const listItem = document.createElement('li');\n listItem.innerHTML = '&lt;span&gt;&lt;i class=&quot;far fa-trash-alt&quot;&gt;&lt;/i&gt;&lt;/span&gt; ' + input.value;\n listItem.addEventListener(&quot;click&quot;, function() {\n this.classList.toggle(&quot;lineThrough&quot;);\n });\n ul.appendChild(listItem);\n listItem.querySelector('span').addEventListener('click', () =&gt; {\n listItem.remove();\n });\n input.value = '';\n};\n</code></pre>\n<p>Note the use of <code>.remove()</code>. This is often preferable to <code>removeChild</code> because <code>removeChild</code> requires a reference to both the parent and the child, which can get a bit verbose, as you can see in your original code.</p>\n<p>There's another issue in <code>addTodo</code>. You are creating the HTML string for the new todo <em>by concatenating user input</em>, which should be avoided without taking precautions; this allows the user to execute arbitrary scripts, and insert arbitrary elements, which is a security risk and can result in unpredictable behavior.</p>\n<p>For example, imagine if this was hosted on a website for students learning, where the students have logged in, and one of them got a message saying:</p>\n<blockquote>\n<p>Try pasting the following string into the todo list, you won't believe what happens next!</p>\n<pre><code>&lt;img onerror=&quot;document.body.appendChild(document.createElement('script')).src = 'evil.js'&quot;&gt;\n</code></pre>\n</blockquote>\n<p>(except obfuscated). Then the student could have their login stolen by an attacker, because the site created the HTML by concatenating user input and did not sanitize it beforehand.</p>\n<p>Either strip out all HTML tags from the input first, or assign to the <code>textContent</code> of the container for the text instead, or use <code>insertAdjacentText</code>:</p>\n<pre><code>listItem.innerHTML = '&lt;span&gt;&lt;i class=&quot;far fa-trash-alt&quot;&gt;&lt;/i&gt;&lt;/span&gt; ';\n// ...\nlistItem.insertAdjacentText('beforeend', input.value);\n</code></pre>\n<p>It would also be a good idea (as always) to run the script in strict mode, and put it inside an IIFE so as to avoid global pollution. All together:</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 const ul = document.querySelector('.list');\n const input = document.querySelector(\"input\");\n const toggle = document.querySelector('.fa-plus');\n toggle.addEventListener('click', () =&gt; {\n toggle.classList.toggle('rotated');\n input.classList.toggle('hide');\n });\n\n input.addEventListener('keydown', (e) =&gt; {\n if (e.key === 'Enter' &amp;&amp; input.value !== '') {\n addTodo();\n };\n });\n\n\n const addTodo = () =&gt; {\n const listItem = document.createElement('li');\n listItem.innerHTML = '&lt;span&gt;&lt;i class=\"far fa-trash-alt\"&gt;&lt;/i&gt;&lt;/span&gt; ';\n listItem.addEventListener(\"click\", () =&gt; {\n listItem.classList.toggle(\"lineThrough\");\n });\n ul.appendChild(listItem);\n listItem.querySelector('span').addEventListener('click', () =&gt; {\n listItem.remove();\n });\n listItem.insertAdjacentText('beforeend', input.value);\n input.value = '';\n };\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n font-size: 16px;\n}\n\n*,\n*:before,\n*:after {\n -webkit-box-sizing: inherit;\n -moz-box-sizing: inherit;\n box-sizing: inherit;\n}\n\nbody,\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\np,\nol,\nul {\n margin: 0;\n padding: 0;\n font-weight: normal;\n}\n\nol,\nul {\n list-style: none;\n}\n\nimg {\n max-width: 100%;\n height: auto;\n}\n\n\n/* RESET FINISHED */\n\n@import url('https://fonts.googleapis.com/css2?family=Heebo:wght@500&amp;display=swap');\nbody {\n font-family: 'Heebo', sans-serif;\n background: rgb(200, 230, 201);\n background: linear-gradient(90deg, #00b09b 0%, #96c93d 100%);\n}\n\n#container {\n width: 360px;\n margin: 100px auto;\n background-color: #fff;\n border-radius: 5px;\n box-shadow: 0 0 10px rgba(42, 59, 56, 0.4);\n}\n\nh1 {\n font-size: 1.6em;\n font-weight: bold;\n padding: .8em .5em;\n background: #00b09b;\n color: #fff;\n}\n\n.fa-plus {\n float: right;\n transition: ease-in .2s;\n}\n\n.rotated {\n transform: rotate(45deg);\n -webkit-transform: rotate(45deg);\n -ms-transform: rotate(45deg);\n transition: ease-in .2s;\n}\n\n.hide {\n display: none;\n}\n\ninput {\n clear: left;\n font-size: 1em;\n padding: .8em .5em;\n width: 100%;\n outline: none;\n border-top: none;\n border-left: none;\n border-right: none;\n border-bottom: 1px solid rgba(48, 87, 80, 0.4);\n background-color: rgb(236, 236, 236);\n transition: ease-in .2s;\n}\n\ninput:focus {\n box-shadow: 0 5px 5px rgba(42, 59, 56, .4);\n border-bottom: none;\n}\ninput:focus::placeholder {\n color: transparent;\n}\n\n.lineThrough {\n text-decoration: line-through;\n color: grey;\n transition: ease-in .2s;\n}\n\nli {\n width: 100%;\n line-height: 40px;\n transition: ease-in .2s;\n}\n\nli:nth-child(2n) {\n background-color: rgb(236, 236, 236);\n}\n\nspan {\n background-color: #e74c3c;\n height: 40px;\n margin-right: 10px;\n text-align: center;\n color: #fff;\n width: 0;\n display: inline-block;\n transition: 0.2s linear;\n opacity: 0;\n}\n\nli:hover span {\n width: 40px;\n opacity: 1;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://kit.fontawesome.com/391e6a689e.js\" crossorigin=\"anonymous\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"assets/js/lib/jquery-3.4.1.min.js\"&gt;&lt;/script&gt;\n&lt;div id=\"container\"&gt;\n &lt;h1&gt;Javascript To-Do List&lt;i class=\"fa fa-plus rotated\"&gt;&lt;/i&gt;&lt;/h1&gt;\n &lt;input placeholder=\"What do you want to do?\" type=\"text\"&gt;\n &lt;ul class=\"list\"&gt;\n\n &lt;/ul&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": "2020-05-21T03:55:49.320", "Id": "476239", "Score": "0", "body": "Thankyou so much for this. I really appreciate you taking the time to provide all this information, invaluable. I'll get to making the changes right away." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T07:42:34.497", "Id": "476256", "Score": "2", "body": "[About strict mode](https://tvernon.tech/blog/javascript-strict-mode). You don't need to wrap the code in an IIFE to avoid pollution of the global namespace. Just wrap it in `{}`, i.e. enclose it in a [code block](https://javascript.info/closure)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T12:08:29.650", "Id": "476271", "Score": "0", "body": "@KooiInc I don't like using plain blocks because they're quite unusual to see, and because they [don't get transpiled correctly](https://babeljs.io/repl) - if you plug in `{\n const foo = 'foo';\n}`, you get `{\n var foo = 'foo';\n}`, resulting in global pollution. An IIFE is a bit better choice, I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T12:40:55.883", "Id": "476274", "Score": "0", "body": "@Kooilnc Thankyou for the feedback, I was unaware of this, will look into it and look to use moving forward." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:57:51.547", "Id": "242665", "ParentId": "242659", "Score": "8" } } ]
{ "AcceptedAnswerId": "242665", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T19:56:13.297", "Id": "242659", "Score": "3", "Tags": [ "javascript", "beginner" ], "Title": "Simple todo list in Javascript" }
242659
<p>I want to extract the <strong>headers data</strong> and column data <strong>(not row data)</strong> from an HTML table using JavaScript.</p> <p>Is this a good approach of doing it? And how can I simplify this using jQuery?</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>let table = document.getElementById('tab') debugger let headers = Array.from(table.rows[0].cells).map(x =&gt; x.innerText) let columnData = Array.from(table.rows). slice(1, table.rows.length). map(row =&gt;Array.from(row.cells).map(x =&gt; x.innerText)) .reduce((acc,rowData)=&gt;{ rowData.forEach((value,index)=&gt;{ acc[index]= acc[index] || [ ] acc[index].push(value) }) return acc },[]) console.log(headers) console.log(columnData)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="tab"&gt; &lt;tr&gt; &lt;th&gt; Name &lt;/th&gt; &lt;th&gt; Age &lt;/th&gt; &lt;th&gt; Location &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt; Jason &lt;/th&gt; &lt;th&gt; 22 &lt;/th&gt; &lt;th&gt; Texas &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt; Lawson &lt;/th&gt; &lt;th&gt; 21 &lt;/th&gt; &lt;th&gt; Florida &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt; Jose &lt;/th&gt; &lt;th&gt; 25 &lt;/th&gt; &lt;th&gt; London &lt;/th&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Always use <code>const</code></a> to declare variables - only use <code>let</code> when you must reassign. This keeps code readable, because then a reader of the code doesn't have to constantly keep in mind that a variable might be reassigned later. (If you use <code>let</code> but then <em>don't</em> reassign, it can still be confusing - in professional code, one might think \"Why is <code>let</code> being used here? Was this meant to be reassigned in a section of code that was later removed, or something?)</p>\n\n<p><code>Array.from</code> accepts an optional mapper function as a second parameter. Any time you have:</p>\n\n<pre><code>Array.from(arrayLike).map(mapper)\n</code></pre>\n\n<p>you may replace it with</p>\n\n<pre><code>Array.from(arrayLike, mapper)\n</code></pre>\n\n<p>(If all you're doing is converting an array-like object into an array, some prefer spread syntax because it's even more concise: <code>[...arrayLike]</code>)</p>\n\n<p><code>innerText</code> is a <a href=\"http://perfectionkills.com/the-poor-misunderstood-innerText/\" rel=\"nofollow noreferrer\">weird property</a> introduced by Internet Explorer (<em>outside</em> of web standards originally) that has a number of odd quirks. Unless you're <em>deliberately looking</em> to invoke those quirks, it would be a better idea to use <code>textContent</code> instead to retrieve text from an element.</p>\n\n<p>You can easily distinguish the first <code>tr</code> from the other <code>tr</code>s by using the query string <code>#tab tr:first-child</code> or <code>#tab tr:nth-child(n + 2)</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const headers = Array.from(\n document.querySelectorAll('#tab tr:first-child th'),\n th =&gt; th.textContent.trim()\n);\n// Make an empty array for every item in headers:\nconst data = Array.from(headers, () =&gt; []);\nfor (const tr of document.querySelectorAll('#tab tr:nth-child(n + 2)')) {\n [...tr.children].forEach((th, i) =&gt; {\n data[i].push(th.textContent.trim());\n });\n}\nconsole.log(headers);\nconsole.log(data);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;table id=\"tab\"&gt;\n &lt;tr&gt;\n &lt;th&gt;\n Name\n &lt;/th&gt;\n &lt;th&gt;\n Age\n &lt;/th&gt;\n &lt;th&gt;\n Location\n &lt;/th&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;th&gt;\n Jason\n &lt;/th&gt;\n &lt;th&gt;\n 22\n &lt;/th&gt;\n &lt;th&gt;\n Texas\n &lt;/th&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;th&gt;\n Lawson\n &lt;/th&gt;\n &lt;th&gt;\n 21\n &lt;/th&gt;\n &lt;th&gt;\n Florida\n &lt;/th&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;th&gt;\n Jose\n &lt;/th&gt;\n &lt;th&gt;\n 25\n &lt;/th&gt;\n &lt;th&gt;\n London\n &lt;/th&gt;\n &lt;/tr&gt;\n\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>That's already quite simple, IMO. I think adding jQuery to the mix would make things unnecessarily more complicated, not less.</p>\n\n<p>I refactored it out, but I don't think it's good idea to use <code>reduce</code> when the accumulator is going to be the same object every time. See: <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">Is <code>reduce</code> bad?</a> by Google devs. If it's always going to be the same object, it'll be a bit easier to read if that object is declared as a standalone variable in the outer scope.</p>\n\n<p>The HTML is a bit weird. A <code>&lt;th&gt;</code> is a <em>table header</em>. It makes sense for the headers to be <code>&lt;th&gt;</code>s, but the table <em>data</em> should probably be <code>&lt;td&gt;</code>s instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:26:29.853", "Id": "476203", "Score": "0", "body": "Hey there @CertainPerformance. This answer is cool . Let me understand and learn from it. Actually i was lazy to write the <tr> again and again.i copied it and changed the values.forgot to make it td." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T22:01:23.057", "Id": "476207", "Score": "0", "body": "Hey i forgot @CertainPerformance.it should output column data actually.not row data.Please run my snippet to understand" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:19:32.670", "Id": "242666", "ParentId": "242660", "Score": "2" } } ]
{ "AcceptedAnswerId": "242666", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:02:59.340", "Id": "242660", "Score": "2", "Tags": [ "javascript", "jquery", "html" ], "Title": "Javascript - Extract data from html table" }
242660
<p>I have tried Implementing Stacks Using Linked Lists, and would like some tips and tricks regarding optimizations or ways to simplify/compact processes.</p> <p>It has 3 functions, Push, Pop, and Peek (For checking the top item in stacks)</p> <pre class="lang-py prettyprint-override"><code>class Node: def __init__(self, data, next=None): self.data = data self.next = next class Stack: def __init__(self): self.bottom = None self.top = None self.length = 0 def peek(self): return self.top.data if self.top != None else None def push(self, data): NewNode = Node(data) if self.length == 0: self.bottom = self.top = NewNode else: top = self.top self.top = NewNode self.top.next = top self.length += 1 return self def pop(self): length = self.length top = self.top if length == 0: raise IndexError('No items in stack') elif self.bottom == top: self.bottom = None else: NextTop = self.top.next self.top = NextTop self.length -= 1 return top.data </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>stack = Stack() stack.push(0) stack.push(1) stack.push(2) stack.push(3) print(stack.peek()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) stack.push(5) stack.push(2) print(stack.pop()) print(stack.pop()) ----------------------- 3 3 2 1 0 2 5 ----------------------- </code></pre>
[]
[ { "body": "<p>First, I believe that the <code>Node</code> class is an implementation detail. You could move it inside the <code>Stack</code> or your could rename it <code>_Node</code> to indicate that it is private.</p>\n\n<p>Next, I will refer you to this answer to a different CR question, also written by me: <a href=\"https://codereview.stackexchange.com/a/185052/106818\">https://codereview.stackexchange.com/a/185052/106818</a></p>\n\n<p>Specifically, points 2-7:</p>\n\n<ol start=\"2\">\n<li><p>... consider how the <a href=\"https://docs.python.org/3/library/stdtypes.html#lists\" rel=\"nofollow noreferrer\">Python <code>list</code> class</a> (and <code>set</code>, and <code>dict</code>, and <code>tuple</code>, and ...) is initialized. And how the <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\">Mutable Sequence Types</a> are expected to work.</p>\n\n<p>Because <em>your code</em> is implementing a \"mutable sequence type.\" So there's no reason that your code shouldn't work the same way. In fact, if you want other people to use your code, you should try to produce as few surprises as possible. Conforming to an existing interface is a good way to do that!</p></li>\n<li><p>Create an initializer that takes a sequence.</p>\n\n<pre><code>class Stack:\n def __init__(self, seq=None):\n ...\n if seq is not None:\n self.extend(sequence)\n</code></pre></li>\n<li><p>Implement as many of the mutable sequence operations as possible.</p></li>\n<li><p>Use the standard method names where possible: <code>clear</code>, <code>extend</code>, <code>append</code>, <code>remove</code>, etc.</p></li>\n<li><p>Implement special <em>dundermethods</em> (method names with \"double-underscores\" in them: double-under-methods, or \"dundermethods\") as needed to make standard Python idioms work:</p>\n\n<pre><code>def __contains__(self, item):\n for i in self:\n ...\n\ndef __iter__(self):\n node = self.head\n\n while node:\n yield node.value\n node = node.next\n</code></pre></li>\n<li><p>Implement your test code using standard Python idioms, to prove it's working <em>and to show developers how your code should be used!</em></p></li>\n</ol>\n\n<p>Finally, some direct code criticisms:</p>\n\n<ol start=\"8\">\n<li><p>Don't use equality comparisons with <code>None</code>. Use <code>is None</code> or <code>is not None</code> instead. This is a <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP-8</a>-ism, and also actually faster.</p></li>\n<li><p>You don't really use <code>self.bottom</code> for anything. Go ahead and delete it.</p></li>\n<li><p>Don't use <code>CamelCase</code> variable names. That's another PEP-8 violation. Use <code>snake_case</code> for local variables.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T22:20:03.343", "Id": "242668", "ParentId": "242662", "Score": "1" } } ]
{ "AcceptedAnswerId": "242668", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:39:13.053", "Id": "242662", "Score": "1", "Tags": [ "python", "python-3.x", "object-oriented", "linked-list", "stack" ], "Title": "Stack Implementation Using Linked Lists" }
242662
<p>How can I improve the visual appeal Of My text-based Pokemon battling simulator?</p> <p>I created a Pokemon battling simulator in C++. I showed it to my mom, dad, and brother, and they didn't say anything about this, but I have a tugging feeling that they didn't think it looked to great. I myself don't think it looks to great. I'm not talking about the code (the code is a huge mess), I'm talking about the actual terminal application. And not only do I want to make it look better, I also want to help make it easier for the user to give his inputs.</p> <p>There are a bunch of files, but many of them aren't that important, so here is the github page: <a href="https://github.com/nishantc1527/Pokemon-Simulator" rel="nofollow noreferrer">https://github.com/nishantc1527/Pokemon-Simulator</a>. But if you only want the important files (it might look like a lot, but you only pretty much need to look at main.cpp and pokemon.hpp):</p> <p>If you want to quickly run this, I added a button so you can run it on repl.it. It's at the top of the gitub README page</p> <p>In a file called <code>main.cpp</code> (the main class)</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;Windows.h&gt; #include "helper_functions.hpp" #include "gameplay_functions.hpp" #include "helper_constants.hpp" int main() { read_file(); try { start(); } catch(std::exception e) { print("Quitting"); } } void start() { while (true) { switch (get_input("Do You Want To Create A Team Or Battle Using Existing Teams?", false, { "Create Team", "Battle" })) { case CREATE_TEAM: create_team(); break; case BATTLE: battle(); break; } } } void create_team() { std::vector&lt;std::string&gt; u_team; while (u_team.size() &lt; 6) { switch (get_input("Do You Want To Create A New Pokemon Or Add An Existing Pokemon To Your Team?", false, { "Create Pokemon", "Add Pokemon" })) { case CREATE_POKEMON: create_pokemon(); break; case ADD_POKEMON: add_pokemon(u_team); break; } } print("What Do You Want To Name Your Team?"); std::string team_name; std::getline(std::cin, team_name); add_team_to_file(team_name, u_team); u_teams[team_name] = u_team; } void battle() { std::vector&lt;std::pair&lt;std::string, std::vector&lt;std::string&gt;&gt;&gt; key_value = key_value_pairs(u_teams); std::vector&lt;std::string&gt; keys; for (auto&amp; pair : key_value) { keys.push_back(pair.first); } int in = get_input("Player 1: Which Team Do You Want To Use?", false, keys); if (in == -1) { print("You Have No Teams To Battle With."); return; } std::string&amp; p1_team_name = keys[in - 1]; in = get_input("Player 2: Which Team Do You Want To Use?", false, keys); std::string&amp; p2_team_name = keys[in - 1]; std::vector&lt;pokemon&gt; p1_team; std::vector&lt;std::string&gt;&amp; p1_team_pokemon = u_teams[p1_team_name]; for (int i = 0; i &lt; 6; i++) { p1_team.push_back(pokemon(u_pokemon[p1_team_pokemon[i]][0], p1_team_pokemon[i], u_pokemon[p1_team_pokemon[i]][1], u_pokemon[p1_team_pokemon[i]][2], u_pokemon[p1_team_pokemon[i]][3], u_pokemon[p1_team_pokemon[i]][4])); } std::vector&lt;pokemon&gt; p2_team; std::vector&lt;std::string&gt; p2_team_pokemon = u_teams[p2_team_name]; for (int i = 0; i &lt; 6; i++) { p2_team.push_back(pokemon(u_pokemon[p2_team_pokemon[i]][0], p2_team_pokemon[i], u_pokemon[p2_team_pokemon[i]][1], u_pokemon[p2_team_pokemon[i]][2], u_pokemon[p2_team_pokemon[i]][3], u_pokemon[p2_team_pokemon[i]][4])); } in = get_input("Player 1: Choose Your Lead", false, to_string_array(p1_team)); pokemon&amp; p1_lead = p1_team[in - 1]; in = get_input("Player 2: Choose Your Lead", false, to_string_array(p2_team)); pokemon&amp; p2_lead = p2_team[in - 1]; battle(p1_team, p2_team, p1_lead, p2_lead); } void create_pokemon() { std::string input_pokemon; std::vector&lt;std::string&gt; values; std::vector&lt;std::pair&lt;int, std::string&gt;&gt; key_value = key_value_pairs(available_pokemon); for (auto&amp; pair : key_value) { values.push_back(pair.second); } int in = get_input("Which Pokemon Do You Want To Add?", true, values); add_user_pokemon(available_pokemon[in]); } void add_pokemon(std::vector&lt;std::string&gt;&amp; u_team) { std::vector&lt;std::pair&lt;std::string, std::vector&lt;std::string&gt;&gt;&gt; key_value = key_value_pairs(u_pokemon); std::vector&lt;std::string&gt; keys; for (auto&amp; pair : key_value) { keys.push_back(pair.first); } if (keys.size() == 0) { print("You Have No Pokemon"); return; } int in = get_input("Which Pokemon Do You Want To Add?", true, keys); u_team.push_back(keys[in - 1]); } void battle(std::vector&lt;pokemon&gt;&amp; p1_team, std::vector&lt;pokemon&gt;&amp; p2_team, pokemon&amp; p1_lead, pokemon&amp; p2_lead) { pokemon&amp; curr_p1 = p1_lead; pokemon&amp; curr_p2 = p2_lead; while (true) { std::ifstream file1(curr_p1.name + ".txt"); std::ifstream file2(curr_p2.name + ".txt"); std::string next_line; while(std::getline(file1, next_line)) { print(" " + next_line); } print("\n\n\n\n\n\n\n\n\n"); while(std::getline(file2, next_line)) { print(next_line); } switch (get_input("Player 1: Do You Want To Attack Or Swtich?", false, { "Attack", "Switch" } )) { case ATTACK: switch (get_input("Player 2: Do You Want To Attack Or Swtich?", false, { "Attack", "Switch" } )) { case ATTACK: { std::string p1_move = choose_move(curr_p1, 1); std::string p2_move = choose_move(curr_p2, 2); if (curr_p1.s_speed &gt; curr_p2.s_speed) { if (curr_p1.attack(p1_move, curr_p2, 2)) { remove(p2_team, curr_p2); int in = get_input(curr_p2.name + " Has Fainted. Player 2: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p2_team)); if (in == -1) { print("Player 1 Has Won!"); return; } curr_p2 = p2_team[in - 1]; } else { if (curr_p2.attack(p2_move, curr_p1, 1)) { remove(p1_team, curr_p1); int in = get_input(curr_p1.name + " Has Fainted. Player 1: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p1_team)); if (in == -1) { print("Player 2 Has Won!"); return; } curr_p1 = p1_team[in - 1]; } } } else { if (curr_p2.attack(p2_move, curr_p1, 1)) { remove(p1_team, curr_p1); int in = get_input(curr_p1.name + " Has Fainted. Player 1: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p1_team)); if (in == -1) { print("Player 2 Has Won!"); return; } curr_p1 = p1_team[in - 1]; } else { if (curr_p1.attack(p1_move, curr_p2, 2)) { remove(p2_team, curr_p2); int in = get_input(curr_p2.nick + " Has Fainted. Player 2: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p2_team)); if (in == -1) { print("Player 1 Has Won!"); return; } curr_p2 = p2_team[in - 1]; } } } } break; case SWITCH: std::vector&lt;pokemon&gt; removed = temp_remove(p2_team, curr_p2); int in = get_input("Player 2: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(removed)); curr_p2 = p2_team[in - 1]; std::string p1_move = choose_move(curr_p1, 1); if (curr_p1.attack(p1_move, curr_p2, 2)) { remove(p2_team, curr_p2); int in = get_input(curr_p2.nick + " Has Fainted. Player 2: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p2_team)); if (in == -1) { print("Player 1 Has Won!"); return; } curr_p2 = p1_team[in - 1]; } } break; case SWITCH: switch (get_input("Player 2: Do You Want To Attack Or Swtich?", false, { "Attack", "Switch" } )) { case ATTACK: { std::vector&lt;pokemon&gt; removed = temp_remove(p1_team, curr_p1); int in = get_input("Player 1: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(removed)); curr_p1 = p1_team[in - 1]; std::string p2_move = choose_move(curr_p2, 2); if (curr_p2.attack(p2_move, curr_p1, 1)) { remove(p1_team, curr_p1); int in = get_input(curr_p1.name + " Has Fainted. Player 1: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(p1_team)); if (in == -1) { print("Player 2 Has Won!"); return; } curr_p1 = p1_team[in - 1]; } } break; case SWITCH: std::vector&lt;pokemon&gt; removed = temp_remove(p1_team, curr_p1); int in = get_input("Player 1: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(removed)); curr_p1 = p1_team[in - 1]; removed = temp_remove(p2_team, curr_p2); in = get_input("Player 2: Which Pokemon Do You Want To Switch Out To?", false, to_string_array(removed)); curr_p2 = p2_team[in - 1]; } break; } } } ////////////////Helper Functions/////////////////// int get_input(const std::string&amp; prompt, bool fast, const std::vector&lt;std::string&gt;&amp; options) { if (options.size() == 0) { return -1; } print(prompt + " If you want to exit, type -2."); for (int i = 0, option_count = 1; i &lt; options.size(); i++, option_count++) { print(std::to_string(option_count) + ": " + options[i], fast ? 10 : 50); } while (true) { std::string input; std::getline(std::cin, input); if (!is_valid(input, options.size())) { print("INVALID"); } else { int num = std::stoi(input); if(num == -2) { throw std::exception(); } else { return std::stoi(input); } } } } void print(const std::string&amp; text, int delay) { for (int i = 0; i &lt; text.length(); i++) { std::cout &lt;&lt; text[i]; } std::cout &lt;&lt; std::endl; } void read_file() { std::ifstream data("pokemon_data.txt"); std::string next_line; std::string prev; int count = 1; while (std::getline(data, next_line)) { if (next_line[0] == '#') { std::string p_name = split(next_line, 1); pokemon_data[p_name] = next_line;; available_pokemon[count++] = p_name; prev = p_name; continue; } pokemon_moves[prev].push_back(next_line); } data.close(); std::ifstream u_pokemon_file("user_pokemon.txt"); while (std::getline(u_pokemon_file, next_line)) { std::vector&lt;std::string&gt; u_pokemon_data; prev = next_line; for (int i = 0; i &lt; 13; i++) { std::getline(u_pokemon_file, next_line); u_pokemon_data.push_back(next_line); } u_pokemon[prev] = u_pokemon_data; } u_pokemon_file.close(); std::ifstream u_teams_file("user_teams.txt"); while (std::getline(u_teams_file, next_line)) { std::vector&lt;std::string&gt; team_data; prev = next_line; for (int i = 0; i &lt; 6; i++) { std::getline(u_teams_file, next_line); team_data.push_back(next_line); } u_teams[prev] = team_data; } std::ifstream move_file("move_data.txt"); while (std::getline(move_file, next_line)) { std::vector&lt;std::string&gt; curr_move_data; prev = next_line; for (int i = 0; i &lt; 5; i++) { std::getline(move_file, next_line); curr_move_data.push_back(next_line); } move_data[prev] = curr_move_data; } } template &lt;typename T&gt; void print_vector(std::vector&lt;T&gt;&amp; vector) { for (T t : vector) { std::cout &lt;&lt; t; } } std::vector&lt;std::string&gt; split(std::string&amp; string) { std::vector&lt;std::string&gt; ans; std::stringstream stream(string); std::string next_line; while (std::getline(stream, next_line, ' ')) { ans.push_back(next_line); } return ans; } std::string split(std::string&amp; string, int index) { return split(string)[index]; } template&lt;typename K, typename V&gt; std::vector&lt;std::pair&lt;K, V&gt;&gt; key_value_pairs(std::unordered_map&lt;K, V&gt;&amp; map) { std::vector&lt;std::pair&lt;K, V&gt;&gt; ans; for (auto&amp; x : map) { ans.push_back(std::make_pair(x.first, x.second)); } return ans; } void add_user_pokemon(std::string&amp; p_name) { std::vector&lt;std::string&gt; u_moves = get_user_moves(p_name); print("What Do You Want To Name Your Pokemon? Name Must Be Unique"); std::string name; std::getline(std::cin, name); std::ofstream file("user_pokemon.txt", std::ios_base::app); std::vector&lt;std::string&gt; data = split(pokemon_data[p_name]); file &lt;&lt; name &lt;&lt; "\n" &lt;&lt; p_name &lt;&lt; "\n" &lt;&lt; u_moves[0] &lt;&lt; "\n" &lt;&lt; u_moves[1] &lt;&lt; "\n" &lt;&lt; u_moves[2] &lt;&lt; "\n" &lt;&lt; u_moves[3] &lt;&lt; "\n" &lt;&lt; data[2] &lt;&lt; "\n" &lt;&lt; data[3] &lt;&lt; "\n" &lt;&lt; data[4] &lt;&lt; "\n" &lt;&lt; data[5] &lt;&lt; "\n" &lt;&lt; data[6] &lt;&lt; "\n" &lt;&lt; data[7] &lt;&lt; "\n" &lt;&lt; data[8] &lt;&lt; "\n" &lt;&lt; data[9] &lt;&lt; "\n"; file.close(); u_pokemon[name] = { p_name, u_moves[0], u_moves[1], u_moves[2], u_moves[3], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9] }; } std::vector&lt;std::string&gt; get_user_moves(std::string&amp; p_name) { std::vector&lt;std::string&gt; available_moves = pokemon_moves[p_name]; std::vector&lt;std::string&gt; u_moves; int move_count = 5; while (move_count-- &gt; 1) { int in = get_input("Choose " + std::to_string(move_count) + " Moves", true, available_moves); u_moves.push_back(available_moves[in - 1]); available_moves.erase(available_moves.begin() + in - 1); } return u_moves; } void add_team_to_file(std::string&amp; team_name, std::vector&lt;std::string&gt;&amp; p_names) { std::ofstream team_file("user_teams.txt", std::ios_base::app); team_file &lt;&lt; team_name &lt;&lt; "\n" &lt;&lt; p_names[0] &lt;&lt; "\n" &lt;&lt; p_names[1] &lt;&lt; "\n" &lt;&lt; p_names[2] &lt;&lt; "\n" &lt;&lt; p_names[3] &lt;&lt; "\n" &lt;&lt; p_names[4] &lt;&lt; "\n" &lt;&lt; p_names[5] &lt;&lt; "\n"; team_file.close(); } template&lt;typename T&gt; void remove(std::vector&lt;T&gt;&amp; vec, T&amp; element) { for (int i = 0; i &lt; vec.size(); i++) { if (vec[i] == element) { vec.erase(vec.begin() + i); return; } } } std::vector&lt;std::string&gt; to_string_array(const std::vector&lt;pokemon&gt;&amp; vec) { std::vector&lt;std::string&gt; ans; for (int i = 0; i &lt; vec.size(); i++) { ans.push_back(vec[i].nick); } return ans; } std::string choose_move(pokemon&amp; p, int player_num) { std::string move; switch (get_input("Player " + std::to_string(player_num) + ": Which Move Do You Want To Use?", false, { p.move1, p.move2, p.move3, p.move4 } )) { case MOVE_1: move = p.move1; break; case MOVE_2: move = p.move2; break; case MOVE_3: move = p.move3; break; case MOVE_4: move = p.move4; break; } return move; } template&lt;typename T&gt; std::vector&lt;T&gt; temp_remove(std::vector&lt;T&gt; vec, T&amp; to_remove) { remove(vec, to_remove); return vec; } bool is_valid(const std::string&amp; to_check, int max_num) { try { int num = std::stoi(to_check); return num == -2 || (num &gt;= 1 &amp;&amp; num &lt;= max_num); } catch (std::exception&amp; e) { return false; } } </code></pre> <p>In a file called <code>pokemon.hpp</code>:</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;unordered_map&gt; #include "helper_maps.hpp" #include "helper_functions.hpp" namespace p_util { void print(std::string text) { for (int i = 0; i &lt; text.length(); i++) { std::cout &lt;&lt; text[i]; } std::cout &lt;&lt; std::endl; } std::vector&lt;std::string&gt; split(std::string string) { std::vector&lt;std::string&gt; ans; std::stringstream stream(string); std::string next_line; while (std::getline(stream, next_line, ' ')) { ans.push_back(next_line); } return ans; } } class pokemon { private: int b_hp, b_attack, b_defense, b_special_attack, b_special_defense, b_speed; float type_effectivenss[18][18]{ {1, 1, 1, 1, 1, 0.5, 1, 0, 0.5, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {2, 1, 0.5, 0.5, 1, 2, 0.5, 0, 2, 1, 1, 1, 1, 0.5, 2, 1, 2, 0.5}, {1, 2, 1, 1, 1, 0.5, 2, 1, 0.5, 1, 1, 2, 0.5, 1, 1, 1, 1, 1}, {1, 1, 1, 0.5, 0.5, 0.5, 1, 0.5, 0, 1, 1, 2, 1, 1, 1, 1, 1, 2}, {1, 1, 0, 2, 1, 2, 0.5, 1, 2, 2, 1, 0.5, 2, 1, 1, 1, 1, 1}, {1, 0.5, 2, 1, 0.5, 1, 2, 1, 0.5, 2, 1, 1, 1, 1, 2, 1, 1, 1}, {1, 0.5, 0.5, 0.5, 1, 1, 1, 0.5, 0.5, 0.5, 1, 2, 1, 2, 1, 1, 2, 0.5}, {0, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0.5, 1}, {1, 1, 1, 1, 1, 2, 1, 1, 0.5, 0.5, 0.5, 1, 0.5, 1, 2, 1, 1, 2}, {1, 1, 1, 1, 1, 0.5, 2, 1, 2, 0.5, 0.5, 2, 1, 1, 2, 0.5, 1, 1}, {1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 0.5, 0.5, 1, 1, 1, 0.5, 1, 1}, {1, 1, 0.5, 0.5, 2, 2, 0.5, 1, 0.5, 0.5, 2, 0.5, 1, 1, 1, 0.5, 1, 1}, {1, 1, 2, 1, 0, 1, 1, 1, 1, 1, 2, 0.5, 0.5, 1, 1, 0.5, 1, 1}, {1, 2, 1, 2, 1, 1, 1, 1, 0.5, 1, 1, 1, 1, 0.5, 1, 1, 0, 1}, {1, 1, 2, 1, 2, 1, 1, 1, 0.5, 0.5, 0.5, 2, 1, 1, 0.5, 2, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 0.5, 1, 1, 1, 1, 1, 1, 2, 1, 0}, {1, 0.5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0.5, 0.5}, {1, 2, 1, 0.5, 1, 1, 1, 1, 0.5, 0.5, 1, 1, 1, 1, 1, 2, 2, 1} }; std::unordered_map&lt;std::string, int&gt; type_indices{ {"normal", 0}, {"fighting", 1}, {"flying", 2}, {"poison", 3}, {"ground", 4}, {"rock", 5}, {"bug", 6}, {"ghost", 7}, {"steel", 8}, {"fire", 9}, {"water", 10}, {"grass", 11}, {"electric", 12}, {"psychic", 13}, {"ice", 14}, {"dragon", 15}, {"dark", 16}, {"fairy", 17} }; public: int s_attack, s_defense, s_special_attack, s_special_defense, s_speed; float max_hp, s_hp; std::string name, type1, type2, move1, move2, move3, move4, nick; public: pokemon(std::string&amp; _name, std::string&amp; _nick, std::string&amp; _move1, std::string&amp; _move2, std::string&amp; _move3, std::string&amp; _move4) { name = _name; nick = _nick; std::vector&lt;std::string&gt; data = p_util::split(pokemon_data[_name]); type1 = data[2]; type2 = data[3]; b_hp = std::stoi(data[4]); b_attack = std::stoi(data[5]); b_defense = std::stoi(data[6]); b_special_attack = std::stoi(data[7]); b_special_defense = std::stoi(data[8]); b_speed = std::stoi(data[9]); s_hp = (2 * b_hp) + 110; max_hp = s_hp; s_attack = b_attack * 2 + 5; s_defense = b_defense * 2 + 5; s_special_attack = b_special_attack * 2 + 5; s_special_defense = b_special_defense * 2 + 5; s_speed = b_speed * 2 + 5; move1 = _move1; move2 = _move2; move3 = _move3; move4 = _move4; } public: bool take_damage(float damage) { s_hp -= damage; return s_hp &lt;= 0; } bool attack(std::string&amp; move, pokemon&amp; other, int player_num) { std::vector&lt;std::string&gt; data = move_data[move]; float f_rand = ((rand() % 15) + 85.0) / 100.0; float STAB = (data[1] == type1 || data[1] == type2) ? 1.5 : 1; float type = type_effectivenss[type_indices[move]][type_indices[other.type1]] * type_effectivenss[type_indices[move]][type_indices[other.type2]]; const float MODIFIER = f_rand * STAB * type; const float POWER = std::stoi(data[2]); const float ATTACK = data[1] == "p" ? s_attack : s_special_attack; const float DEFENSE = data[1] == "p" ? other.s_defense : other.s_special_defense; const float DAMAGE = ((52 * POWER * (ATTACK / DEFENSE) / 50) + 2) * MODIFIER; bool fainted = other.take_damage(DAMAGE); p_util::print("Player " + std::to_string(player_num) + "'s " + other.nick + " Has " + std::to_string((other.s_hp / other.max_hp) * 100) + "% Of It's HP Left"); return fainted; } bool operator==(const pokemon&amp; other) const { return (name == other.name) &amp;&amp; (move1 == other.move1) &amp;&amp; (move2 == other.move2) &amp;&amp; (move3 == other.move3) &amp;&amp; (move4 == other.move4); } }; </code></pre> <p>In a file called <code>helper_functions.hpp</code>:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include "pokemon.hpp" int get_input(const std::string&amp; prompt, bool fast, const std::vector&lt;std::string&gt;&amp; options); void print(const std::string&amp; text, int delay = 50); void read_file(); std::vector&lt;std::string&gt; split(std::string&amp; string); std::string split(std::string&amp; string, int index); template &lt;typename K, typename V&gt; std::vector&lt;std::pair&lt;K, V&gt;&gt; key_value_pairs(std::unordered_map&lt;K, V&gt;&amp; map); template &lt;typename T&gt; void print_vector(std::vector&lt;T&gt;&amp; vector); void add_user_pokemon(std::string&amp; p_name); std::vector&lt;std::string&gt; get_user_moves(std::string&amp; p_name); void add_team_to_file(std::string&amp; team_name, std::vector&lt;std::string&gt;&amp; p_names); template &lt;typename T&gt; void remove(std::vector&lt;T&gt;&amp; vec, T&amp; element); std::vector&lt;std::string&gt; to_string_array(const std::vector&lt;pokemon&gt;&amp; vec); std::string choose_move(pokemon&amp; p, int player_num); template &lt;typename T&gt; std::vector&lt;T&gt; temp_remove(std::vector&lt;T&gt; vec, T&amp; to_remove); bool is_valid(const std::string&amp; to_check, int max_num); </code></pre> <p>And finally, in a file called <code>gameplay_functions.hpp</code>:</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; #include "pokemon.hpp" void start(); void create_team(); void battle(); void create_pokemon(); void add_pokemon(std::vector&lt;std::string&gt;&amp; u_team); void battle(std::vector&lt;pokemon&gt;&amp; p1_team, std::vector&lt;pokemon&gt;&amp; p2_team, pokemon&amp; p1_lead, pokemon&amp; p2_lead); <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-24T20:50:22.220", "Id": "479910", "Score": "1", "body": "You are asking us to review the visual appeal of your game, is there any chance you could add some example output?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T20:45:43.947", "Id": "242663", "Score": "2", "Tags": [ "c++", "game" ], "Title": "Text-Based Pokemon Battling Simulator" }
242663
<p>I have been trying to develop a program which implements a parser, i.e., syntactic analysis.</p> <p>Here is what I have done so far:</p> <p><strong>parser.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include "parser.h" void error_handle(char *expected, YYSTYPE *token) { if (token) { fprintf(yyout, "Error: Expected token is { %s }, but actual token is [ %s ] at line %d\n", expected, token-&gt;lexeme, token-&gt;line); recovery = 1; } } void print_token(char *str, YYSTYPE *token) { if (token) fprintf(yyout, str, token-&gt;lexeme, token-&gt;line); } int parser() { parser_errors = 0; recovery = 0; token = tokens; if (!token) return 0; fprintf(yyout, "Starting Program...\n"); if (!match(PROGRAM)) { error_handle("program", token); recovery = 0; } else print_token("[ %s ] at line %d\n", token); next_token(); var_definitions(); statements(); if (!match(END)) { error_handle("end", token); recovery = 0; } else print_token("[ %s ] at line %d\n", token); next_token(); func_definitions(); return parser_errors; } void var_definitions() { if (!type()) if (not_var_definitions()) return; fprintf(yyout, "Variable Definitions...\n"); while (token) { if (!type()) { if (not_var_definitions()) { recovery = 0; break; } } var_definition(); if (match(')')) break; if (!match(SEMICOLON)) error_handle(";", token); next_token(); } } void var_definition() { if (type()) print_token("Variable Type [ %s ] at line %d\n", token); else if (!type()) error_handle("integer, real", token); next_token(); variables_list(); } void variables_list() { int error; do { error = not_var_definitions(); variable(); if (error == 2) { error_handle(",", token); while (!match(COMMA) &amp;&amp; !match(SEMICOLON)) next_token(); recovery = 0; } } while (match(COMMA) &amp;&amp; next_token()); } void variable() { token-&gt;lexeme[token-&gt;count] = '\0'; if (!match(ID)) { if (recovery) { while (!match(ID) &amp;&amp; !match(COMMA) &amp;&amp; !match(SEMICOLON)) next_token(); recovery = 0; if (!match(ID)) return; } else error_handle("Variable Name(id)", token); } next_token(); if (match('[')) { if (!recovery) { back_token(); if (token) fprintf(yyout, "Array Variable %s\n", token-&gt;lexeme); next_token(); } next_token(); if (!match(INT_NUMBER)) { error_handle("int number", token); } else print_token("Array Size [%s] at line %d\n", token); next_token(); if (!match(']') &amp;&amp; token) { if (recovery) { while (!match(']')) next_token(); recovery = 0; } else error_handle("]", token); } next_token(); } else { if (!recovery) { back_token(); print_token("Variable [ %s ] at line %d\n", token); next_token(); } } } void statements() { if (not_statements()) return; fprintf(yyout, "Statement List...\n"); while (!not_statements()) { statement(); if (!match(SEMICOLON)) { if (recovery) { while (!match(SEMICOLON) &amp;&amp; !match('{') &amp;&amp; !match(END)) if (!next_token()) break; recovery = 0; } else error_handle(";", token); } if (match(END)) break; if (match('{')) continue; next_token(); if (match(SEMICOLON)) next_token(); } } void statement() { fprintf(yyout, "Statement...\n"); if (match(ID)) { next_token(); if (match('(')) { back_token(); function_call(); } else { back_token(); fprintf(yyout, "Variable Assignment...\n"); variable(); if (!match('=')) { if (!match(SEMICOLON)) error_handle("=", token); if (recovery) { while (!match('=') &amp;&amp; !match(SEMICOLON) &amp;&amp; !match('{') &amp;&amp; !match(END)) next_token(); recovery = 0; if (match(SEMICOLON) || match('{') || match(END)) return; print_token("Assign Operator [ %s ] at line %d\n", token); } } else print_token("Assign Operator [ %s ] at line %d\n", token); next_token(); if (!expression()) { if (match(END) || match('{')) return; error_handle("int number, real number, id", token); next_token(); } } } else if (match(RETURN)) { fprintf(yyout, "Return Statement...\n"); next_token(); if (match(SEMICOLON)) fprintf(yyout, "Empty Statement\n"); else { if (!expression()) error_handle("ID, int number, real number", token); expression(); } } else if (match('{')) block(); } void function_call() { fprintf(yyout, "Function Call...\n"); print_token("Function Name [ %s ] at line %d\n", token); next_token(); next_token(); parameters_list(); if (!match(')')) { error_handle(", or )", token); next_token(); while (!match(')') &amp;&amp; !match(SEMICOLON)) next_token(); back_token(); } next_token(); } void parameters_list() { fprintf(yyout, "Parameters List...\n"); if (match(')')) { fprintf(yyout, "Empty Parameter\n"); } else variables_list(); } int expression() { fprintf(yyout, "Expression...\n"); if (recovery) { while (!match(INT_NUMBER) &amp;&amp; !match(REAL_NUMBER) &amp;&amp; !match(ID) &amp;&amp; !match('{')) next_token(); recovery = 0; if (match('{')) return 0; } if (match(INT_NUMBER)) { print_token("int number [ %s ] at line %d\n", token); next_token(); } else if (match(REAL_NUMBER)) { print_token("real number [ %s ] at line %d\n", token); next_token(); } else if (match(ID)) { next_token(); if (ar_op()) { back_token(); print_token("ID [ %s ] at line %d\n", token); next_token(); print_token("Arithmetic Operator [ %s ] at line %d\n", token); next_token(); if (!expression()) { error_handle("int number, real number, id", token); next_token(); } } else { back_token(); variable(); } } else return 0; return 1; } void block() { fprintf(yyout, "Block Statement...\n"); if (!match('{')) { if (match(END)) return; error_handle("{", token); } next_token(); var_definitions(); back_token(); if (!match(SEMICOLON) &amp;&amp; !match('{')) { if (match(END)) return; error_handle(";", token); } next_token(); statements(); if (!match('}')) { if (match(END)) return; error_handle("}", token); } next_token(); } void func_definitions() { fprintf(yyout, "Function Definitions List...\n"); while (token) func_definition(); } void func_definition() { if (!returned_type()) { error_handle("integer, real, void", token); while (!returned_type() &amp;&amp; !match(ID)) next_token(); } recovery = 0; fprintf(yyout, "Function Definition...\n"); if (returned_type()) print_token("Return Type [ %s ] at line %d\n", token); else error_handle("integer, real, void", token); next_token(); if (!match(ID)) error_handle("id", token); else print_token("Function Name [ %s ] at line %d\n", token); next_token(); if (!match('(')) error_handle("(", token); next_token(); param_definitions(); if (!match(')')) error_handle(")", token); next_token(); block(); if (recovery) { while (!match('}')) next_token(); next_token(); recovery = 0; } } void param_definitions() { fprintf(yyout, "Parameter definitions List...\n"); if (match(')')) fprintf(yyout, "Empty Parameter\n"); else var_definitions(); } </code></pre> <p><strong>parser.h</strong></p> <pre><code>#pragma once #include "LEXYY.h" int recovery, parser_errors; FILE *yyout; void error_handle(char *, YYSTYPE *); void print_token(char *, YYSTYPE *); int parser(); void var_definitions(); void var_definition(); void variables_list(); </code></pre> <p><strong>LEXYY.h</strong></p> <pre><code>#pragma once #include &lt;stdio.h&gt; typedef struct YYTYPE { int kind; char *lexeme; int line; int count; struct YYTYPE *next; struct YYTYPE *prev; } YYSTYPE; YYSTYPE *token; YYSTYPE *tokens; int line_number; int lexer_errors; void initLexer(); void create_and_store_token(int, char *, int); #define PROGRAM 256 #define END 257 #define INTEGER 258 #define REAL 259 #define INT_NUMBER 260 #define REAL_NUMBER 261 #define ID 262 #define VOID 263 #define RETURN 264 #define COMMA 265 #define SEMICOLON 266 YYSTYPE *next_token(); YYSTYPE *back_token(); int match(int); int type(); int ar_op(); int returned_type(); int not_var_definitions(); int not_statements(); void variable(); void statements(); void statement(); void function_call(); void parameters_list(); int expression(); void block(); void func_definitions(); void func_definition(); void param_definitions(); </code></pre> <p><strong>LEXYY.c</strong></p> <pre><code>%option nounistd %option noyywrap %{ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;io.h&gt; #include "LEXYY.h" #define isatty _isatty #define fileno _fileno void initLexer(); void create_and_store_token(int, char *, int); void errorPrint(char); void illegalError(const char *, const char *); %} WHITESPACE ([ \t]+) NEWLINE (\r|\n|\r\n) COMMENT ("--"[^\r\n]*) ID ([A-Za-z]([_]?[A-Za-z0-9]+)*) ILLEGALID ([_][A-Za-z0-9_]*|[A-Za-z][A-Za-z0-9_]*[_]|[0-9][A-Za-z0-9]*|[A-Za-z]([_]*[A-Za-z0-9]*)*) INTEGER (0|[0-9]+) REAL (0\.[0-9]+|[0-9]+\.[0-9]+) WRONGNUMBER ([0][0-9]+|[0][0-9]+[.][0-9]*|[.][0-9]+|[0-9]+[.]) OPERATOR ([*/=]) SEPARATION ([[\]{}\(\)]) %% {NEWLINE} { line_number++; } {WHITESPACE}+ {} {COMMENT} {} "program" { return PROGRAM; } "end" { return END; } "real" { return REAL; } "integer" { return INTEGER; } "void" { return VOID; } "return" { return RETURN; } {INTEGER} { return INT_NUMBER; } {REAL} { return REAL_NUMBER; } {WRONGNUMBER} { illegalError(yytext, "Number"); } "," { return COMMA; } ";" { return SEMICOLON; } {ID} { return ID; } {ILLEGALID} { illegalError(yytext, "ID"); } {OPERATOR} { return yytext[0]; } {SEPARATION} { return yytext[0]; } . { errorPrint(yytext[0]); } %% void initLexer() { line_number = 1; lexer_errors = 0; tokens = NULL; token = NULL; } void create_and_store_token(int kind, char *lexeme, int line) { if (token == NULL) { tokens = (YYSTYPE *)malloc(sizeof(YYSTYPE)); token = tokens; token-&gt;next = NULL; token-&gt;prev = NULL; } else { token-&gt;next = (YYSTYPE *)malloc(sizeof(YYSTYPE)); token-&gt;next-&gt;next = NULL; token-&gt;next-&gt;prev = token; token = token-&gt;next; } token-&gt;kind = kind; token-&gt;line = line; token-&gt;lexeme = (char *)malloc(sizeof(lexeme) + 1); #ifdef _WIN32 strcpy_s(token-&gt;lexeme, strlen(lexeme) + 1, lexeme); #else strcpy(token-&gt;lexeme, lexeme); #endif } YYSTYPE *next_token() { if (token) return (token = token-&gt;next); return NULL; } YYSTYPE *back_token() { if (token) return (token = token-&gt;prev); return NULL; } int match(int kind) { if (token &amp;&amp; token-&gt;kind == kind) return kind; return 0; } int type() { return (match(REAL) ? REAL : match(INTEGER)); } int ar_op() { if (match('*') || match('/')) return 1; return 0; } int returned_type() { return (match(VOID) ? VOID : type()); } int not_var_definitions() { int flag = 0; if (!token) flag = 1; else if (match(ID)) { next_token(); if (match('=') || match('(')) flag = 2; if (match('[')) { next_token(); next_token(); next_token(); if (match('=') || match('(')) flag = 2; back_token(); back_token(); back_token(); } back_token(); } else flag = 3; return flag; } int not_statements() { if (!token) return 1; if (!match(ID) &amp;&amp; !match(RETURN) &amp;&amp; !match('{')) return 1; return 0; } void errorPrint(char ch) { fprintf(yyout, "The character '%c' at line: %d does not begin any legal token in the language.\n", ch, line_number); } void illegalError(const char *text, const char *type) { fprintf(yyout, "Illegal %s '%s' was found at line %d\n", type, text, line_number); } </code></pre> <p><strong>However, I guess it's a rather cumbersome way to implement the parser. How would edit my code, for using the technique of "recursive descent"?</strong> I know that in order to get it being used you need to perform a left recursion on the grammar, and the left common element is called. However, I find it difficult to apply it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T23:39:58.060", "Id": "476216", "Score": "0", "body": "Why not writing a flex lexer and generate the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T01:16:49.037", "Id": "476225", "Score": "0", "body": "I did, but it's less relevant now..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T11:51:55.413", "Id": "476269", "Score": "0", "body": "@πάνταῥεῖ He did https://codereview.stackexchange.com/questions/242559/implementing-lexical-syntatic-and-semantic-analysis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T11:59:13.700", "Id": "476270", "Score": "0", "body": "I'm curious why is the lexer less relevant now? Since no one has answered your first question yet you could add your updates to the question and remove this one, since it is almost a duplicate, or copy the relevant code here. I'd stick with the old question because that has an up vote. I'm in the process of reviewing the other one, but it's difficult and I can't get it to build. I have not installed win_flex yet and the code doesn't compile for me, especially semantic.c. It might also be better if you added your test case to the question and expected output." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T23:21:48.697", "Id": "242675", "Score": "1", "Tags": [ "c", "parsing", "lexer" ], "Title": "implementing parser - improvment" }
242675
<h2><strong>Note</strong></h2> <p>As there are a lot of related modules in the project, I recently posted several similar posts(because all content cannot fit due to character limit) and someone indicated that this might be against the website policy, so I edited and included only the features of what my code does, I got some votes for closing the question, therefore, i'll include a few modules [<code>trainer.py</code>, <code>evaluator.py</code>] here and you can check the rest on github and review whatever parts you prefer.</p> <p>All modules:</p> <ul> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Main/detector.py" rel="nofollow noreferrer">detector.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Main/evaluator.py" rel="nofollow noreferrer">evaluator.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Main/models.py" rel="nofollow noreferrer">models.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Main/trainer.py" rel="nofollow noreferrer">trainer.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/anchors.py" rel="nofollow noreferrer">anchors.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/annotation_parsers.py" rel="nofollow noreferrer">annotation_parsers.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/augmentor.py" rel="nofollow noreferrer">augmentor.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/dataset_handlers.py" rel="nofollow noreferrer">dataset_handlers.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/utils.py" rel="nofollow noreferrer">utils.py</a></li> <li><a href="https://github.com/emadboctorx/yolov3-keras-tf2/blob/master/Helpers/visual_tools.py" rel="nofollow noreferrer">visual_tools.py</a></li> </ul> <h2><strong>Description</strong></h2> <p>yolov3-keras-tf2 is an implementation of <a href="https://pjreddie.com/darknet/yolo/" rel="nofollow noreferrer">yolov3</a> (you only look once) which is is a state-of-the-art, real-time object detection system that is extremely fast and accurate. There are many implementations that support tensorflow, only a few that support tensorflow v2 and as I did not find versions that suit my needs so, I decided to create this version which is very flexible and customizable.</p> <p><a href="https://i.stack.imgur.com/cGbsH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cGbsH.jpg" alt="Detections"></a></p> <h1><strong>Features</strong></h1> <ul> <li>tensorflow-2.X--keras-functional-api.</li> <li>cpu-gpu support.</li> <li>Random weights and DarkNet weights support.</li> <li>csv-xml annotation parsers.</li> <li>Anchor generator.</li> <li><code>matplotlib</code> visualization of all stages.</li> <li><code>tf.data</code> input pipeline.</li> <li><code>pandas</code> &amp; <code>numpy</code> data handling.</li> <li><code>imgaug</code> augmentation pipeline(customizable).</li> <li><code>logging</code> coverage.</li> <li>All-in-1 custom trainer.</li> <li>Stop and resume training support.</li> <li>Fully vectorized mAP evaluation.</li> <li>Photo &amp; video detection.</li> </ul> <h1><strong>Directory structure</strong></h1> <pre><code>yolov3-keras-tf2 ├── Config │   ├── __pycache__ │   │   └── augmentation_options.cpython-37.pyc │   ├── augmentation_options.py │   ├── beverly_hills.txt │   ├── coco.names │   ├── set_annotation_conf.py │   └── voc_conf.json ├── Data │   ├── Photos │   ├── TFRecords │   ├── XML\ Labels │   └── bh_labels.csv ├── Docs │   ├── Augmentor.md │   ├── Evaluator.md │   ├── Predictor.md │   └── Trainer.md ├── Helpers │   ├── __pycache__ │   │   ├── anchors.cpython-37.pyc │   │   ├── annotation_parsers.cpython-37.pyc │   │   ├── dataset_handlers.cpython-37.pyc │   │   ├── utils.cpython-37.pyc │   │   └── visual_tools.cpython-37.pyc │   ├── anchors.py │   ├── annotation_parsers.py │   ├── augmentor.py │   ├── dataset_handlers.py │   ├── scratch │   │   └── label_coordinates.csv │   ├── utils.py │   └── visual_tools.py ├── LICENSE ├── Logs │   └── session.log ├── Main │   ├── __pycache__ │   │   ├── evaluator.cpython-37.pyc │   │   └── models.cpython-37.pyc │   ├── detector.py │   ├── evaluator.py │   ├── models.py │   └── trainer.py ├── Models ├── Output │   ├── Data │   ├── Detections │   ├── Evaluation │   └── Plots ├── README.md ├── Samples │   ├── anchors.png │   ├── anchors_sample.png │   ├── aug1.png │   ├── data.png │   ├── detections.png │   ├── map.png │   ├── pr.png │   ├── sample_image.png │   └── true_false.png ├── requirements.txt └── test.py </code></pre> <h2><strong>Features</strong></h2> <h2><strong>tensorflow 2.2 &amp; keras functional api</strong></h2> <p>This program leverages features that were introduced in tensorflow 2.0 including: </p> <ul> <li><strong>Eager execution:</strong> an imperative programming environment that evaluates operations immediately, without building graphs check <a href="https://www.tensorflow.org/guide/eager" rel="nofollow noreferrer">here</a></li> <li><strong><code>tf.function</code>:</strong> A JIT compilation decorator that speeds up some components of the program check <a href="https://www.tensorflow.org/api_docs/python/tf/function" rel="nofollow noreferrer">here</a></li> <li><strong><code>tf.data</code>:</strong> API for input pipelines check <a href="https://www.tensorflow.org/guide/data" rel="nofollow noreferrer">here</a></li> </ul> <h3><strong>CPU &amp; GPU support</strong></h3> <p>The program detects and uses available GPUs at runtime(training/detection) if no GPUs available, the CPU will be used(slow).</p> <h3><strong>Random weights and DarkNet weights support</strong></h3> <p>Both options are available, and NOTE in case of using DarkNet <a href="https://pjreddie.com/media/files/yolov3.weights" rel="nofollow noreferrer">yolov3 weights</a> you must maintain the same number of <a href="https://gist.github.com/AruniRC/7b3dadd004da04c80198557db5da4bda" rel="nofollow noreferrer">COCO classes</a> (80 classes) as transfer learning to models with different classes will be supported in future versions of this program.</p> <h3><strong>csv-xml annotation parsers</strong></h3> <p>There are 2 currently supported formats that the program is able to read and translate to input.</p> <ul> <li><strong>XML VOC format which looks like the following example:</strong></li> </ul> <pre class="lang-xml prettyprint-override"><code>&lt;annotation&gt; &lt;folder&gt;/path/to/image/folder&lt;/folder&gt; &lt;filename&gt;image_filename.png&lt;/filename&gt; &lt;path&gt;/path/to/image/folder/image_filename.png&lt;/path&gt; &lt;size&gt; &lt;width&gt;image_width&lt;/width&gt; &lt;height&gt;image_height&lt;/height&gt; &lt;depth&gt;image_depth&lt;/depth&gt; &lt;/size&gt; &lt;object&gt; &lt;name&gt;obj1_name&lt;/name&gt; &lt;bndbox&gt; &lt;xmin&gt;382.99999987200005&lt;/xmin&gt; &lt;ymin&gt;447.000000174&lt;/ymin&gt; &lt;xmax&gt;400.00000051200004&lt;/xmax&gt; &lt;ymax&gt;469.000000098&lt;/ymax&gt; &lt;/bndbox&gt; &lt;/annotation&gt; </code></pre> <ul> <li><strong>CSV with relative labels that looks like the following example:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/rODNY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rODNY.png" alt="table"></a></p> <h3><strong>Anchor generator</strong></h3> <p>A <a href="https://en.wikipedia.org/wiki/K-means_clustering" rel="nofollow noreferrer">k-means</a> algorithm finds the optimal sizes and generates anchors with process visualization.</p> <h3><strong>matplotlib visualization of all stages</strong></h3> <p><strong>Including:</strong></p> <ul> <li><strong>k-means visualization:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/vqgYA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vqgYA.png" alt="kmeans"></a></p> <ul> <li><strong>Generated anchors:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/z6jJq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z6jJq.png" alt="anchors"></a></p> <ul> <li><strong>Precision and recall curves:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/e7pWe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e7pWe.png" alt="pr"></a></p> <ul> <li><strong>Evaluation bar charts:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/jiAIF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jiAIF.png" alt="map"></a></p> <ul> <li><strong>Actual vs. detections:</strong></li> </ul> <p><a href="https://i.stack.imgur.com/zOb1P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zOb1P.png" alt="true false"></a></p> <p>You can always visualize different stages of the program using my other repo <a href="https://github.com/emadboctorx/labelpix" rel="nofollow noreferrer">labelpix</a> which is tool for drawing bounding boxes, but can also be used to visualize bounding boxes over images using csv files in the format mentioned above</p> <h3><strong><code>tf.data</code> input pipeline</strong></h3> <p><a href="https://www.tensorflow.org/tutorials/load_data/tfrecord" rel="nofollow noreferrer">TFRecords</a> a simple format for storing a sequence of binary records. Protocol buffers are a cross-platform, cross-language library for efficient serialization of structured data and are used as input pipeline to store and read data efficiently the program takes as input images and their respective annotations and builds training and validation(optional) TFRecords to be further used for all operations and TFRecords are also used in the evaluation(mid/post) training, so it's valid to say you can delete images to free space after conversion to TFRecords.</p> <h3><strong><code>pandas</code> &amp; <code>numpy</code> data handling</strong></h3> <p>Most of the operations are using numpy and pandas for efficiency and vectorization.</p> <h3><strong><code>imgaug</code> augmentation pipeline(customizable)</strong></h3> <p>Special thanks to the amazing <a href="https://github.com/aleju/imgaug" rel="nofollow noreferrer">imgaug</a> creators, an augmentation pipeline(optional) is available and NOTE that the augmentation is conducted <strong>before</strong> the training not during the training due to technical complications to integrate tensorflow and imgaug. If you have a small dataset, augmentation is an option and it can be preconfigured before the training </p> <h3><strong><code>logging</code></strong></h3> <p>Different operations are recorded using <code>logging</code> module.</p> <h3><strong>All-in-1 custom <code>Trainer</code> class</strong></h3> <p>For custom training, <code>Trainer</code> class accepts configurations for augmentation, new anchor generation, new dataset(TFRecord(s)) creation, mAP evaluation mid-training and post training. So all you have to do is place images in Data > Photos, provide the configuration that suits you and start the training process, all operations are managed from the same place for convenience. For detailed instructions check </p> <h3><strong>Stop and resume training support</strong></h3> <p>by default the trainer checkpoints to Models > checkpoint_name.tf at the end of each training epoch which enables the training to be resumed at any given point by loading the checkpoint which would be the most recent.</p> <h3><strong>Fully vectorized mAP evaluation</strong></h3> <p>Evaluation is optional during the training every n epochs(not recommended for large datasets as it predicts every image in the dataset) and one evaluation at the end which is optional as well. Training and validation datasets can be evaluated separately and calculate mAP(mean average precision) as well as precision and recall curves for every class in the model.</p> <p><code>trainer.py</code></p> <pre><code>import tensorflow as tf import os import numpy as np import pandas as pd from pathlib import Path import sys sys.path.append('..') from tensorflow.keras.callbacks import ( ReduceLROnPlateau, TensorBoard, ModelCheckpoint, Callback, EarlyStopping, ) import shutil from Helpers.dataset_handlers import read_tfr, save_tfr, get_feature_map from Helpers.annotation_parsers import parse_voc_folder from Helpers.anchors import k_means, generate_anchors from Helpers.augmentor import DataAugment from Config.augmentation_options import augmentations from Main.models import V3Model from Helpers.utils import transform_images, transform_targets from Helpers.annotation_parsers import adjust_non_voc_csv from Helpers.utils import calculate_loss, timer, default_logger, activate_gpu from Main.evaluator import Evaluator class Trainer(V3Model): """ Create a training instance. """ def __init__( self, input_shape, classes_file, image_width, image_height, train_tf_record=None, valid_tf_record=None, anchors=None, masks=None, max_boxes=100, iou_threshold=0.5, score_threshold=0.5, ): """ Initialize training. Args: input_shape: tuple, (n, n, c) classes_file: File containing class names \n delimited. image_width: Width of the original image. image_height: Height of the original image. train_tf_record: TFRecord file. valid_tf_record: TFRecord file. anchors: numpy array of (w, h) pairs. masks: numpy array of masks. max_boxes: Maximum boxes of the TFRecords provided(if any) or maximum boxes setting. iou_threshold: float, values less than the threshold are ignored. score_threshold: float, values less than the threshold are ignored. """ self.classes_file = classes_file self.class_names = [ item.strip() for item in open(classes_file).readlines() ] super().__init__( input_shape, len(self.class_names), anchors, masks, max_boxes, iou_threshold, score_threshold, ) self.train_tf_record = train_tf_record self.valid_tf_record = valid_tf_record self.image_folder = ( Path(os.path.join('..', 'Data', 'Photos')).absolute().resolve() ) self.image_width = image_width self.image_height = image_height def get_adjusted_labels(self, configuration): """ Adjust labels according to given configuration. Args: configuration: A dictionary containing any of the following keys: - relative_labels - from_xml - adjusted_frame Returns: pandas DataFrame with adjusted labels. """ labels_frame = None check = 0 if configuration.get('relative_labels'): labels_frame = adjust_non_voc_csv( configuration['relative_labels'], self.image_folder, self.image_width, self.image_height, ) check += 1 if configuration.get('from_xml'): if check: raise ValueError(f'Got more than one configuration') labels_frame = parse_voc_folder( os.path.join('..', 'Data', 'XML Labels'), os.path.join('..', 'Config', 'voc_conf.json'), ) labels_frame.to_csv( os.path.join('..', 'Output', 'Data', 'parsed_from_xml.csv'), index=False, ) check += 1 if configuration.get('adjusted_frame'): if check: raise ValueError(f'Got more than one configuration') labels_frame = pd.read_csv(configuration['adjusted_frame']) check += 1 return labels_frame def generate_new_anchors(self, new_anchors_conf): """ Create new anchors according to given configuration. Args: new_anchors_conf: A dictionary containing the following keys: - anchors_no and one of the following: - relative_labels - from_xml - adjusted_frame Returns: None """ anchor_no = new_anchors_conf.get('anchor_no') if not anchor_no: raise ValueError(f'No "anchor_no" found in new_anchors_conf') labels_frame = self.get_adjusted_labels(new_anchors_conf) relative_dims = np.array( list( zip( labels_frame['Relative Width'], labels_frame['Relative Height'], ) ) ) centroids, _ = k_means(relative_dims, anchor_no, frame=labels_frame) self.anchors = ( generate_anchors(self.image_width, self.image_height, centroids) / self.input_shape[0] ) default_logger.info('Changed default anchors to generated ones') def generate_new_frame(self, new_dataset_conf): """ Create new labels frame according to given configuration. Args: new_dataset_conf: A dictionary containing the following keys: - dataset_name and one of the following: - relative_labels - from_xml - adjusted_frame - coordinate_labels(optional in case of augmentation) - augmentation(optional) and this implies the following: - sequences - workers(optional, defaults to 32) - batch_size(optional, defaults to 64) - new_size(optional, defaults to None) Returns: pandas DataFrame adjusted for building the dataset containing labels or labels and augmented labels combined """ if not new_dataset_conf.get('dataset_name'): raise ValueError('dataset_name not found in new_dataset_conf') labels_frame = self.get_adjusted_labels(new_dataset_conf) if new_dataset_conf.get('augmentation'): labels_frame = self.augment_photos(new_dataset_conf) return labels_frame def initialize_dataset(self, tf_record, batch_size, shuffle_buffer=512): """ Initialize and prepare TFRecord dataset for training. Args: tf_record: TFRecord file. batch_size: int, training batch size shuffle_buffer: Buffer size for shuffling dataset. Returns: dataset. """ dataset = read_tfr( tf_record, self.classes_file, get_feature_map(), self.max_boxes ) dataset = dataset.shuffle(shuffle_buffer) dataset = dataset.batch(batch_size) dataset = dataset.map( lambda x, y: ( transform_images(x, self.input_shape[0]), transform_targets( y, self.anchors, self.masks, self.input_shape[0] ), ) ) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return dataset @staticmethod def augment_photos(new_dataset_conf): """ Augment photos in self.image_paths Args: new_dataset_conf: A dictionary containing the following keys: one of the following: - relative_labels - from_xml - adjusted_frame - coordinate_labels(optional) and: - sequences - workers(optional, defaults to 32) - batch_size(optional, defaults to 64) - new_size(optional, defaults to None) Returns: pandas DataFrame with both original and augmented data. """ sequences = new_dataset_conf.get('sequences') relative_labels = new_dataset_conf.get('relative_labels') coordinate_labels = new_dataset_conf.get('coordinate_labels') workers = new_dataset_conf.get('workers') batch_size = new_dataset_conf.get('batch_size') new_augmentation_size = new_dataset_conf.get('new_size') if not sequences: raise ValueError(f'"sequences" not found in new_dataset_conf') if not relative_labels: raise ValueError(f'No "relative_labels" found in new_dataset_conf') augment = DataAugment( relative_labels, augmentations, workers or 32, coordinate_labels ) augment.create_sequences(sequences) return augment.augment_photos_folder( batch_size or 64, new_augmentation_size ) @timer(default_logger) def evaluate( self, weights_file, merge, workers, shuffle_buffer, min_overlaps, display_stats=True, plot_stats=True, save_figs=True, ): """ Evaluate on training and validation datasets. Args: weights_file: Path to trained .tf file. merge: If False, training and validation datasets will be evaluated separately. workers: Parallel predictions. shuffle_buffer: Buffer size for shuffling datasets. min_overlaps: a float value between 0 and 1, or a dictionary containing each class in self.class_names mapped to its minimum overlap display_stats: If True evaluation statistics will be printed. plot_stats: If True, evaluation statistics will be plotted including precision and recall curves and mAP save_figs: If True, resulting plots will be save to Output folder. Returns: stats, map_score. """ default_logger.info('Starting evaluation ...') evaluator = Evaluator( self.input_shape, self.train_tf_record, self.valid_tf_record, self.classes_file, self.anchors, self.masks, self.max_boxes, self.iou_threshold, self.score_threshold, ) predictions = evaluator.make_predictions( weights_file, merge, workers, shuffle_buffer ) if isinstance(predictions, tuple): training_predictions, valid_predictions = predictions if any([training_predictions.empty, valid_predictions.empty]): default_logger.info( 'Aborting evaluations, no detections found' ) return training_actual = pd.read_csv( os.path.join('..', 'Data', 'TFRecords', 'training_data.csv') ) valid_actual = pd.read_csv( os.path.join('..', 'Data', 'TFRecords', 'test_data.csv') ) training_stats, training_map = evaluator.calculate_map( training_predictions, training_actual, min_overlaps, display_stats, 'Train', save_figs, plot_stats, ) valid_stats, valid_map = evaluator.calculate_map( valid_predictions, valid_actual, min_overlaps, display_stats, 'Valid', save_figs, plot_stats, ) return training_stats, training_map, valid_stats, valid_map actual_data = pd.read_csv( os.path.join('..', 'Data', 'TFRecords', 'full_data.csv') ) if predictions.empty: default_logger.info('Aborting evaluations, no detections found') return stats, map_score = evaluator.calculate_map( predictions, actual_data, min_overlaps, display_stats, save_figs=save_figs, plot_results=plot_stats, ) return stats, map_score @staticmethod def clear_outputs(): """ Clear Output folder. Returns: None """ for file_name in os.listdir(os.path.join('..', 'Output')): if not file_name.startswith('.'): full_path = ( Path(os.path.join('..', 'Output', file_name)) .absolute() .resolve() ) if os.path.isdir(full_path): shutil.rmtree(full_path) else: os.remove(full_path) default_logger.info(f'Deleted old output: {full_path}') def create_new_dataset(self, new_dataset_conf): """ Build new dataset and respective TFRecord(s). Args: new_dataset_conf: A dictionary containing the following keys: one of the following: - relative_labels - from_xml - adjusted_frame - coordinate_labels(optional) and: - sequences - workers(optional, defaults to 32) - batch_size(optional, defaults to 64) - new_size(optional, defaults to None) Returns: None """ default_logger.info(f'Generating new dataset ...') test_size = new_dataset_conf.get('test_size') labels_frame = self.generate_new_frame(new_dataset_conf) save_tfr( labels_frame, os.path.join('..', 'Data', 'TFRecords'), new_dataset_conf['dataset_name'], test_size, self, ) def check_tf_records(self): """ Ensure TFRecords are specified to start training. Returns: None """ if not self.train_tf_record: issue = 'No training TFRecord specified' default_logger.error(issue) raise ValueError(issue) if not self.valid_tf_record: issue = 'No validation TFRecord specified' default_logger.error(issue) raise ValueError(issue) @staticmethod def create_callbacks(checkpoint_name): """ Create a list of tf.keras.callbacks. Args: checkpoint_name: Name under which the checkpoint is saved. Returns: callbacks. """ return [ ReduceLROnPlateau(verbose=3), ModelCheckpoint( os.path.join(checkpoint_name), verbose=1, save_weights_only=True, ), TensorBoard(log_dir=os.path.join('..', 'Logs')), EarlyStopping(monitor='val_loss', patience=6, verbose=1), ] @timer(default_logger) def train( self, epochs, batch_size, learning_rate, new_anchors_conf=None, new_dataset_conf=None, dataset_name=None, weights=None, evaluate=True, merge_evaluation=True, evaluation_workers=8, shuffle_buffer=512, min_overlaps=None, display_stats=True, plot_stats=True, save_figs=True, clear_outputs=False, n_epoch_eval=None, ): """ Train on the dataset. Args: epochs: Number of training epochs. batch_size: Training batch size. learning_rate: non-negative value. new_anchors_conf: A dictionary containing anchor generation configuration. new_dataset_conf: A dictionary containing dataset generation configuration. dataset_name: Name of the dataset for model checkpoints. weights: .tf or .weights file evaluate: If False, the trained model will not be evaluated after training. merge_evaluation: If False, training and validation maps will be calculated separately. evaluation_workers: Parallel predictions. shuffle_buffer: Buffer size for shuffling datasets. min_overlaps: a float value between 0 and 1, or a dictionary containing each class in self.class_names mapped to its minimum overlap display_stats: If True and evaluate=True, evaluation statistics will be displayed. plot_stats: If True, Precision and recall curves as well as comparative bar charts will be plotted save_figs: If True and plot_stats=True, figures will be saved clear_outputs: If True, old outputs will be cleared n_epoch_eval: Conduct evaluation every n epoch. Returns: history object, pandas DataFrame with statistics, mAP score. """ min_overlaps = min_overlaps or 0.5 if clear_outputs: self.clear_outputs() activate_gpu() default_logger.info(f'Starting training ...') if new_anchors_conf: default_logger.info(f'Generating new anchors ...') self.generate_new_anchors(new_anchors_conf) self.create_models() if weights: self.load_weights(weights) if new_dataset_conf: self.create_new_dataset(new_dataset_conf) self.check_tf_records() training_dataset = self.initialize_dataset( self.train_tf_record, batch_size, shuffle_buffer ) valid_dataset = self.initialize_dataset( self.valid_tf_record, batch_size, shuffle_buffer ) optimizer = tf.keras.optimizers.Adam(learning_rate) loss = [ calculate_loss( self.anchors[mask], self.classes, self.iou_threshold ) for mask in self.masks ] self.training_model.compile(optimizer=optimizer, loss=loss) checkpoint_name = os.path.join( '..', 'Models', f'{dataset_name or "trained"}_model.tf' ) callbacks = self.create_callbacks(checkpoint_name) if n_epoch_eval: mid_train_eval = MidTrainingEvaluator( self.input_shape, self.classes_file, self.image_width, self.image_height, self.train_tf_record, self.valid_tf_record, self.anchors, self.masks, self.max_boxes, self.iou_threshold, self.score_threshold, n_epoch_eval, merge_evaluation, evaluation_workers, shuffle_buffer, min_overlaps, display_stats, plot_stats, save_figs, checkpoint_name, ) callbacks.append(mid_train_eval) history = self.training_model.fit( training_dataset, epochs=epochs, callbacks=callbacks, validation_data=valid_dataset, ) default_logger.info('Training complete') if evaluate: evaluations = self.evaluate( checkpoint_name, merge_evaluation, evaluation_workers, shuffle_buffer, min_overlaps, display_stats, plot_stats, save_figs, ) return evaluations, history return history class MidTrainingEvaluator(Callback, Trainer): """ Tool to evaluate trained model on the go(during the training, every n epochs). """ def __init__( self, input_shape, classes_file, image_width, image_height, train_tf_record, valid_tf_record, anchors, masks, max_boxes, iou_threshold, score_threshold, n_epochs, merge, workers, shuffle_buffer, min_overlaps, display_stats, plot_stats, save_figs, weights_file, ): """ Initialize mid-training evaluation settings. Args: input_shape: tuple, (n, n, c) classes_file: File containing class names \n delimited. image_width: Width of the original image. image_height: Height of the original image. train_tf_record: TFRecord file. valid_tf_record: TFRecord file. anchors: numpy array of (w, h) pairs. masks: numpy array of masks. max_boxes: Maximum boxes of the TFRecords provided(if any) or maximum boxes setting. iou_threshold: float, values less than the threshold are ignored. score_threshold: float, values less than the threshold are ignored. n_epochs: int, perform evaluation every n epochs merge: If True, The whole dataset(train + valid) will be evaluated workers: Parallel predictions shuffle_buffer: Buffer size for shuffling datasets min_overlaps: a float value between 0 and 1, or a dictionary containing each class in self.class_names mapped to its minimum overlap display_stats: If True, statistics will be displayed at the end. plot_stats: If True, precision and recall curves as well as comparison bar charts will be plotted. save_figs: If True and display_stats, plots will be save to Output folder weights_file: .tf file(most recent checkpoint) """ Trainer.__init__( self, input_shape, classes_file, image_width, image_height, train_tf_record, valid_tf_record, anchors, masks, max_boxes, iou_threshold, score_threshold, ) self.n_epochs = n_epochs self.evaluation_args = [ weights_file, merge, workers, shuffle_buffer, min_overlaps, display_stats, plot_stats, save_figs, ] def on_epoch_end(self, epoch, logs=None): """ Start evaluation in valid epochs. Args: epoch: int, epoch number. logs: dict, Tensorboard log. Returns: None """ if not (epoch + 1) % self.n_epochs == 0: return self.evaluate(*self.evaluation_args) os.mkdir( os.path.join( '..', 'Output', 'Evaluation', f'epoch-{epoch}-evaluation' ) ) for file_name in os.listdir( os.path.join('..', 'Output', 'Evaluation') ): if not os.path.isdir(file_name) and ( file_name.endswith('.png') or 'prediction' in file_name ): full_path = str( Path(os.path.join('..', 'Output', 'Evaluation', file_name)) .absolute() .resolve() ) new_path = str( Path( os.path.join( '..', 'Output', 'Evaluation', f'epoch-{epoch}-evaluation', file_name, ) ) .absolute() .resolve() ) shutil.move(full_path, new_path) </code></pre> <p><code>evaluator.py</code></p> <pre><code>import cv2 import pandas as pd import numpy as np import tensorflow as tf import os import sys sys.path.append('..') from concurrent.futures import ThreadPoolExecutor, as_completed from Main.models import V3Model from Helpers.dataset_handlers import read_tfr, get_feature_map from Helpers.utils import ( transform_images, get_detection_data, default_logger, timer, ) from Helpers.visual_tools import visualize_pr, visualize_evaluation_stats class Evaluator(V3Model): def __init__( self, input_shape, train_tf_record, valid_tf_record, classes_file, anchors=None, masks=None, max_boxes=100, iou_threshold=0.5, score_threshold=0.5, ): """ Evaluate a trained model. Args: input_shape: input_shape: tuple, (n, n, c) train_tf_record: Path to training TFRecord file. valid_tf_record: Path to validation TFRecord file. classes_file: File containing class names \n delimited. anchors: numpy array of (w, h) pairs. masks: numpy array of masks. max_boxes: Maximum boxes of the TFRecords provided. iou_threshold: Minimum overlap value. score_threshold: Minimum confidence for detection to count as true positive. """ self.classes_file = classes_file self.class_names = [ item.strip() for item in open(classes_file).readlines() ] super().__init__( input_shape, len(self.class_names), anchors, masks, max_boxes, iou_threshold, score_threshold, ) self.train_tf_record = train_tf_record self.valid_tf_record = valid_tf_record self.train_dataset_size = sum( 1 for _ in tf.data.TFRecordDataset(train_tf_record) ) self.valid_dataset_size = sum( 1 for _ in tf.data.TFRecordDataset(valid_tf_record) ) self.dataset_size = self.train_dataset_size + self.valid_dataset_size self.predicted = 1 def predict_image(self, image_data, features): """ Make predictions on a single image from the TFRecord. Args: image_data: image as numpy array features: features of the TFRecord. Returns: pandas DataFrame with detection data. """ image_path = bytes.decode(features['image_path'].numpy()) image_name = os.path.basename(image_path) image = tf.expand_dims(image_data, 0) resized = transform_images(image, self.input_shape[0]) outs = self.inference_model(resized) adjusted = cv2.cvtColor(image_data.numpy(), cv2.COLOR_RGB2BGR) result = ( get_detection_data(adjusted, image_name, outs, self.class_names), image_name, ) return result @staticmethod def get_dataset_next(dataset): try: return next(dataset) except tf.errors.UnknownError as e: # sometimes encountered when reading from google drive default_logger.error( f'Error occurred during reading from dataset\n{e}' ) def predict_dataset( self, dataset, workers=16, split='train', batch_size=64 ): """ Predict entire dataset. Args: dataset: MapDataset object. workers: Parallel predictions. split: str representation of the dataset 'train' or 'valid' batch_size: Prediction batch size. Returns: pandas DataFrame with entire dataset predictions. """ predictions = [] sizes = { 'train': self.train_dataset_size, 'valid': self.valid_dataset_size, } size = sizes[split] current_prediction = 0 with ThreadPoolExecutor(max_workers=workers) as executor: while current_prediction &lt; size: current_batch = [] for _ in range(min(batch_size, size - current_prediction)): item = self.get_dataset_next(dataset) if item is not None: current_batch.append(item) future_predictions = { executor.submit( self.predict_image, img_data, features ): features['image_path'] for img_data, labels, features in current_batch } for future_prediction in as_completed(future_predictions): result, completed_image = future_prediction.result() predictions.append(result) completed = f'{self.predicted}/{self.dataset_size}' percent = (self.predicted / self.dataset_size) * 100 print( f'\rpredicting {completed_image} {completed}\t{percent}% completed', end='', ) self.predicted += 1 current_prediction += 1 return pd.concat(predictions) @timer(default_logger) def make_predictions( self, trained_weights, merge=False, workers=16, shuffle_buffer=512, batch_size=64, ): """ Make predictions on both training and validation data sets and save results as csv in Output folder. Args: trained_weights: Trained .tf weights or .weights file(in case self.classes = 80). merge: If True a single file will be saved for training and validation sets predictions combined. workers: Parallel predictions. shuffle_buffer: int, shuffle dataset buffer size. batch_size: Prediction batch size. Returns: 1 combined pandas DataFrame for entire dataset predictions or 2 pandas DataFrame(s) for training and validation data sets respectively. """ self.create_models() self.load_weights(trained_weights) features = get_feature_map() train_dataset = read_tfr( self.train_tf_record, self.classes_file, features, self.max_boxes, get_features=True, ) valid_dataset = read_tfr( self.valid_tf_record, self.classes_file, features, self.max_boxes, get_features=True, ) train_dataset.shuffle(shuffle_buffer) valid_dataset.shuffle(shuffle_buffer) train_dataset = iter(train_dataset) valid_dataset = iter(valid_dataset) train_predictions = self.predict_dataset( train_dataset, workers, 'train', batch_size ) valid_predictions = self.predict_dataset( valid_dataset, workers, 'valid', batch_size ) if merge: predictions = pd.concat([train_predictions, valid_predictions]) save_path = os.path.join( '..', 'Output', 'Data', 'full_dataset_predictions.csv' ) predictions.to_csv(save_path, index=False) return predictions train_path = os.path.join( '..', 'Output', 'Data', 'train_dataset_predictions.csv' ) valid_path = os.path.join( '..', 'Output', 'Data', 'valid_dataset_predictions.csv' ) train_predictions.to_csv(train_path, index=False) valid_predictions.to_csv(valid_path, index=False) return train_predictions, valid_predictions @staticmethod def get_area(frame, columns): """ Calculate bounding boxes areas. Args: frame: pandas DataFrame that contains prediction data. columns: column names that represent x1, y1, x2, y2. Returns: pandas Series(area column) """ x1, y1, x2, y2 = [frame[column] for column in columns] return (x2 - x1) * (y2 - y1) def get_true_positives(self, detections, actual, min_overlaps): """ Filter True positive detections out of all detections. Args: detections: pandas DataFrame with all detections. actual: pandas DataFrame with real data. min_overlaps: a float value between 0 and 1, or a dictionary containing each class in self.class_names mapped to its minimum overlap Returns: pandas DataFrame that contains detections that satisfy True positive constraints. """ if detections.empty: raise ValueError(f'Empty predictions frame') if isinstance(min_overlaps, float): assert 0 &lt;= min_overlaps &lt; 1, ( f'min_overlaps should be ' f'between 0 and 1, {min_overlaps} is given' ) if isinstance(min_overlaps, dict): assert all( [0 &lt; min_overlap &lt; 1 for min_overlap in min_overlaps.values()] ) assert all([obj in min_overlaps for obj in self.class_names]), ( f'{[item for item in self.class_names if item not in min_overlaps]} ' f'are missing in min_overlaps' ) actual = actual.rename( columns={'Image Path': 'image', 'Object Name': 'object_name'} ) actual['image'] = actual['image'].apply(lambda x: os.path.split(x)[-1]) random_gen = np.random.default_rng() if 'detection_key' not in detections.columns: detection_keys = random_gen.choice( len(detections), size=len(detections), replace=False ) detections['detection_key'] = detection_keys total_frame = actual.merge(detections, on=['image', 'object_name']) assert ( not total_frame.empty ), 'No common image names found between actual and detections' total_frame['x_max_common'] = total_frame[['X_max', 'x2']].min(1) total_frame['x_min_common'] = total_frame[['X_min', 'x1']].max(1) total_frame['y_max_common'] = total_frame[['Y_max', 'y2']].min(1) total_frame['y_min_common'] = total_frame[['Y_min', 'y1']].max(1) true_intersect = ( total_frame['x_max_common'] &gt; total_frame['x_min_common'] ) &amp; (total_frame['y_max_common'] &gt; total_frame['y_min_common']) total_frame = total_frame[true_intersect] actual_areas = self.get_area( total_frame, ['X_min', 'Y_min', 'X_max', 'Y_max'] ) predicted_areas = self.get_area(total_frame, ['x1', 'y1', 'x2', 'y2']) intersect_areas = self.get_area( total_frame, ['x_min_common', 'y_min_common', 'x_max_common', 'y_max_common'], ) iou_areas = intersect_areas / ( actual_areas + predicted_areas - intersect_areas ) total_frame['iou'] = iou_areas if isinstance(min_overlaps, float): return total_frame[total_frame['iou'] &gt;= min_overlaps] if isinstance(min_overlaps, dict): class_data = [ (name, total_frame[total_frame['object_name'] == name]) for name in self.class_names ] thresholds = [min_overlaps[item[0]] for item in class_data] frames = [ item[1][item[1]['iou'] &gt;= threshold] for (item, threshold) in zip(class_data, thresholds) if not item[1].empty ] return pd.concat(frames) @staticmethod def get_false_positives(detections, true_positive): """ Filter out False positives in all detections. Args: detections: pandas DataFrame with detection data. true_positive: pandas DataFrame with True positive data. Returns: pandas DataFrame with False positives. """ keys_before = detections['detection_key'].values keys_after = true_positive['detection_key'].values false_keys = np.where(np.isin(keys_before, keys_after, invert=True)) false_keys = keys_before[false_keys] false_positives = detections.set_index('detection_key').loc[false_keys] return false_positives.reset_index() @staticmethod def combine_results(true_positive, false_positive): """ Combine True positives and False positives. Args: true_positive: pandas DataFrame with True positive data. false_positive: pandas DataFrame with False positive data. Returns: pandas DataFrame with all detections combined. """ true_positive['true_positive'] = 1 true_positive['false_positive'] = 0 true_positive = true_positive[ [ 'image', 'object_name', 'score', 'x_min_common', 'y_min_common', 'x_max_common', 'y_max_common', 'iou', 'image_width', 'image_height', 'true_positive', 'false_positive', 'detection_key', ] ] true_positive = true_positive.rename( columns={ 'x_min_common': 'x1', 'y_min_common': 'y1', 'x_max_common': 'x2', 'y_max_common': 'y2', } ) false_positive['iou'] = 0 false_positive['true_positive'] = 0 false_positive['false_positive'] = 1 false_positive = false_positive[ [ 'image', 'object_name', 'score', 'x1', 'y1', 'x2', 'y2', 'iou', 'image_width', 'image_height', 'true_positive', 'false_positive', 'detection_key', ] ] return pd.concat([true_positive, false_positive]) def calculate_stats( self, actual_data, detection_data, true_positives, false_positives, combined, ): """ Calculate prediction statistics for every class in self.class_names. Args: actual_data: pandas DataFrame with real data. detection_data: pandas DataFrame with all detection data before filtration. true_positives: pandas DataFrame with True positives. false_positives: pandas DataFrame with False positives. combined: pandas DataFrame with True and False positives combined. Returns: pandas DataFrame with statistics for all classes. """ class_stats = [] for class_name in self.class_names: stats = dict() stats['Class Name'] = class_name stats['Average Precision'] = ( combined[combined['object_name'] == class_name][ 'average_precision' ].sum() * 100 ) stats['Actual'] = len( actual_data[actual_data["Object Name"] == class_name] ) stats['Detections'] = len( detection_data[detection_data["object_name"] == class_name] ) stats['True Positives'] = len( true_positives[true_positives["object_name"] == class_name] ) stats['False Positives'] = len( false_positives[false_positives["object_name"] == class_name] ) stats['Combined'] = len( combined[combined["object_name"] == class_name] ) class_stats.append(stats) total_stats = pd.DataFrame(class_stats).sort_values( by='Average Precision', ascending=False ) return total_stats @staticmethod def calculate_ap(combined, total_actual): """ Calculate average precision for a single object class. Args: combined: pandas DataFrame with True and False positives combined. total_actual: Total number of actual object class boxes. Returns: pandas DataFrame with average precisions calculated. """ combined = combined.sort_values( by='score', ascending=False ).reset_index(drop=True) combined['acc_tp'] = combined['true_positive'].cumsum() combined['acc_fp'] = combined['false_positive'].cumsum() combined['precision'] = combined['acc_tp'] / ( combined['acc_tp'] + combined['acc_fp'] ) combined['recall'] = combined['acc_tp'] / total_actual combined['m_pre1'] = combined['precision'].shift(1, fill_value=0) combined['m_pre'] = combined[['m_pre1', 'precision']].max(axis=1) combined['m_rec1'] = combined['recall'].shift(1, fill_value=0) combined.loc[ combined['m_rec1'] != combined['recall'], 'valid_m_rec' ] = 1 combined['average_precision'] = ( combined['recall'] - combined['m_rec1'] ) * combined['m_pre'] return combined @timer(default_logger) def calculate_map( self, prediction_data, actual_data, min_overlaps, display_stats=False, fig_prefix='', save_figs=True, plot_results=True, ): """ Calculate mAP(mean average precision) for the trained model. Args: prediction_data: pandas DataFrame containing predictions. actual_data: pandas DataFrame containing actual data. min_overlaps: a float value between 0 and 1, or a dictionary containing each class in self.class_names mapped to its minimum overlap display_stats: If True, statistics will be displayed. fig_prefix: Prefix for plot titles. save_figs: If True, figures will be saved. plot_results: If True, results will be calculated. Returns: pandas DataFrame with statistics, mAP score. """ actual_data['Object Name'] = actual_data['Object Name'].apply( lambda x: x.replace("b'", '').replace("'", '') ) class_counts = actual_data['Object Name'].value_counts().to_dict() true_positives = self.get_true_positives( prediction_data, actual_data, min_overlaps ) false_positives = self.get_false_positives( prediction_data, true_positives ) combined = self.combine_results(true_positives, false_positives) class_groups = combined.groupby('object_name') calculated = pd.concat( [ self.calculate_ap(group, class_counts.get(object_name)) for object_name, group in class_groups ] ) stats = self.calculate_stats( actual_data, prediction_data, true_positives, false_positives, calculated, ) map_score = stats['Average Precision'].mean() if display_stats: pd.set_option( 'display.max_rows', None, 'display.max_columns', None, 'display.width', None, ) print(stats.sort_values(by='Average Precision', ascending=False)) print(f'mAP score: {map_score}%') pd.reset_option('display.[max_rows, max_columns, width]') if plot_results: visualize_pr(calculated, save_figs, fig_prefix) visualize_evaluation_stats(stats, fig_prefix) return stats, map_score </code></pre>
[]
[ { "body": "<h2>Paths</h2>\n<pre><code>sys.path.append('..')\n</code></pre>\n<p>is scary. If it needs to happen at all, it should not be done at the global level - that will interfere with other consumers of your program's symbols.</p>\n<p>If it can be avoided, don't do this at all.</p>\n<h2>Type hints</h2>\n<p>In a function signature as long and complex as this:</p>\n<pre><code>def __init__(\n self,\n input_shape,\n classes_file,\n image_width,\n image_height,\n train_tf_record=None,\n valid_tf_record=None,\n anchors=None,\n masks=None,\n max_boxes=100,\n iou_threshold=0.5,\n score_threshold=0.5,\n):\n</code></pre>\n<p>type hints would help. <code>image_width</code> and <code>image_height</code> can probably be <code>image_width: int, image_height: int</code> for instance.</p>\n<h2>Context manager</h2>\n<pre><code> self.class_names = [\n item.strip() for item in open(classes_file).readlines()\n ]\n</code></pre>\n<p>should close the file after it's done:</p>\n<pre><code>with open(classes_file) as f:\n self.class_names = [item.strip() for item in f]\n</code></pre>\n<p><code>readlines</code> can be replaced with implicit iteration over the file handle.</p>\n<h2>Path formation</h2>\n<pre><code>Path(os.path.join('..', 'Data', 'Photos'))\n</code></pre>\n<p>should be</p>\n<pre><code>Path('..') / 'Data' / 'Photos'\n</code></pre>\n<p>You also write <code>os.path.join</code> elsewhere that a <code>Path</code> would be nicer.</p>\n<p><code>os.path.isdir</code> and <code>shutil.move</code> should similarly be replaced with a call to a <code>Path</code> member.</p>\n<h2>Interpolation</h2>\n<pre><code>f'Got more than one configuration'\n</code></pre>\n<p>does not need to be an f-string since there are no fields.</p>\n<h2>Throw-away values</h2>\n<pre><code> labels_frame = self.get_adjusted_labels(new_dataset_conf)\n if new_dataset_conf.get('augmentation'):\n labels_frame = self.augment_photos(new_dataset_conf)\n</code></pre>\n<p>The first assignment should be in an <code>else</code>, since you throw it away in one case.</p>\n<h2>Exception logging</h2>\n<pre><code> default_logger.error(issue)\n raise ValueError(issue)\n</code></pre>\n<p>Pass the exception to <code>error(exc_info=)</code>; read about it here:</p>\n<p><a href=\"https://docs.python.org/3.8/library/logging.html#logging.Logger.debug\" rel=\"nofollow noreferrer\">https://docs.python.org/3.8/library/logging.html#logging.Logger.debug</a></p>\n<h2>Logic inversion</h2>\n<pre><code>not (epoch + 1) % self.n_epochs == 0\n</code></pre>\n<p>should be</p>\n<pre><code>(epoch + 1) % self.n_epochs != 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:51:36.950", "Id": "480492", "Score": "0", "body": "Thanks, that's really helpful, i'll take some time examining the documentation. I really hate `sys.path.append(..)` but otherwise i might need to create a wheel which can be a hassle anyway what do you think of the whole code in general? You can check the rest of the code on my github https://github.com/emadboctorx/yolov3-keras-tf2 and feel free to post other answers/update your answers as I don't think this can be reviewed all at once thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:32:14.083", "Id": "244735", "ParentId": "242676", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T00:04:34.553", "Id": "242676", "Score": "5", "Tags": [ "python", "python-3.x", "machine-learning", "object-detection" ], "Title": "Yolov3 Real Time Object Detection in tensorflow 2.2" }
242676
<p>Hello I am a beginner in PHP and I need some opinions. How secure is my registration code ? If I launched this on the web would you feel safe signing up with personal info ? </p> <pre><code> &lt;?php // shows all errors ini_set('display_errors', 1); error_reporting(E_ALL); //check if form is submitted if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) { // looks like a hack, send to index.php header('Location: index.php'); die(); } include("connect.php"); $errors = []; if (empty($_POST["username"])) { $errors[] = "Fill in username to sign up"; } if (empty($_POST["pw"])) { $errors[] = "Fill in password to sign up"; } if (empty($_POST["pw2"])) { $errors[] = "Confirm password to sign up"; } // and so on... if ($_POST['pw'] !== $_POST['pw2']) { $errors[] = "The passwords do not match."; } if (!$errors) { $stmt = $conn-&gt;prepare("SELECT * FROM users WHERE username=?"); $stmt-&gt;bind_param("s", $_POST['username']); $stmt-&gt;execute(); $row = $stmt-&gt;get_result()-&gt;fetch_assoc(); if ($row &amp;&amp; $row['username'] == $_POST['username']) { $errors[] = "Username exists"; } } if (!$errors) { $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, array('cost' =&gt; 14)); $stmt = $conn-&gt;prepare("INSERT INTO users (username, pw) VALUES(?, ?)"); $stmt-&gt;bind_param("ss", $_POST['username'], $pw ); $stmt-&gt;execute(); echo "Registration successful &lt;a href= index.php&gt;Login here&lt;/a&gt;&lt;br /&gt;"; } else { foreach ($errors as $error) { echo "$error &lt;br /&gt; \n"; } echo '&lt;a href="index.php"&gt;Try again&lt;/a&gt;&lt;br /&gt;'; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:11:14.033", "Id": "476431", "Score": "2", "body": "There is nothing much to review. The code is up to modern security standards. You should just set 'display_errors' to 0 on a live server." } ]
[ { "body": "<p>Some remarks:</p>\n\n<p>You have repetitive code eg:</p>\n\n<pre><code>if (empty($_POST[\"username\"])) {\n</code></pre>\n\n<p>You might as well define an array of fields to check and run validation in a loop.\nAlthough you have only 3 items here...</p>\n\n<p>There is a major <strong>flaw</strong>: you are not <strong>sanitizing</strong> the input fields:</p>\n\n<pre><code>$stmt-&gt;bind_param(\"s\", $_POST['username']);\n</code></pre>\n\n<p>At a minimum you should <strong>trim</strong> the text because it may contains whitespace (before and after). So if user 'admin' is already taken, I can register as 'admin ' for example (one space). That is not necessarily a direct <strong>vulnerability</strong>, it depends on the rest of the code, but you have <strong>inconsistent data</strong> and this will likely cause problems later. Usernames should not contain <s>whitespace</s> leading or trailing whitespace. Because you can have two different accounts the all look the same in print and on screen. That makes impersonation easy.</p>\n\n<p>What you should do is assign the POST fields to variables, and then use variables in the rest of the code, after checking them and sanitizing them. Do not reuse <code>$_POST['whatever']</code> all across your code.</p>\n\n<p>You should also test what happens if the HTTP request is tainted, for example if \n<code>$_POST['username']</code> is included twice in the POST request. Or if the field contains multiline input (or null characters). How will your code react ? Do you have error handling and logging ?</p>\n\n<p>I note that you are not checking the <strong>length of input fields</strong>, including the password. What happens if the text is very large, larger than the corresponding table field ?</p>\n\n<p>You should have a sensible <strong>password policy</strong> and not accept any password like 1234 or same as the username...</p>\n\n<p>What you are showing is the registration form, but what would be interesting to see is the <strong>login page</strong>. That's the thing that should not be easy to trick or bypass.</p>\n\n<p>If you use a modern development framework you can simplify your life, and your code will very probably be more secure.</p>\n\n<p>In my opinion a page that does not have <strong>error handling</strong> is not secure, because you are not seeing what's going on and the code could also behave unpredictably.</p>\n\n<p>Conclusion:</p>\n\n<blockquote>\n <p>If I launched this on the web would you feel safe signing up with\n personal info ?</p>\n</blockquote>\n\n<p>No. There are simply not enough checks. The code is not robust. You should test it in adverse conditions. Try automated tools like SQLmap, Nikto and simulate an attack against yourself.</p>\n\n<p>It is good that you are using parameterized queries, that's the least you could do in 2020. But that does not mean user input does not have to be checked and sanitized. You may be opening your site to other vulnerabilities. What is pretty much guaranteed is that users will use very weak passwords since you are accepting anything. Therefore many accounts will be susceptible to brute force attacks. And you will be blamed for facilitating a breach of personal data.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:34:21.423", "Id": "476447", "Score": "1", "body": "There are good points and bad points. I'll highlight the latter. trim() is anything but a **sanitization**. \"Usernames should not contain whitespace\" is a questionable statement. You probably meant \"leading or trailing whitespace\". By the way, I can register as \"аdmin\" without any whitespace. You said trim is \"minimum\" but didn't venture any further. Make *your own* statements consistent first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:41:28.330", "Id": "476449", "Score": "1", "body": "\"a page that does not have error handling is not secure\" is outright wrong. Having each separate page fumbling with its homebewed error handler IS insecure. An error handler should be centralized and never have any business with other scripts. PHP's default error handler is all right. You cannot tell there is no error handler. It is always there. Check your error log." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:46:46.520", "Id": "476451", "Score": "2", "body": "The overall tone is rather alarming (\"there is no sanitization!\", \"the code is not safe!\") but *without any particular attack vector suggested*. It leaves the OP rather confused than enlightened." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T16:09:01.167", "Id": "476452", "Score": "0", "body": "Some fair points, edit made. To rephrase my statement, judging by the presence of stuff like `ini_set('display_errors', 1);` I think it is safe to assume that the OP is not handling any errors (otherwise logged by PHP) and there is no centralized handling of errors either. For that reason I do not consider the code as 'safe'. Ignoring errors is never good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T16:35:36.183", "Id": "476455", "Score": "1", "body": "To make it clear: Yes. Ignoring errors is never good. It doesn't mean, however, that there should be a single line of (system) error handling code in this script. So we should just tell the op to keep an eye on the error log and may be to think of a custom error handler. But in general error handling is irrelevant to this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T18:36:34.727", "Id": "476462", "Score": "0", "body": "Regarding the possible attack vectors, fair point. I was thinking about **null byte injection**. I am not sure that the `empty` function will always be safe enough. If you provide a null character it seems to return false. POC: `<?php $user=chr(0); var_dump(empty($user)); ?>` Output: `bool(false)`. There are quite a few pitfalls with this function, `0` or `'0'` will also return true which is probably not what the coder had in mind in and may cause problems in some edge cases. What seems evident is that it is possible to insert garbage into the database and that is a warning sign." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T11:12:12.727", "Id": "476797", "Score": "0", "body": "Instead of sanitizing user input, validate it! The backend should just respond with an error when it encounters any unwanted characters (or any other violation), it should not try to remove those characters and treat the remainder as what the client wanted. Maybe the client really wanted whitespace there, now he figures it cannot be done, but he is free to choose completly different username, rather than being registered with a similar username than he wanted, but stripped of whitespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T13:17:24.097", "Id": "476808", "Score": "0", "body": "Valid point, instead of sanitizing silently, explain why the input is not allowed. But there has to be a minimum of validation. From a **design** point of view, a good form should provide some **hints** to the user as to what kind of data is expected/allowed and what is not. For example, password length or complexity. The user should not have to guess.\nMy point is, while the author took care to use parameterized queries and hash passwords, he is allowing garbage into his/her database, and **weak passwords**. So hashing them does not help much. They can be brute-forced." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:19:20.313", "Id": "242759", "ParentId": "242677", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T00:17:50.357", "Id": "242677", "Score": "1", "Tags": [ "php" ], "Title": "How secure is my registration code" }
242677
<p>I have some paths in a list. Here is an example:</p> <pre class="lang-py prettyprint-override"><code>a=["/desktop/folderA/fileA","/desktop/folderA/folderX/file1","/diskKH/folderA/fileA","/desktop/folderB/folderC/fileX"] </code></pre> <p>However I need the output to be in the following form.</p> <pre class="lang-py prettyprint-override"><code>[{ 'name': 'desktop', 'children': [{ 'name': 'folderA', 'children': [{ 'name': 'fileA' }, { 'name': 'folderX', 'children': { 'name': 'file1' } }] }, { 'name': 'folderB', 'children': { 'name': 'folderC', 'children': { 'name': 'fileX' } } }] }, { 'name': 'diskKH', 'children': { 'name': 'folderA', 'children': { 'name': 'fileA' } } }] </code></pre> <p>I have programmed the following to do this.</p> <pre class="lang-py prettyprint-override"><code>import copy def ChageArraryInverted(arrary): dict_1={} for index in range(len(arrary)-1,-1,-1): dict_1["name"]= arrary[index] dict_2=copy.copy(dict_1) dict_1["children"]=dict_2 return dict_1["children"] def GetResArrary(arrary): list_all=[] for item in arrary: item=str(item).split("/")[1::] item=ChageArraryInverted(item) list_all.append(item) print(list_all) return list_all import pysnooper # @pysnooper.snoop() def Merge(dict1, dict2): result = copy.copy(dict1) if isinstance(dict1,dict): if dict1["name"] == dict2["name"]: if 'children' in dict1 and 'children' in dict2: if isinstance(dict1["children"], dict): if dict1['children']['name'] == dict2['children']['name']: result['children'] = [Merge(dict1['children'], dict2['children'])] else: result['children'] = [dict1['children'], dict2['children']] if isinstance(dict1["children"], list): for index in range(0, len(dict1["children"])): if dict1['children'][index]['name'] == dict2['children']['name']: result['children'] = [Merge(dict1['children'][index], dict2['children'])] else: if dict2['children'] not in result['children']: result['children'].append(dict2['children']) elif 'children' in dict1: result['children'] = [dict1['children']] elif 'children' in dict2: result['children'] = [dict2['chidlren']] else: if "children" in result: del result['children'] return result else: result = [result, dict2] return result elif isinstance(dict1,list): for index in range(0,len(dict1)): if dict1[index]["name"] == dict2["name"]: if 'children' in dict1[index] and 'children' in dict2: if isinstance(dict1[index]["children"], dict): if dict1[index]['children']['name'] == dict2['children']['name']: result['children'] = [Merge(dict1[index]['children'], dict2['children'])] else: result['children'] = [dict1[index]['children'], dict2['children']] if isinstance(dict1[index]["children"], list): for index in range(0, len(dict1[index]["children"])): if dict1[index]['children'][index]['name'] == dict2['children']['name']: result['children'] = [Merge(dict1[index]['children'][index], dict2['children'])] else: if dict2['children'] not in result[index]['children']: result[index]['children'].append(dict2['children']) elif 'children' in dict1[index]: result[index]['children'] = [dict1[index]['children']] elif 'children' in dict2: result[index]['children'] = [dict2['chidlren']] else: if "children" in result[index]: del result[index]['children'] return result else: result = [result, dict2] return result def CirArraryToResult(list): re={} for index in range(0,len(list)): if index&lt;len(list)-1: if len(re)==0: re=Merge(list[index],list[index+1]) else: if(index==len(list)-1): return re re=Merge(re,list[index+1]) return re a=["/desktop/folderA/fileA","/desktop/folderA/folderX/file1","/diskKH/folderA/fileA","/desktop/folderB/folderC/fileX"] res=GetResArrary(a) res=CirArraryToResult(res) print("res:",res) </code></pre> <p>I think this can be done better as the code is rather complex. Can the code be improved by using a more efficient algorithm? Any help or optimization ideas are greatly appreciated. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T01:51:23.537", "Id": "476226", "Score": "0", "body": "Should \"'name': 'diskC'\" be \"'name': 'desktop'\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T02:37:11.547", "Id": "476233", "Score": "0", "body": "yes,is desktop 。 。。。" } ]
[ { "body": "<h1>Style</h1>\n\n<ol>\n<li><p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. Much of your code goes against it.</p>\n\n<ul>\n<li>Functions and variables should be <code>lower_snake_case</code>.</li>\n<li>You should have one space around most operators. Commas and brackets are the common exceptions.</li>\n<li>You should have two newlines before and after each top level function.</li>\n<li>All module level Imports should be at the top of the file.</li>\n<li>You should spell things correctly. <code>array</code> not <code>arrary</code>.</li>\n<li>You shouldn't shadow builtins.</li>\n<li>Don't put brackets around if statements.</li>\n</ul>\n\n<p>You can get many tools to check this for you like pycodestyle, Prospector and flake8.\nYou can also get tools to fix this like Black and YAPF.</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import copy\n\nimport pysnooper\n\n\ndef change_array_inverted(array)\n dict_1 = {}\n for index in range(len(array) - 1, -1, -1):\n dict_1[\"name\"] = array[index]\n dict_2 = copy.copy(dict_1)\n dict_1[\"children\"] = dict_2\n return dict_1[\"children\"]\n\n\ndef get_res_array(array):\n list_all = []\n for item in array:\n item = str(item).split(\"/\")[1::]\n item = change_array_inverted(item)\n list_all.append(item)\n print(list_all)\n return list_all\n\n\n# @pysnooper.snoop()\ndef merge(dict1, dict2):\n result = copy.copy(dict1)\n if isinstance(dict1, dict):\n if dict1[\"name\"] == dict2[\"name\"]:\n if 'children' in dict1 and 'children' in dict2:\n if isinstance(dict1[\"children\"], dict):\n if dict1['children']['name'] == dict2['children']['name']:\n result['children'] = [merge(dict1['children'], dict2['children'])]\n else:\n result['children'] = [dict1['children'], dict2['children']]\n if isinstance(dict1[\"children\"], list):\n for index in range(0, len(dict1[\"children\"])):\n if dict1['children'][index]['name'] == dict2['children']['name']:\n result['children'] = [merge(dict1['children'][index], dict2['children'])]\n else:\n if dict2['children'] not in result['children']:\n result['children'].append(dict2['children'])\n elif 'children' in dict1:\n result['children'] = [dict1['children']]\n elif 'children' in dict2:\n result['children'] = [dict2['chidlren']]\n else:\n if \"children\" in result:\n del result['children']\n return result\n else:\n result = [result, dict2]\n return result\n elif isinstance(dict1, list):\n for index in range(0, len(dict1)):\n if dict1[index][\"name\"] == dict2[\"name\"]:\n if 'children' in dict1[index] and 'children' in dict2:\n if isinstance(dict1[index][\"children\"], dict):\n if dict1[index]['children']['name'] == dict2['children']['name']:\n result['children'] = [merge(dict1[index]['children'], dict2['children'])]\n else:\n result['children'] = [dict1[index]['children'], dict2['children']]\n if isinstance(dict1[index][\"children\"], list):\n for index in range(0, len(dict1[index][\"children\"])):\n if dict1[index]['children'][index]['name'] == dict2['children']['name']:\n result['children'] = [merge(dict1[index]['children'][index], dict2['children'])]\n else:\n if dict2['children'] not in result[index]['children']:\n result[index]['children'].append(dict2['children'])\n elif 'children' in dict1[index]:\n result[index]['children'] = [dict1[index]['children']]\n elif 'children' in dict2:\n result[index]['children'] = [dict2['chidlren']]\n else:\n if \"children\" in result[index]:\n del result[index]['children']\n return result\n else:\n result = [result, dict2]\n return result\n\n\ndef cir_array_to_result(array):\n re = {}\n for index in range(0, len(array)):\n if index &lt; len(array) - 1:\n if len(re) == 0:\n re = merge(array[index], array[index+1])\n else:\n if index == len(array) - 1:\n return re\n re = merge(re, array[index+1])\n return re\n\n\na = [\"/desktop/folderA/fileA\", \"/desktop/folderA/folderX/file1\", \"/diskKH/folderA/fileA\", \"/desktop/folderB/folderC/fileX\"]\nres = get_res_array(a)\nres = cir_array_to_result(res)\nprint(\"res:\", res)\n</code></pre>\n\n<h1>Improvements</h1>\n\n<ol start=\"2\">\n<li><p>The code in <code>change_array_inverted</code> is really confusing.</p>\n\n<ol>\n<li>Please don't copy objects when you can just create a new one.\nCopying can add things that are not immediately apparent.</li>\n<li>Rather than building from the bottom up we can build from the top down.\nThis makes the code easier to follow.</li>\n<li>I would change the name of the argument to <code>names</code> as we are being passed a list of names.</li>\n</ol></li>\n<li><p>There are some changes I'd make to <code>get_res_array</code>.</p>\n\n<ol>\n<li>Change the name of the argument to <code>paths</code> as we are being passed paths.</li>\n<li>Use a list comprehension. This is special syntax to make building lists quicker to read and write.</li>\n</ol></li>\n<li><p>There are some changes I would make to <code>cir_array_to_result</code>.</p>\n\n<ol>\n<li>We can remove the <code>if index &lt; len(array) - 1:</code> statement by changing the value we pass to <code>range</code>.</li>\n<li>Rather than having the <code>if index == len(array) - 1:</code> check we can start by assigning <code>re</code> to <code>array[0]</code>.</li>\n</ol></li>\n<li><p>The function <code>merge</code> really needs some love.</p>\n\n<ol>\n<li><p>We need to split the function into two.\nWhenever you think about copying and pasting a block of code you should always think about making a function instead.</p>\n\n<p>The code to handle lists looks like it has some errors in it.</p>\n\n<ol>\n<li>You use <code>result[index]</code> when there are no children in both dict1 or dict2.</li>\n<li>You don't use <code>result[index]</code> when <code>dict1['children']</code> is a dictionary, or the names are not the same.</li>\n<li>You use <code>result[index]</code> when <code>dict1['children']</code> is a list, but you have another loop that changes the value of <code>index</code>.</li>\n</ol>\n\n<p>This smaller function will be called <code>_merge</code> take <code>dict1</code>, <code>dict2</code> and <code>result</code>.</p></li>\n<li>When <code>dict1</code> is a list, if the first dictionary doesn't have the same name as <code>dict2</code> then none of the other dictionaries get checked.\nMove the <code>else: return [result, dict2]</code> outside the loop.</li>\n<li>When <code>dict1['children']</code> is a list you have another issue. If there is more than one child, then <code>dict2</code> is always appended and potentially merged.</li>\n</ol></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import copy\n\nimport pysnooper\n\n\ndef change_array_inverted(names)\n root = item = {}\n for name in names:\n item[\"children\"] = {\"name\": array[index]}\n return root[\"children\"]\n\n\ndef get_res_array(paths):\n return [\n change_array_inverted(str(path).split(\"/\")[1::])\n for path in paths\n ]\n\n\ndef cir_array_to_result(array):\n re = array[0]\n for index in range(1, len(array)):\n re = merge(re, array[index])\n return re\n\n\ndef _merge(lhs, rhs, result):\n if 'children' in lhs and 'children' in rhs:\n if isinstance(lhs[\"children\"], dict):\n if lhs['children']['name'] == rhs['children']['name']:\n result['children'] = [merge(lhs['children'], rhs['children'])]\n else:\n result['children'] = [lhs['children'], rhs['children']]\n if isinstance(lhs[\"children\"], list):\n for index in range(0, len(lhs[\"children\"])):\n if lhs['children'][index]['name'] == rhs['children']['name']:\n result['children'] = [merge(lhs['children'][index], rhs['children'])]\n break\n else:\n if rhs['children'] not in result['children']:\n result['children'].append(rhs['children'])\n elif 'children' in lhs:\n result['children'] = [lhs['children']]\n elif 'children' in rhs:\n result['children'] = [rhs['chidlren']]\n else:\n if \"children\" in result:\n del result['children']\n\n\n# @pysnooper.snoop()\ndef merge(dict1, dict2):\n result = copy.copy(dict1)\n if isinstance(dict1, dict):\n if dict1[\"name\"] == dict2[\"name\"]:\n _merge(dict1, dict2, result)\n return result\n else:\n return [result, dict2]\n elif isinstance(dict1, list):\n for index in range(len(dict1)):\n if dict1[index][\"name\"] == dict2[\"name\"]:\n _merge(dict1[index], dict2, result[index])\n return result\n return [result, dict2]\n\n\na = [\"/desktop/folderA/fileA\", \"/desktop/folderA/folderX/file1\", \"/diskKH/folderA/fileA\", \"/desktop/folderB/folderC/fileX\"]\nres = get_res_array(a)\nres = cir_array_to_result(res)\nprint(\"res:\", res)\n</code></pre>\n\n<p>There are still some other ways to improve the code, but they're starting to get challenging to implement.</p>\n\n<h1>High Level Review</h1>\n\n<p>It's much easier to use dictionaries in a different way.\nBy only taking the folder names as the keys and having them point to child dictionaries we can build a tree.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root = {}\nroot.setdefault('desktop', {}).setdefault('folderA', {}).setdefault('fileA', {})\nprint(root)\n# {'desktop': {'folderA': {'fileA': {}}}}\n\nroot.setdefault('desktop', {}).setdefault('folderA', {}).setdefault('folderX', {}).setdefault('file1', {})\nprint(root)\n# {'desktop': {'folderA': {'fileA': {}, 'folderX': {'file1': {}}}}}\n</code></pre>\n\n<p>Rather than using <code>.setdefault</code> all the time we can instead subclass <code>dict</code> to make it super simple.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class TreeDict(dict):\n def __missing__(self, key):\n self[key] = value = TreeDict()\n return value\n\n\nroot = TreeDict()\nroot['desktop']['folderA']['fileA']\nprint(root)\n# {'desktop': {'folderA': {'fileA': {}}}}\n\nroot['desktop']['folderA']['folderX']['file1']\nprint(root)\n# {'desktop': {'folderA': {'fileA': {}, 'folderX': {'file1': {}}}}}\n\nroot['diskKH']['folderA']['fileA']\nroot['desktop']['folderB']['folderC']['fileX']\n</code></pre>\n\n<p>From this we can then just convert to whatever form you want.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import json\n\n\ndef to_desired(node, name=''):\n result = {'name': name}\n if node:\n children = [\n to_desired(value, key)\n for key, value in node.items()\n ]\n if len(children) == 1:\n children = children[0]\n result['children'] = children\n return result\n\n\nresult = to_desired(root)['children']\nprint(json.dumps(result, indent=4))\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>[\n {\n \"name\": \"desktop\",\n \"children\": [\n {\n \"name\": \"folderA\",\n \"children\": [\n {\n \"name\": \"fileA\"\n },\n {\n \"name\": \"folderX\",\n \"children\": {\n \"name\": \"file1\"\n }\n }\n ]\n },\n {\n \"name\": \"folderB\",\n \"children\": {\n \"name\": \"folderC\",\n \"children\": {\n \"name\": \"fileX\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"diskKH\",\n \"children\": {\n \"name\": \"folderA\",\n \"children\": {\n \"name\": \"fileA\"\n }\n }\n }\n]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:46:11.653", "Id": "476360", "Score": "1", "body": "To make it usable on different OSes, you might want to use `pathlib` or `os.path` rather than `.split('/')`, to get the parts of the path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:48:05.213", "Id": "476361", "Score": "0", "body": "@RootTwo We don't know what type of path it is. It could be a URL path which always uses '/'. Changing to `os.sep`, or `pathlib`, can lead to unforeseen problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T03:31:36.497", "Id": "476366", "Score": "0", "body": "It’s very kind of you,It is very useful。I learned a lot" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T12:34:29.403", "Id": "242695", "ParentId": "242678", "Score": "3" } }, { "body": "<p>The easy way to generate the output in the given format is to build the dynamic tree structure first, to maintain parent and child mappings as a tree. Then we have the structure we can transform the intermediate output to desired output</p>\n\n<pre><code>from collections import defaultdict\n\nall_folders = [\"/desktop/folderA/fileA\", \"/desktop/folderA/folderX/file1\", \"/diskKH/folderA/fileA\",\n \"/desktop/folderB/folderC/fileX\"]\n\n\ndef build_dynamic_trees(list_of_folders):\n tree = lambda: defaultdict(tree)\n root = tree()\n for folders in list_of_folders:\n dynamic_keys = ''\n for folder_name in folders.split(\"/\"):\n if not folder_name:\n continue\n dynamic_keys += \"['{}']\".format(folder_name)\n exec('root' + dynamic_keys + ' = None')\n return root\n\nres = to_desired(build_dynamic_trees(all_folders))['children']\n</code></pre>\n\n<p>As @Peilonrayz mentioned, you can use <code>to_desired</code> method to recursively transform the output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T03:34:58.560", "Id": "476368", "Score": "0", "body": "thank you very much,it is very useful to me。" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:24:17.080", "Id": "476444", "Score": "0", "body": "This is really really not good. you can easily change `dynamic_keys` so you don't you're not building a string to eval, and instead just evaluate the code right there and then. `node = node[folder_name]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:30:28.013", "Id": "476445", "Score": "0", "body": "@Peilonrayz . I'm using 'exec' not 'eval'. Since we have dynamic keys it's also a choice to use for dynamic assignment of the dictionaries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:33:39.580", "Id": "476446", "Score": "0", "body": "@RohithRangaraju That's just pedantry, eval is bad [1](https://stackoverflow.com/q/1832940) [2](https://security.stackexchange.com/q/94017). You can do the exact same thing without it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T16:22:37.687", "Id": "476453", "Score": "0", "body": "@Peilonrayz I agree that it is a not a good practice to use exec or eval but not in the simple dictionary variable assignment, the things you might be talking about is about complex cases. Even though there are security risks involved with exec or eval, I don't see any applicable issues on dictionary assignment. If your saying as a general thumb rule to not use it, then if can you come up with some counter examples to not use for dictionary variable assignment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T16:28:58.613", "Id": "476454", "Score": "0", "body": "Yes. `build_dynamic_trees([\"foo/bar']= print('Uh oh you didn\\\\'t sanatize your input'); root['foo\"])`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T16:38:06.733", "Id": "476456", "Score": "0", "body": "Practically such input at run time it will fail before entering the function. And I don't even need to sanitize the input, python interpreter make sure that such input will never enter the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T19:26:15.990", "Id": "476471", "Score": "0", "body": "@RohithRangaraju No, that's just wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T03:02:02.883", "Id": "476506", "Score": "0", "body": "@Peilonrayz try executing the input which you mentioned in the interpreter, it won't work. I have tried that's why I'm saying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T04:04:19.893", "Id": "476513", "Score": "0", "body": "No, it is vulnerable check this [Repl.it](https://repl.it/repls/MustySympatheticPaintprogram)." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T15:01:09.867", "Id": "242699", "ParentId": "242678", "Score": "2" } } ]
{ "AcceptedAnswerId": "242695", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T01:38:49.350", "Id": "242678", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Merging folder paths into a tree structure" }
242678
<p>From <a href="https://github.com/nishantc1527/Algorithms" rel="nofollow noreferrer">my repository</a>.</p> <p>This is my first time implementing a Fibonacci Heap, and since it's pretty complicated (at least to me), I would like to check if it is all correct.</p> <pre><code>import java.util.HashMap; import java.util.HashSet; import java.util.Objects; public class FibonacciHeap { private final HashMap&lt;Integer, Node&gt; references; private Node min; public FibonacciHeap() { references = new HashMap&lt;&gt;(); } public void insert(int val) { Node newNode = new Node(val); references.put(val, newNode); if (min == null) { min = newNode; min.left = min; min.right = min; } else { min.insert(newNode); if (newNode.val &lt; min.val) { min = newNode; } } } public int extractMin() { int toReturn = min.val; references.remove(toReturn); if (min.left == min &amp;&amp; min.child == null) { min = null; } else { min.safeUnlink(); min = min.left; consolidate(); } return toReturn; } public void delete(int val) { Node nodeForm = references.get(val); nodeForm.val = Integer.MIN_VALUE; min = nodeForm; extractMin(); } public boolean isEmpty() { return min == null; } private void consolidate() { Node[] degrees = new Node[45]; Node dummy = min; HashSet&lt;Node&gt; visited = new HashSet&lt;&gt;(); do { if (visited.contains(dummy)) { break; } if (dummy.val &lt; min.val) { min = dummy; } while (degrees[dummy.degree] != null) { Node other = degrees[dummy.degree]; if (other.val &lt; dummy.val) { Node temp = other; other = dummy; dummy = temp; } dummy.link(other); degrees[dummy.degree - 1] = null; } degrees[dummy.degree] = dummy; visited.add(dummy); dummy = dummy.right; } while (dummy != min); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (min != null) { Node dummy = min; do { sb.append(dummy.val).append(" "); dummy = dummy.right; } while (dummy != min); } return sb.toString(); } private static class Node { public int val; public Node left, right, child; public int degree; public boolean mark; public Node(int _val) { val = _val; } public void insert(Node other) { if (left == this) { left = other; right = other; left.right = this; left.left = this; } else { Node temp = left; left = other; left.right = this; left.left = temp; temp.right = left; } } public void unlink() { left.right = right; right.left = left; } public void safeUnlink() { saveChildren(); unlink(); } public void link(Node other) { other.unlink(); if (child == null) { child = new Node(other.val); child.left = child; child.right = child; } else { child.insert(other); } other.mark = false; degree++; } public void saveChildren() { if (child != null) { Node dummy = child; do { Node tempNext = dummy.right; insert(dummy); dummy = tempNext; } while (dummy != child); child = null; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; return val == node.val &amp;&amp; degree == node.degree &amp;&amp; mark == node.mark &amp;&amp; Objects.equals(left, node.left) &amp;&amp; Objects.equals(right, node.right) &amp;&amp; Objects.equals(child, node.child); } @Override public int hashCode() { return Objects.hash(val); } @Override public String toString() { return val + ""; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T06:52:32.363", "Id": "476249", "Score": "0", "body": "Hello, please add the class `Node` file and your test scenarios." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T07:04:24.917", "Id": "476251", "Score": "0", "body": "Sorry, that part got accidentally cut of." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T04:02:01.697", "Id": "242683", "Score": "2", "Tags": [ "java", "algorithm", "heap" ], "Title": "Fibonacci Heap Implementation In Java" }
242683
<p>I am looking for improvements in the code below which is taking a long time to finish. Initially when I export around 26k+ records, it will take around 20-30 mins to finish. Usually then either the server running out of time, or a DB timeout occurrs. I do realize it is bulky code.</p> <p>The data is populated after <code>if (stockInfoList != null)</code> and at last the entire <code>stockInfoList</code> object is added in <code>sInfo = new ArrayList&lt;StockTransInfo&gt;();</code> </p> <pre><code> ArrayList extlist = new ArrayList(); JSONArray arr = new JSONArray(extlist); JSONObject data = new JSONObject(); JSONObject obj = null; sInfo = new ArrayList&lt;StockTransInfo&gt;(); stockInfoList = new ArrayList&lt;StockTransInfo&gt;(); stockInfoList = stInterface.getStockTransactionInfo( transactionType, product, stockManagementProgram, memberCountries, searchText, dateRange, paging, stockStatus); System.out.println("stockInfoList--"+stockInfoList.size()); PrivilegeInterface privilegeInterface = new PrivilegeDAO(sessionId); List&lt;Status&gt; statusList = privilegeInterface.getStatusList( sessionId, "Transaction"); conversionInformation = new HashMap&lt;String, List&lt;ConvertInfo&gt;&gt;(); outputProgramLevel = new HashMap&lt;String, String&gt;(); StringBuilder sbCertificates = new StringBuilder(); DateUtility dateUtil = new DateUtility(getCoreProductId()); int counter=0; if (stockInfoList != null) { System.out.println("inside stockInfoList--"+stockInfoList.size()); for (StockTransInfo info : stockInfoList) { counter++; obj = new JSONObject(); obj.put("StockTransactionID", info.getStockTransactionId()); obj.put(DATE, info.getCreatedDate() != null ? dateUtil .genericDateFormate(info.getCreatedDate()) : ""); obj.put("MemberId", info.getMemberAccountId()); obj.put("MemberName", info.getMemberAccount()); obj.put("MemberCountry", info.getMemberCountry()); obj.put(PRODUCT, info.getProductName()); obj.put("StockTransactionType", getStockTransactionTypeStatus(info .getStockTransactionType())); JSONArray conv_arr = new JSONArray(extlist); if (info.getStockTransactionType().equalsIgnoreCase("CNV")) { List&lt;ConvertInfo&gt; conversions = stInterface .getConversions(info.getStockTransactionId()); System.out.println(counter+" conversions----"+conversions.size()); List&lt;ConvertInfo&gt; subList_output = new ArrayList&lt;ConvertInfo&gt;(); for (ConvertInfo conv_info : conversions) { JSONObject conv_obj = new JSONObject(); if (conv_info.getProductType().equalsIgnoreCase( "output")) { subList_output.add(conv_info); conv_obj.put("productName", conv_info.getProductName()); conv_obj.put("productVolume", conv_info.getProductDVolume()); conv_obj.put("programName", conv_info.getProgramLevelName()); conv_arr.put(conv_obj); if (!obj.has("outputProgramLevel") &amp;&amp; conv_info.getProgramLevelName() != null) { obj.put("outputProgramLevel", conv_info.getProgramLevelName()); outputProgramLevel.put( info.getStockTransactionId(), conv_info.getProgramLevelName()); } } } if (!subList_output.isEmpty()) conversionInformation.put( info.getStockTransactionId(), subList_output); } obj.put("conversions", conv_arr); obj.put("OriginalVolume", info.getOriginalVolume()); double volume = info.getVolume(); obj.put("TransactionVolume", volume); obj.put("RemainingVolume", info.getRemainingVolume()); obj.put("statusID", info.getStatus()); if ("ADMIN_CORRECTION".equalsIgnoreCase(info.getStatus()) || "CORRECTED_BY_MEMBER".equalsIgnoreCase(info .getStatus())) { for (Iterator&lt;Status&gt; stItr = statusList.iterator(); stItr .hasNext();) { Status sts = (Status) stItr.next(); if (info.getStatus().equalsIgnoreCase( sts.getValueId())) info.setStatus(sts.getValue()); } } if (info.getStockTransactionType().equalsIgnoreCase("RMWH")) { if ("Removed from Warehouse".equalsIgnoreCase(info .getStatus())) { info.setStatus("Warehouse Stock Returned"); } } if (info.getStockTransactionType().equalsIgnoreCase("RWS")) { if ("Removed From Warehouse Stock" .equalsIgnoreCase(info.getStatus())) { info.setStatus("Removed From Warehouse Stock"); } } if (info.getStatus() != null) { obj.put("status", info.getStatus()); } obj.put("status", info.getStatus()); if (!obj.has("outputProgramLevel")) { if(!info.getStockTransactionType().equalsIgnoreCase("STKMGR")) { obj.put("outputProgramLevel", info.getDowngradeProgramName()); outputProgramLevel.put(info.getStockTransactionId(), info.getDowngradeProgramName()); } } Double conversionRatio = 0d; System.out.println(counter+" conversionRatio-----"+conversionRatio); String programName = info.getProgramName(); if (info.getStockTransactionType().equalsIgnoreCase( CreditTradeConstants.CNVCRBK) || info.getStockTransactionType().equalsIgnoreCase( CreditTradeConstants.CNVCRBK_SYSTEM) ) { obj.put(PROGRAM, programName); info.setProgramName(programName); } else { obj.put(PROGRAM, programName); info.setProgramName(programName); } if ((info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCR) || info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCRBK) || info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCRBK_SYSTEM) || info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCR_SYSTEM)) /** Added for OM-3909 */ &amp;&amp; info.getOutPutProductName() != null) { obj.put("allocation", info.getOutPutProductName()); } else { obj.put("allocation", ""); } if (info.getStockTransactionType().equalsIgnoreCase( CreditTradeConstants.CNVCRBK) || info.getStockTransactionType().equalsIgnoreCase( CreditTradeConstants.CNVCRBK_SYSTEM) ) { sbCertificates.setLength(0); if (volume != 0) { conversionRatio = commonUtility .formatDecimalsDisplay(info .getConvertedCertificates() / volume); } obj.put("outputProgramLevel", programName); outputProgramLevel.put(info.getStockTransactionId(), programName); setOutputProgram(programName); obj.put("OriginalVolume", info.getOriginalVolume()); Double transactionVolume = commonUtility.performOpsOnDoubleValuesAsBigDecimals(info.getRemainingVolume(), info.getOriginalVolume(),"subtract"); sbCertificates.append("&lt;span style=\"" + AppConstants.LEGENDS_CERTIFICATE_COLOR + "\"&gt;&lt;b&gt;" + dateUtil.seprateVolume( info.getConvertedCertificates(), locale.ENGLISH) + "&lt;/b&gt;&lt;/span&gt;"); obj.put("TransactionVolume", sbCertificates.toString()); info.setVolumeStr(sbCertificates.toString()); obj.put("RemainingVolume", info.getRemainingVolume()); obj.put("allocationTransaction", transactionVolume); info.setOutPutVolumeStr(String.valueOf(transactionVolume)); } if (info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCR) || info.getStockTransactionType().equalsIgnoreCase(CreditTradeConstants.CNVCR_SYSTEM)) /** Added for OM-3909 */ { sbCertificates.setLength(0); conversionRatio = 0d; if (volume != 0) { conversionRatio = commonUtility .formatDecimalsDisplay(info .getConvertedCertificates() / volume); } sbCertificates.append("&lt;span style=\"" + AppConstants.LEGENDS_CERTIFICATE_COLOR + "\"&gt;&lt;b&gt;" + dateUtil.seprateVolume( info.getConvertedCertificates(), locale.ENGLISH) + "&lt;/b&gt;&lt;/span&gt;"); obj.put("allocationTransaction", sbCertificates.toString()); info.setOutPutVolumeStr(sbCertificates.toString()); obj.put("outputProgramLevel", info.getDowngradeProgramName()); outputProgramLevel .put(info.getStockTransactionId(), info.getDowngradeProgramName()); } System.out.println(counter+" StockTransactionTypeId------"+info.getStockTransactionType()); obj.put("StockTransactionTypeId", info.getStockTransactionType()); obj.put("adminFee", info.getAdminFee() &gt; 0 ? info.getAdminFee() : ""); obj.put("transactionFee", info.getTransactionFee() &gt; 0 ? info .getTransactionFee() : ""); String operatingholdingNameLink = null; if (info.getHoldingName() != null &amp;&amp; info.getHoldingName() != "") { operatingholdingNameLink = "&lt;a href=javascript:viewHoldingDetailsWindow(\'" + info.getHoldingId() + "\','readOnly')&gt;" + info.getHoldingName() + "&lt;/a&gt;"; } else { operatingholdingNameLink = ""; } obj.put("holdingName", operatingholdingNameLink); obj.put("Action", ""); if (info.getLicenseID() != null) { info.setLicense(info.getLicenseID()+" ("+info.getLicenseStatus()+")"); obj.put("License", getLicenseHyperLink(info.getLicenseID(),getCoreProductId(),info.getLicenseStatus())); }else{ info.setLicense(""); obj.put("License", ""); } arr.put(obj); count = info.getTotalCount(); System.out.println("info.getTotalCount()---"+ info.getTotalCount()); sInfo.add(info); } System.out.println("Counter---"+ counter); System.out.println("items added in sInfo"); } } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } </code></pre> <p><strong>Please Note:</strong> The <code>counter</code> variable is added by me to trace whether the execution is stuck in middle or not.</p> <p>Kindly help me to refactoring and possible optimization required to improve the performance of the above code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T13:45:24.203", "Id": "476279", "Score": "2", "body": "Please explain what the code does in the body of the question. Have you tried profiling the code. Where is the beginning and end of the function? Does this belong to a class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:11:01.413", "Id": "476375", "Score": "0", "body": "It is belong to class and it is defined in execute() method, It is Struts Action Class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:12:49.770", "Id": "476376", "Score": "0", "body": "Code profiling is quite new term for me, I have researched bit about over the internet, but still require proficiency in this technique to proceed further" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T04:26:21.803", "Id": "478111", "Score": "0", "body": "Please show off of the method the code presented in the initial revision of your question is part of. And motivate *how* `performance` came to be an issue." } ]
[ { "body": "<p>There's a lot of things that are ... quite suboptimal in this code. Let's start with the easy and obvious ones:</p>\n\n<h3>The naming scheme and bracing style is a bit of a mess</h3>\n\n<p>The following names are bordering on meaninglessness. When naming variables you should strive to imbue them with semantic information that helps the reader understand the thought process and the surrounding context.</p>\n\n<p><code>extlist</code>, <code>arr</code>, <code>data</code>, <code>obj</code>, <code>counter</code> and similar variables do <strong>nothing</strong> to illuminate the context of the code. That costs time and mental resources when reading the code.</p>\n\n<p><code>conv_obj</code>, <code>conv_arr</code> and <code>subList_output</code> should not be named with underscores in the names, since there's no java style guide recommending snake_case for the variables.</p>\n\n<p>In addition, there are at least two if-blocks that do not have braces around the block and at least one \"double if-block\" that should be merged into a single one.<br>\nSpeaking overall, the formatting seems to be constrained to some arbitrary number of columns, which I found to be somewhat ... hard to read. </p>\n\n<h3>Serialization shouldn't be manual work</h3>\n\n<p>What you have here is the serialization of data into a JSON object that you do <strong>manually</strong>. In general you'd want to not do that.</p>\n\n<p>In the ideal case you'd be able to leave the JSON serialization to a renderer that follows in your usual action chain. That <strong>should</strong> allow you to cut out all of the rendering code for JSON interacting with JSONArray, JSONObject and all the other related classes.</p>\n\n<p>Unfortunately it's impossible to see from the code you presented, how your environment is set up, so I can't really give you any hints on how to achieve that.</p>\n\n<h3>Avoid System.out.println</h3>\n\n<p>System.out.println is not a replacement for proper logging and you can expect it to cost you quite some runtime if you use it inside a loop or on a hotpath because it's not really optimized (and shouldn't be).</p>\n\n<p>If you want debug information, use a debugger. If you want to retrace an execution after it's taken place, either use logging or use an observability provider and instrument your code with that.<br>\nSystem.out is <strong>not</strong> intended for either of these things, so don't use it like that.</p>\n\n<h3>Unused, overscoped and wrongly used variables and language constructs</h3>\n\n<ul>\n<li><code>extlist</code> is only ever used to initialize JSONArray instances. Instead of calling the JSONArray constructor taking a list as argument, you should just use the no-argument constructor and remove <code>extlist</code>.</li>\n<li><code>data</code> is <strong>never used</strong> in the code you show here. Remove it.</li>\n<li><code>obj</code> doesn't need to be created outside of the if-block. Push it inside the block because it's not used outside.</li>\n<li><code>stockInfoList</code> does not need to be initialized before directly being overwritten again. Remove <code>stockInfoList = new ArrayList&lt;StockTransInfo&gt;();</code>.</li>\n<li><code>privilegeInterface</code> can be inlined because it's only ever used to get the status list. That statusList is only used when the info status is <code>ADMIN_CORRECTION</code> or <code>CORRECTED_BY_MEMBER</code>. You subsequently check whether the status is in the <code>statusList</code> <strong>just</strong> to put the status object's correct casing <strong>back into the <code>info</code> object</strong>. In 99.9% of the cases this <strong>SHOULD NOT ACCOMPLISH ANYTHING</strong>.</li>\n<li><p>The <code>sbCertificates</code> String is only ever used directly after being cleared and then set once. It's never used to actually build a string and should be replaced by:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String cert = String.format(\"&lt;span style=\\\"%s\\\"&gt;&lt;b&gt;%s&lt;/b&gt;&lt;/span&gt;\",\n AppConstants.LEGENDS_CERTIFICATE_COLOR, dateUtil.seprateVolume(\n info.getConvertedCertificates(), locale.ENGLISH));\nobj.put(\"TransactionVolume\", cert);\ninfo.setVolumeStr(cert);\n</code></pre></li>\n<li><p>While we're here: <code>seprateVolume</code> should probably be <code>separateVolume</code>?</p></li>\n<li><p>There's at least one if-statement where the corresponding else-statement does <strong>EXACTLY THE SAME</strong>, making the distinction utterly meaningless.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (info.getStockTransactionType().equalsIgnoreCase(\n CreditTradeConstants.CNVCRBK)\n || info.getStockTransactionType().equalsIgnoreCase(\n CreditTradeConstants.CNVCRBK_SYSTEM) ) {\n obj.put(PROGRAM, programName);\n info.setProgramName(programName);\n} else {\n obj.put(PROGRAM, programName);\n info.setProgramName(programName);\n}\n</code></pre></li>\n<li>The <code>counter</code> variable is only ever used in System.out calls. I don't see it adding much value at all, since it won't allow identifying a transaction, as such it should just be removed along with all the System.out calls. If you want to diagnose the code in production, use the StockTransactionId to identify a transaction.</li>\n<li>The <code>if (info.getStatus() != null)</code> block is completely useless, just remove it.</li>\n<li>While <code>conversionRatio</code> is written to multiple times, it's only read in a System.out call directly after it's initialization, making it a pointless exercise.</li>\n</ul>\n\n<h3>I'm tired.</h3>\n\n<p>I'm really tired by this code.<br>\nWhat this code needs is a good scrubbing and cleanup around removing things that are never used or used in ways that don't actually make an impact.</p>\n\n<p>After that you need to find a way to separate display logic from business logic. It doesn't seem viable to generate html inside an Action to put into a JSON object as a string. That's something for the frontend to do.</p>\n\n<p>When all of that is done, the next thing is taking a good hard look at your domain model and identifying places where you can take advantage of a strongly typed language. The obvious example I can see is the <code>stockTransactionType</code>. There's a variety of types you handle, but they are always mutually exclusive and there only exists a finite number of them. From what I can see, they should be represented by an <code>enum</code> and not a <code>String</code>. A sideeffect of that would be a significant increase in speed when checking which transactionType you're currently dealing with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:31:46.577", "Id": "243336", "ParentId": "242687", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T07:18:49.777", "Id": "242687", "Score": "1", "Tags": [ "java", "performance" ], "Title": "Exporting Stock Transaction Data to Excel" }
242687
<p>I write an hobbyist application that collects soccer-data from different sources around the www and aggregates it for a graphical representation and sends it out as a tweet. Now I want to fully automate this process in a more or less robust way (more or less because 1. this is a hobby and 2. depends on scraped 3rd party websites).</p> <p>I have problems to wrap my head around how this full automation can be organized. The following tasks need to be done:</p> <ol> <li>check once daily if and when there are soccer matches I am interested in</li> <li>start collecting data of these matches from all sources as soon as match is over</li> <li>retry collecting data every x minutes if it wasn't available yet (the sources have very different speed in releasing the data and it may take 24hrs. sometimes)</li> <li>as soon as all sources have been collected successfully launch aggregation and tweet. </li> </ol> <p>My question:<br> I don't know how to implement the connection between 3. and 4. in a good way. I think I need some wrapper which is called by the scheduler as soon as a match is over, but this doesn't seem to be a robust way:</p> <pre><code>class MatchCollector: def __init__(self,teams,sources=settings.sources): self.teams=teams self.sources = sources def execute(self): finished = False counter = 0 while not finished: finished = True for source in self.sources: s = SourceCollector(source,self.teams) successful = s.execute() if not successful: finished = False time.sleep(600) counter += counter if counter == 10000 # arbitrary chosen, have to make calc, when would be a good point to give up raise IterationException('Tried for x hours without success. Somethings broken') d = DataAggregator(sources) d.execute() </code></pre> <p>Am I missing something problematic, by doing this?</p> <p>I arrange daily scheduling (1., 2.) via cron and python-crontab in a scheduling script. It is started once daily and reads the daily matches and writes again into cron the script to handle the single matches with arguments passed via sys.argv. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T10:54:27.290", "Id": "476264", "Score": "1", "body": "If you already have a working first stab at a solution, please present it above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T12:33:41.593", "Id": "476273", "Score": "0", "body": "I honestly think, I did this. What part of the code are you missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T13:34:59.650", "Id": "476278", "Score": "1", "body": "Does the code you present include the wrapper you mention in your question? This site is called Code Review, we look at the code and suggest improvements for the code, we can't help you write code that is not written. Please see our guidelines at https://codereview.stackexchange.com/help/asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:27:35.360", "Id": "476321", "Score": "1", "body": "@pacmaninbw Yes, this is what I called \"wrapper\". As I'm self teaching coding, maybe that was not a correct terminus. But I meant the class which I showed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:39:23.110", "Id": "476339", "Score": "0", "body": "I don't find `once daily` (argued to be not part of \"this\", but some `scheduler `?), `connection between 3. and 4.`. I see a) `retry`. I have no idea regarding `if and when there are soccer matches…`, `all sources`, `as soon as match is over` - or what the doubling of `counter` is intended to be good for. `launch aggregation and tweet` is pretty well hidden in what seems to be one instantiation and one method invocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:33:39.430", "Id": "476379", "Score": "1", "body": "@greybeard So I should show the whole code and not just the part I feel unsure about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:46:58.720", "Id": "476393", "Score": "0", "body": "Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers). Your first edit invalidated (a part of) the answer I gave. If you want to, you can always [ask] a new question with updated code, or just fix the bug in your code on your machine and leave it as is here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:48:38.500", "Id": "476396", "Score": "0", "body": "@Graipher: Ok, sorry. I changed it, because greybeard was referring to it as \"not understandable\". So i wanted to clarify my code. (And mentioned the editing below)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:49:51.230", "Id": "476398", "Score": "3", "body": "@J_Scholz: Yeah, that is a bit unfortunate. If I had found that problem before I had almost finished writing my answer, I probably would have just left a comment instead at first, so you would have been free to fix it." } ]
[ { "body": "<p>Well, whatever you do, you should only re-check those sources which have not finished, so you should remember which have finished already, or equivalently, only those which have not. </p>\n\n<pre><code>class MatchCollector:\n def __init__(self, teams, sources=settings.sources):\n self.teams = teams\n self.sources = sources\n self.unfinished = {SourceCollector(source, teams) for source in sources}\n self.timeout = 600 # s\n self.iterations = 1000 # arbitrarily chosen, have to make calc, when would be a good point to give up\n\n def execute(self):\n counter = 0\n while self.unfinished:\n self.unfinished = {source for source in self.unfinished if not s.execute()}\n time.sleep(self.timeout)\n counter += 1\n if counter &gt;= self.iterations \n raise IterationException('Tried for x hours without success. Somethings broken') \n d = DataAggregator(self.sources)\n d.execute()\n</code></pre>\n\n<p>This assumes that <code>SourceCollector.execute</code> can be run repeatedly without needing to re-initialize it. If this is not the case, just do <code>self.unfinished = {source for source in self.unfinished if not SourceCollector(source, self.teams).execute()}</code>.</p>\n\n<p>Note that doing <code>counter += counter</code> is probably not what you want. Since you initialize it to <code>0</code>, it does <code>0 + 0 = 0</code>, so nothing. If you had initialized it to a non-zero value, it would also not simply count up, but double every iteration.</p>\n\n<p>I also made the timeout between retries and the number of iterations members of the class so they are no longer magic numbers.</p>\n\n<p>You should also follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using spaces around <code>=</code> in assignments and after commas in argument lists of functions and methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:46:20.960", "Id": "476392", "Score": "0", "body": "Yes, should have been counter += 1, this was a mistake from the hurry I was typing. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:48:20.360", "Id": "476395", "Score": "0", "body": "@J_Scholz: Sorry, but I rolled back that edit (but added back the text you made in your next edit) , since it invalidated parts of my answer. See the link I posted above for more explanation on what you can and cannot do here after having received an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:06:30.797", "Id": "476401", "Score": "0", "body": "I think self.unfinished should be a list-, not a dict-comprehension?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:08:10.270", "Id": "476402", "Score": "1", "body": "@J_Scholz: A list comprehension would also work, but it is a set comprehension here, not a dict comprehension. I had originally wanted to use `set.add` and `set.remove`, which are faster for sets than lists, especially the latter if the element is not at the end of the list. As long as your class is hashable (which it is by default), a set will work just as well here, except that the order in which you try the sources may not always be the same." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T09:17:51.937", "Id": "242690", "ParentId": "242689", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T08:59:35.527", "Id": "242689", "Score": "1", "Tags": [ "python", "scheduled-tasks" ], "Title": "Start task as soon as multiple tasks are successful" }
242689
<p>Description: The web server retrieves data from file database (pdf, doc, 3d file, zip and rar) and financial program such as inventory, price, indexes, order status and so on. <a href="https://i.stack.imgur.com/EypXE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EypXE.jpg" alt="Communication diagram"></a></p> <p>I'm doing REST API PHP for the first time, I've never used this API with PHP, I am an absolute beginner to REST.</p> <p>Code returns data to cooperate with a www site.</p> <p>First, I will test for a product that exists.</p> <p><strong>Output code 200:</strong><code>get_id2.php?id=39</code></p> <pre><code>id "39" caption "product01" filename "http://localhost/photo_gallery/public/files/images/image01.jpg" description "testing Api" </code></pre> <p>Next, I will test for a product that does not exist.</p> <p><strong>Output code 404:</strong><code>get_id2.php?id=99999</code></p> <pre><code>message "No product." </code></pre> <p>I need your opinions.</p> <ol> <li>Are there any code smells (can it be done better)?</li> <li>Better to use prepared statement or not?</li> <li>Use htmlspecialchars and urlencode for output?</li> <li>What is good practice for REST API (PHP)?</li> </ol> <p>Thank you in advance for your opinion.</p> <p><strong>File: get_id2.php</strong> </p> <pre><code>header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: access"); header("Access-Control-Allow-Methods: GET"); header("Access-Control-Allow-Credentials: true"); header("Content-Type: application/json; charset=UTF-8"); include_once('config_setup.php'); //$id = $_GET['id']; $id = isset($_GET['id']) ? $_GET['id'] : die(); $sql = "SELECT * "; $sql .= "FROM photographs "; $sql .= "WHERE id='" . db_escape($db, $id) . "'"; $result = mysqli_query($db, $sql); confirm_db_connect($result); $url = 'http://localhost/photo_gallery/public/files/images/'; $allowed_tags = '&lt;div&gt;&lt;img&gt;&lt;h1&gt;&lt;h2&gt;&lt;p&gt;&lt;br&gt;&lt;strong&gt;&lt;em&gt;&lt;ul&gt;&lt;li&gt;&lt;table&gt;&lt;td&gt;&lt;tr&gt;&lt;th&gt;&lt;tbody&gt;'; $photo = mysqli_fetch_assoc($result); $id = $photo['id']; $caption = $photo['caption']; $filename = $photo['filename']; $description2 = $photo['description2']; if ($photo['caption'] != null) { // create array $product_arr = array( "id" =&gt; u(h($id)), "caption" =&gt; h($caption), "filename" =&gt; $url . h($filename), "description2" =&gt; strip_tags($description2, $allowed_tags) ); // set response code - 200 OK http_response_code(200); echo json_encode( $product_arr ); } else { // set response code - 404 Not found http_response_code(404); // tell the user product does not exist echo json_encode(array("message" =&gt; "No product.")); } mysqli_free_result($result); db_disconnect($db); </code></pre> <p><strong>Functions</strong></p> <pre><code>function h($string="") { return htmlspecialchars($string); } function u($string="") { return urlencode($string); } function confirm_result_set($result_set) { if (!$result_set) { exit("Database query failed."); } } function db_escape($connection, $string) { return mysqli_real_escape_string($connection, $string); } function db_disconnect($connection) { if(isset($connection)) { mysqli_close($connection); } } </code></pre>
[]
[ { "body": "<ul>\n<li><code>get_id2.php</code> is expected to produce a json string, so make sure that it always does that.</li>\n<li>Don't use <code>die()</code> because then you are not providing an informative json response.</li>\n<li>Don't be too informative when the expected id is missing or invald -- be clear about the problem, but also vague.</li>\n<li>Validate the incoming <code>id</code> using <code>isset()</code> then <code>ctype_digit()</code>, if it passes those checks, then your script may advance to the querying step.</li>\n<li>I prefer object-oriented mysqli syntax since it is less verbose, but you can keep using procedural if you like.</li>\n<li>Calling <code>confirm_db_connect($result);</code> after executing the query doesn't make any sense. If you are going to bother checking the connection, you should be doing that before trying to execute the query.</li>\n<li>You only need four columns in your result set, so I advise that you list those columns explicitly in your SELECT clause so that you don't ask for more than you need.</li>\n<li><p>I don't see any value in declaring single use variables from the result set.</p>\n\n<pre><code>$id = $photo['id'];\n$caption = $photo['caption'];\n$filename = $photo['filename'];\n$description2 = $photo['description2'];\n</code></pre>\n\n<p>Just use the <code>$photo[...]</code> variables directly when sanitizing/preparing the data.</p></li>\n<li>Those single character sanitizing/preparing functions are a bad idea. Developers that need to read your script in the future (including yourself) will have no chances of instantly understanding what these calls do. This will require manually jumping to another file to look up what action is being executed. Use more meaningful function names and don't try to save characters at the cost of losing comprehensibility. In fact, it only hurts your code to write a custom function that replaces a single native function call -- just use the native call and your script and developers will be happier.</li>\n<li><p>As of PHP7.4, <code>strip_tags()</code> allows an alternative declaration of allowed tags. So your second parameter could look like this:</p>\n\n<pre><code>['div', 'img', 'h1', 'h2', 'p', 'br', 'strong', 'em', 'ul', 'li', 'table', 'td', 'tr', 'th', 'tbody']\n</code></pre>\n\n<p>Admittedly, when using proper spacing between values, the expression ends up being longer; but it can be sensibly broken into multiple lines to reduce overall width.</p></li>\n<li>I prefer to write the negative response before the positive responses in my projects for consistency. This just means moving the <code>No product.</code> outcome earlier in the code.</li>\n<li>It is not necessary to manually free the result nor close the db connection when this script resolves; php will do this clean up for you automatically.</li>\n<li>write <code>json_encode()</code> just once and pass a variable to it -- for the sake of DRY-ness.</li>\n</ul>\n\n<p>My untested suggestions:</p>\n\n<pre><code>header(\"Access-Control-Allow-Origin: *\");\nheader(\"Access-Control-Allow-Headers: access\");\nheader(\"Access-Control-Allow-Methods: GET\");\nheader(\"Access-Control-Allow-Credentials: true\");\nheader(\"Content-Type: application/json; charset=UTF-8\");\n\nif (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {\n $response = ['message' =&gt; 'Missing/Invalid identifier provided'];\n} else { \n include_once('config_setup.php');\n $sql = \"SELECT id, caption, filename, description2 FROM photographs WHERE id = \" . $_GET['id'];\n $result = mysqli_query($db, $sql);\n if (!$result) {\n $response = ['message' =&gt; 'Please contact the dev team.'];\n } else {\n $photo = mysqli_fetch_assoc($result);\n if (!$photo) {\n $response = ['message' =&gt; 'No product.'];\n } else {\n $url = 'http://localhost/photo_gallery/public/files/images/';\n $allowed = '&lt;div&gt;&lt;img&gt;&lt;h1&gt;&lt;h2&gt;&lt;p&gt;&lt;br&gt;&lt;strong&gt;&lt;em&gt;&lt;ul&gt;&lt;li&gt;&lt;table&gt;&lt;td&gt;&lt;tr&gt;&lt;th&gt;&lt;tbody&gt;';\n $response = [\n 'id' =&gt; urlencode(htmlspecialchars($photo['id'])),\n 'caption' =&gt; htmlspecialchars($photo['caption']),\n 'filename' =&gt; $url . htmlspecialchars($photo['filename']),\n 'description2' =&gt; strip_tags($photo['description2'], $allowed),\n ];\n }\n }\n}\n\nhttp_response_code(isset($response['message']) ? 404 : 200);\necho json_encode($response);\n</code></pre>\n\n<p>Granted, some developers will not wish to write three nested condition blocks and might prefer to write early json exits. I am choosing not to do this because my script is not excessively wide and it makes only one call of <code>http_response_code()</code> and <code>json_encode()</code> at the end. \"To each their own.\" Restructure the snippet however you like.</p>\n\n<p>An alternative structure with multiple returns to avoid arrowhead code:</p>\n\n<pre><code>function getResponse() {\n if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {\n return ['message' =&gt; 'Missing/Invalid identifier provided'];\n }\n include_once('config_setup.php');\n $sql = \"SELECT id, caption, filename, description2 FROM photographs WHERE id = \" . $_GET['id'];\n $result = mysqli_query($db, $sql);\n if (!$result) {\n return ['message' =&gt; 'Please contact the dev team.'];\n }\n $photo = mysqli_fetch_assoc($result);\n if (!$photo) {\n return ['message' =&gt; 'No product.'];\n }\n $url = 'http://localhost/photo_gallery/public/files/images/';\n $allowed = '&lt;div&gt;&lt;img&gt;&lt;h1&gt;&lt;h2&gt;&lt;p&gt;&lt;br&gt;&lt;strong&gt;&lt;em&gt;&lt;ul&gt;&lt;li&gt;&lt;table&gt;&lt;td&gt;&lt;tr&gt;&lt;th&gt;&lt;tbody&gt;';\n return [\n 'id' =&gt; urlencode(htmlspecialchars($photo['id'])),\n 'caption' =&gt; htmlspecialchars($photo['caption']),\n 'filename' =&gt; $url . htmlspecialchars($photo['filename']),\n 'description2' =&gt; strip_tags($photo['description2'], $allowed),\n ];\n}\n\n$response = getResponse();\nhttp_response_code(isset($response['message']) ? 404 : 200);\necho json_encode($response);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:38:35.683", "Id": "476546", "Score": "0", "body": "What about putting the whole code into a function and `return` when you're done? That avoids the deeply nested conditions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:40:02.010", "Id": "476547", "Score": "0", "body": "Sure, I could just as easily support a `return` based approach. https://3v4l.org/g9V0T My current boss actually doesn't like multiple `return`s in a function; I must say I prefer them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T23:37:11.497", "Id": "476582", "Score": "0", "body": "I like returns based approach too, although i often use multiple returns as guard clauses at the start of the function, but if i end up putting returns all over the place, the chances are the function could be refactored into multiple functions or simplified in other ways" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T00:18:27.070", "Id": "476583", "Score": "1", "body": "I think my employer's stance is about speed of readability. The argument being that it is simpler for the human eye to follow indentation versus colored `return`s (amidst all other syntax which is colored by the IDE). Again, I am happy to adapt my code writing style to conform with specific projects or company/team policy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T00:28:22.960", "Id": "476584", "Score": "0", "body": "The same can be said regarding my decision to not implement a prepared statement. The incoming value is suitably validated as an integer before being injected into the sql string. It isn't necessary, but if the project is using prepared statements for 100% of the db interactions, then I am happy to endorse conformity/consistency and implement a prepared statement." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T00:55:34.777", "Id": "242782", "ParentId": "242694", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T12:11:29.667", "Id": "242694", "Score": "0", "Tags": [ "php", "json" ], "Title": "REST API PHP find by id" }
242694
<p>A section of my page lists 'Workshops' and just uses objects from a queryset. The page/site uses bootstrap.</p> <pre><code>&lt;div class="row my-4"&gt; &lt;div class="container"&gt; {% if workshops|length %} &lt;div class="row"&gt; &lt;h3 class="text-uppercase font-weight-bolder font-title ml-4"&gt;Learn through workshops&lt;/h3&gt; &lt;/div&gt; &lt;div class="row"&gt; {% for workshop in workshops %} &lt;style&gt; #workshop-cover { max-width: {{ workshop.cover_max_width }}px; } &lt;/style&gt; &lt;div class="col-xs-12 col-sm-5 col-lg-4"&gt; &lt;div class="mb-5 mt-5"&gt; &lt;div class="container" style="position:relative"&gt; &lt;div class="row"&gt; &lt;div&gt; &lt;a href="{{ workshop.url }}" target="_blank" style="text-decoration:none;"&gt; &lt;img id="workshop-cover" src="{{ MEDIA_URL }}{{ workshop.cover }}" alt="Workshop cover" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;div style="position:absolute;left:13.9rem;top:8rem;"&gt; &lt;a href="/{{ workshop.speaker.handle }}"&gt; &lt;img class="speaker-avatar float-right" src="{{ workshop.speaker.avatar_url }}" alt="{{ workshop.speaker.handle }}'s Avatar or Logo" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-8"&gt; &lt;a href="{{ workshop.url }}" target="_blank" style="text-decoration:none;"&gt; &lt;span class="font-weight-bold d-flex font-title mt-1 mb-1" style="color:black;"&gt;{{ workshop.name }}&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div class="small"&gt;in {{ workshop.start_date|timeuntil }}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endif %} &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://i.stack.imgur.com/btNez.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/btNez.png" alt="enter image description here"></a></p> <p>In particular, I am wondering two things:</p> <p>In order to show the 'speaker avatar' in the position I wanted, I just used a <code>position: relative</code> container in which I put the 'cover' and the avtar and set the div for the avatar as <code>absolute</code>. I want to know if there is a better to way to accomplish what I want.</p> <p>Second, I needed the workshop title to wrap so it does not get hidden by the 'speaker avatar', but after some 'playing around' I just put it in a <code>col-8</code> (boostrap) <code>div</code>. I am wondering about a better to handle wraping the title? What rearranging would I need to do if any to accomplish that?</p> <p>Lastly, any advice on how to make this cleaner both structurally or syntactically would be welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T14:18:22.893", "Id": "242698", "Score": "2", "Tags": [ "twitter-bootstrap", "django-template-language" ], "Title": "Displaying workshops on a page" }
242698
<p>This defaults to user input if the arguments are not passed at compile time.. How effective is this technique and where can it be applied?</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #include &lt;iostream&gt; void foo(unsigned number = []() {unsigned num = 0; std::cin &gt;&gt; num; return num; } ()) { std::cout &lt;&lt; number &lt;&lt; "\n"; } int main() { foo(1); //prints 1 foo(); //defaults to user input return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T15:50:35.580", "Id": "476302", "Score": "0", "body": "There's a problem with your `main` function parameter definition,, fix that please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:12:43.230", "Id": "476316", "Score": "0", "body": "I do not see much benefit of this other than code being closer to the call site. Perhaps you could create more complex and concrete example that would better illustrate the advantages?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:13:27.330", "Id": "476317", "Score": "0", "body": "That's what I am asking for XD. Can you think of any?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:45:59.560", "Id": "476340", "Score": "0", "body": "This does not look [actual code from one of your projects](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T21:05:43.703", "Id": "476345", "Score": "0", "body": "@greybeard, It isn't and I'm really sorry for that. But I wanted to know the implications of the code if I use it in my project. I know I've violated the guideline and should be 'fined' for that. I will be fine with it, even if you vote to close this question (which I guess you probably have). P.S. I will refrain from such questions in the future :)" } ]
[ { "body": "<p>I haven't seen this pattern in use, and I wouldn't use it personally, for two reasons:</p>\n\n<p>1) Unintuitive - Changing the function's behavior in this significant of a way is not something you'd expect from the default value of a parameter.</p>\n\n<p>2) Mixing Concerns - It's almost always better to separate your I/O from your algorithm.</p>\n\n<p>Considering that this is a compile-time difference anyway, it would be more clear to have another method to read input. For example:</p>\n\n<pre><code>foo(1);\nfoo(foo_input());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:55:40.200", "Id": "476326", "Score": "0", "body": "Please don't take the code literally. I wanted to focus on the part wherein default arguments are user input. The definition may be different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:58:46.897", "Id": "476327", "Score": "0", "body": "Gotcha. In that case, point 2 applies even more-so." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:45:12.683", "Id": "242712", "ParentId": "242702", "Score": "3" } } ]
{ "AcceptedAnswerId": "242712", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T15:44:20.150", "Id": "242702", "Score": "1", "Tags": [ "c++" ], "Title": "How effective is it to default to user input in C++ function parameters?" }
242702
<p>Now implemented changes suggested in my previous post and now am back again for the internet to tear me and my shitty code down. </p> <p>PatchNotes Extracted templateRetriever class from the email service thus making it a little smaller. Put the email bodyTEXT in embedded HTML file so the program is more future proof. Change method name of ReadFully to StreamToByteArray to be clearer Removed duplicate code from AddRecipients</p> <p>Did not remove return type to void as this would make it harder to use the method for others, and think it is more readable to return it. Please tell me if this is an anti-pattern/bad practice </p> <p>Old post: <a href="https://codereview.stackexchange.com/questions/242562/email-service-sending-an-email-with-azure-blob-storage/242578?noredirect=1#comment476141_242578">Email Service - Sending an email with azure blob storage</a></p> <pre><code> /// &lt;summary&gt; Handles emails using Office365 &lt;/summary&gt; public class EmailService : IEmailService { private readonly IBlobStorageService _blobStorageService; private readonly EmailSettings _emailSettings; public EmailService(IBlobStorageService blobStorageService, EmailSettings emailSettings) { _emailSettings = emailSettings ?? throw new ArgumentNullException("Email configuration cannot be null."); _blobStorageService = blobStorageService; } /// &lt;summary&gt; Sends an email using Office365 with the credentials specified in configuration. &lt;/summary&gt; /// &lt;param name="motionActivity"&gt;&lt;/param&gt; /// &lt;param name="mediaResults"&gt;&lt;/param&gt; /// &lt;returns&gt; true or false &lt;/returns&gt; /// &lt;exception cref="ArgumentException"&gt;&lt;/exception&gt; public async Task&lt;bool&gt; SendEmail(MotionActivity motionActivity, List&lt;MediaAnalysis&gt; mediaResults) { if (motionActivity == null) throw new ArgumentException("Motion activity cannot be null"); if (mediaResults == null) throw new ArgumentException("Media result should not be null"); // Filter out all results below 60% probability var mediaResultsAbove60Percent = mediaResults.FindAll(x =&gt; x.Probability &gt;= 60); // If no pictures remain afterwards, return if (mediaResultsAbove60Percent.Count == 0) return false; var highestProbability = mediaResultsAbove60Percent.Max(x =&gt; x.Probability); var message = await CreateEmailMessage(motionActivity, highestProbability, mediaResultsAbove60Percent); var fullMessage = AddRecipients(message, highestProbability); return await SendMessage(fullMessage).ConfigureAwait(false); } /// &lt;summary&gt; Sends the message using MimeMessage/office365 &lt;/summary&gt; /// &lt;param name="message"&gt; The message we are sending &lt;/param&gt; /// &lt;returns&gt;Whether or not the message send was successful.&lt;/returns&gt; private async Task&lt;bool&gt; SendMessage(MimeMessage message) { try { using (var client = new SmtpClient()) { await client.ConnectAsync(_emailSettings.Host, _emailSettings.Port, false); await client.AuthenticateAsync(_emailSettings.FromAddress, _emailSettings.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception ex) { Log.Error( "An error occurred trying to send an Office 365 email: {message}, {innerException}, {stacktrace}", ex.Message, ex.InnerException, ex.StackTrace); return false; } return true; } /// &lt;summary&gt; Creates the templates used for emails &lt;/summary&gt; /// &lt;param name="motionActivity"&gt; is the data of the entire time we collected motion for ONE camera &lt;/param&gt; /// &lt;param name="highestProbability"&gt; the highest probability we found that we think there is a canister &lt;/param&gt; /// &lt;param name="mediaResultsAbove60Percent"&gt; images above 60% &lt;/param&gt; private async Task&lt;MimeMessage&gt; CreateEmailMessage(MotionActivity motionActivity, double highestProbability, IEnumerable&lt;MediaAnalysis&gt; mediaResultsAbove60Percent) { var (subject, body) = await TemplateRetriever.CreateEmailTemplate(motionActivity, highestProbability); var builder = new BodyBuilder {HtmlBody = body}; var message = new MimeMessage(); message.From.Add(new MailboxAddress(_emailSettings.DisplayName, _emailSettings.FromAddress)); message.Subject = subject; var emailWithAttachments = await AddImageAttachment(mediaResultsAbove60Percent, message, builder); emailWithAttachments.Body = builder.ToMessageBody(); return emailWithAttachments; } /// &lt;summary&gt; Adds all recipients to our email &lt;/summary&gt; /// &lt;param name="email"&gt; the email we are sending &lt;/param&gt; /// &lt;param name="highestProbability"&gt; the highest probability from all media results &lt;/param&gt; private MimeMessage AddRecipients(MimeMessage email, double highestProbability) { var recipients = highestProbability &gt;= 75 ? _emailSettings.FullRecipients : _emailSettings.Recipients; foreach (var recipient in recipients) email.To.Add(new MailboxAddress(recipient)); return email; } /// &lt;summary&gt; Takes all images above 60% probability and adds the image to the email&lt;/summary&gt; /// &lt;param name="mediaResultsAbove60Percent"&gt; images above 60% &lt;/param&gt; /// &lt;param name="email"&gt; the email we will be sending &lt;/param&gt; /// &lt;param name="bodyBuilder"&gt; the body builder for emails &lt;/param&gt; /// &lt;returns&gt; the email &lt;/returns&gt; private async Task&lt;MimeMessage&gt; AddImageAttachment(IEnumerable&lt;MediaAnalysis&gt; mediaResultsAbove60Percent, MimeMessage email, BodyBuilder bodyBuilder) { foreach (var mediaResult in mediaResultsAbove60Percent) { if (mediaResult.MediaUrl == null) continue; var download = await _blobStorageService.DownloadFile(mediaResult.MediaUrl).ConfigureAwait(false); var byteArray = StreamToByteArray(download.Content); bodyBuilder.Attachments.Add(mediaResult.MediaUrl, byteArray); } return email; } /// &lt;summary&gt; Helper method for add image attachment. Converts stream to byte array. &lt;/summary&gt; /// &lt;param name="input"&gt; the image we are converting &lt;/param&gt; /// &lt;returns&gt; the byte array &lt;/returns&gt; private static byte[] StreamToByteArray(Stream input) { using (var ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } } } </code></pre> <p>Did split the class into two</p> <pre><code>public static class TemplateRetriever { /// &lt;summary&gt; Creates the templates used for emails &lt;/summary&gt; /// &lt;param name="motionActivity"&gt; is the data of the entire time we collected motion for ONE camera &lt;/param&gt; /// &lt;param name="highestProbability"&gt; the highest probability we found that we think there is a canister &lt;/param&gt; public static async Task&lt;Tuple&lt;string, string&gt;&gt; CreateEmailTemplate(MotionActivity motionActivity, double highestProbability) { var dataHash = new Dictionary&lt;string, object&gt; { {"highestProbability", highestProbability}, {"motionActivity", motionActivity} }; var subject = string.Empty; var bodyTemplate = string.Empty; //Changes subject headline based on probability if (highestProbability &gt;= 60 &amp;&amp; highestProbability &lt;= 74) { subject = $"Chameleon Detect: Audit Image - {highestProbability}%"; bodyTemplate = await GetTemplate("HighProbabilityTemplate.html", dataHash); } if (highestProbability &gt;= 75 &amp;&amp; highestProbability &lt;= 87) { subject = $"Chameleon Detect: Warning Image - {highestProbability}%"; bodyTemplate = await GetTemplate("MediumProbabilityTemplate.html", dataHash); } if (highestProbability &gt;= 88 &amp;&amp; highestProbability &lt;= 100) { subject = $"Chameleon Detect: High Risk Image - {highestProbability}%"; bodyTemplate = await GetTemplate("LowProbabilityTemplate.html", dataHash); } return new Tuple&lt;string, string&gt;(subject, bodyTemplate); } private static async Task&lt;string&gt; GetTemplate(string fileName, Dictionary&lt;string, object&gt; dataHash) { // Determine path var assembly = Assembly.GetExecutingAssembly(); var resourcePath = assembly.GetManifestResourceNames() .Single(str =&gt; str.EndsWith(fileName)); var stubble = new StubbleBuilder().Build(); using (var stream = assembly.GetManifestResourceStream(resourcePath)) using (var streamReader = new StreamReader(stream ?? throw new Exception(), Encoding.UTF8)) { var content = await streamReader.ReadToEndAsync(); var output = await stubble.RenderAsync(content, dataHash); return output; } } } </code></pre> <p>And the HTML file being read using the Stubble HTML template framework <a href="https://github.com/StubbleOrg/Stubble/blob/master/docs/how-to.md" rel="nofollow noreferrer">https://github.com/StubbleOrg/Stubble/blob/master/docs/how-to.md</a></p> <pre><code>&lt;body&gt; &lt;p&gt;Dear Concierge &lt;/p&gt; &lt;p&gt;It is possible that an explosive canister has entered the building at the address above. Please review the attached photographs and take precautionary action.&lt;/p&gt; &lt;p&gt;Motion Activity: {{motionActivity}}&lt;/p&gt; &lt;/body&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T17:35:54.053", "Id": "242705", "Score": "2", "Tags": [ "c#", "html", ".net", "email" ], "Title": "Email Service - Sending an email with azure blob storage Version 2.0" }
242705
<p>Here's a little bash script I wrote, which basically checks something on an Amazon EC2 instance and reports data to CloudWatch every 60 seconds. I'll run this inside a container. Everything works just fine, but I think it's clunky, doesn't write anything to stdout/stderr so no logs, and doesn't handle any errors. I am open to refactoring this or even writing it in Python, to make my docker image more efficient. Any suggestions, criticism is most welcome.</p> <p>Here's the full script less some sensitive data that I've xxx'd:</p> <pre><code>#!/bin/bash INSTANCEID=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id/) AZ=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone) REGION= $(echo $AZ | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:') URL="xxx" putdata() { aws cloudwatch put-metric-data "some other stuff" $1 "xxx" sleep 60 } while true; do HTTP_RESPONSE=$(curl --write-out "%{http_code}" --silent --output /dev/null "$URL") if [ "$HTTP_RESPONSE" = "200" ]; then putdata 0 else putdata 1 fi done </code></pre> <p><strong>EDIT:</strong> just realized that the sleep command runs as a separate PID inside the container, which is why the container takes quite a while to stop. Running with --init flag improves the exit workflow as it better reaps the processes upon exit but that's another unwanted PID. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:49:02.217", "Id": "476324", "Score": "0", "body": "Hi, removing the tag makes sense. I am not asking anyone to rewrite my code, just suggestions how this can be made better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:51:28.970", "Id": "476325", "Score": "0", "body": "FWIW \"I am open to refactoring this or even writing it in Python\" with the [tag:python] can be misconstrued as that :) All the best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T19:00:07.587", "Id": "476329", "Score": "0", "body": "ah ok.. gotcha, thx!" } ]
[ { "body": "<h1>Good</h1>\n\n<ul>\n<li>good variable names</li>\n<li>nice indentation</li>\n<li>good use of <code>$()</code></li>\n<li>double quoting <code>$</code> variable interpolation</li>\n</ul>\n\n<h1>Challenges</h1>\n\n<p>I'm guessing some part of what you removed and <code>xxx</code>d has caused the <code>putdata</code> function to not do anything with the argument you are passing in. If I guessed wrong, then you should remove the arguments so it doesn't cause someone else confusion.</p>\n\n<p>Do you want this to be totally silent? I'm not sure if the <code>aws</code> command produces any output here. Adding a <code>date</code> command in the <code>while</code> loop would help debugging if you come back to the terminal later to figure out what happened. I'd run this in a terminal under <code>tmux</code> for a few weeks before I started trying it in containers. This sort of thing can have fun edge cases when some API falls over. It can take a while to catch all of those.</p>\n\n<p>It sounds like you'd like some logging. That can be done in bash with redirection such as <code>&gt;&gt; logfile</code>. Of course, there are <a href=\"https://serverfault.com/a/103569/205542\">more advanced choices</a>.</p>\n\n<p>I'd put a blank link before the <code>while</code> loop and get rid of the blank line inside of it.</p>\n\n<p>You mention rewriting in python. I wouldn't worry about it for anything this small. But generally for AWS programming python is the winning choice since <a href=\"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html\" rel=\"nofollow noreferrer\">AWS provides their API that way</a>. Functionality may be available through the API before it is available in console. Everything in the <code>aws</code> CLI command is built with this. You can use <code>jq</code> to process JSON that comes back from running the <code>aws</code> command to do the same stuff in bash, but it is more work than python where you get a dictionary back and not have to parse any JSON.</p>\n\n<p>Finally, using <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> is a good habit to get into when shell coding.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T21:04:09.253", "Id": "476344", "Score": "0", "body": "Hey there, thanks for the response. Great suggestions, especially date and time, and yes, the put metric data command doesn't produce any output, that's the crappy part: https://docs.aws.amazon.com/cli/latest/reference/cloudwatch/put-metric-data.html#examples which is making logging hard. Maybe I should output the exit code of that aws command with the time for the logs. And btw I work for AWS, more of a deployment guy, am new to scripting/coding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T21:10:43.467", "Id": "476346", "Score": "1", "body": "Cool that you're part of the cloud! :). Logging the exit code and the date/time would have been my first suggestion. And if something breaks it might produce more output, so try to log that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:36:43.137", "Id": "242716", "ParentId": "242709", "Score": "2" } } ]
{ "AcceptedAnswerId": "242716", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:18:52.637", "Id": "242709", "Score": "3", "Tags": [ "bash", "docker" ], "Title": "Bash script to send certain data from AWC EC2 to CloudWatch" }
242709
<p>I've been working on an LR(1) parser, and I've just finished making the LR(1) item. I'm very rusty with C++, so any pointers (especially optimization and code structure) would be appreciated. Here are my files:</p> <p><strong>main.cpp:</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;array&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; #include "lritem.cpp" int main() { std::cout &lt;&lt; std::boolalpha; LR1Item item = LR1Item( "expr", std::array&lt;const char*, 3&gt; {"alpha", "B", "beta"}, std::array&lt;const char*, 2&gt; {"$", "beta"}, 0); item.move_forward(); item.move_forward(); std::vector&lt;const char*&gt; abc = item.first_of(std::unordered_map&lt;const char*, std::array&lt;const char*, 2&gt;&gt; { {"alpha", std::array&lt;const char*, 2&gt; {"B", "beta"}}, {"B", std::array&lt;const char*, 2&gt; {"alpha", "beta"}}, {"beta", std::array&lt;const char*, 2&gt; {"alpha", "B"}}, {"$", std::array&lt;const char*, 2&gt; {"beta", "alpha"}} }); std::cout &lt;&lt; "["; for (const char* y: abc) { std::cout &lt;&lt; y &lt;&lt; ","; } std::cout &lt;&lt; "]\n"; } </code></pre> <p><strong>lritem.cpp:</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;array&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;algorithm&gt; #include "lritem.hpp" template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; bool LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::is_final_item() const { // check if we are at the end of rhs return parsed_till == rhs.size(); } template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; const char* LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::move_forward() { // return the symbol we are moving over, then // move forward return rhs[parsed_till++]; } template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; const char* LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::get_neighbor() const { // return the symbol after the place we have parsed till return rhs[parsed_till]; } template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; template &lt;std::size_t FIRST_SIZE&gt; std::vector&lt;const char*&gt; LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::first_of( std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets) { if (parsed_till + 1 &lt;= rhs.size() - 1) { std::vector&lt;const char*&gt; first = get_following_items(first_sets); // if we find ε ("" in this case) in the first set if (std::find(first.begin(), first.end(), "") != first.end()) { if (parsed_till + 1 &gt; rhs.size() - 1) { // add all the lookahead symbols first.reserve(lookahead.size()); for (const char* la: lookahead) { first.push_back(la); } } } // remove ε ("" in this case) std::remove(first.begin(), first.end(), ""); return first; } else { // if we are a final item, just return a vector version // of the lookahead return std::vector&lt;const char*&gt; (lookahead.begin(), lookahead.end()); } } template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; template &lt;std::size_t FIRST_SIZE&gt; std::vector&lt;const char*&gt; LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::get_following_items( std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets) { // set 'following' to all the items after the location after // we have parsed till; if there is no symbol after the location // we have parsed till, set following to an empty vector std::vector&lt;const char*&gt; following = ((parsed_till + 1 &gt; rhs.size()) ? std::vector&lt;const char*&gt; (): std::vector&lt;const char*&gt; (rhs.begin() + parsed_till + 1, rhs.end())); // extend all the symbols in the lookahead to 'following' for (const char* la: lookahead) { following.push_back(la); } int i = 0; for (const char* x: following) { // if 'x' is not nullable (does not have ε ("" in this case)), //then everything ahead of it is cut off, and we break out // of the loop if (std::find(first_sets[x].begin(), first_sets[x].end(), "") == first_sets[x].end()) { following = std::vector&lt;const char*&gt; (following.cbegin(), following.cbegin() + i + 1); break; } ++i; } // get the first sets of the symbols in 'following' std::vector&lt;const char*&gt; first; first.reserve(2 * following.size()); for (const char* symbol: following) { for (const char* item: first_sets[symbol]) { first.push_back(item); } } return first; } </code></pre> <p><strong>lritem.hpp:</strong></p> <pre class="lang-cpp prettyprint-override"><code>#ifndef LRUTIL_H #define LRUTIL_H #include &lt;array&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt; class LR1Item { private: const char* lhs; std::array&lt;const char*, RHS_SIZE&gt; rhs; std::array&lt;const char*, LA_SIZE&gt; lookahead; int parsed_till; public: LR1Item(const char* lhs, std::array&lt;const char*, RHS_SIZE&gt; rhs, std::array&lt;const char*, LA_SIZE&gt; lookahead, int parsed_till): lhs(lhs), rhs(rhs), lookahead(lookahead), parsed_till(parsed_till) {} bool is_final_item() const; const char* get_neighbor() const; const char* move_forward(); template &lt;std::size_t FIRST_SIZE&gt; std::vector&lt;const char*&gt; first_of( std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets); template &lt;std::size_t FIRST_SIZE&gt; std::vector&lt;const char*&gt; get_following_items( std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets); }; #endif <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:17:13.233", "Id": "476335", "Score": "0", "body": "`#include \"lritem.cpp\"`? 0_o" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:18:45.577", "Id": "476336", "Score": "0", "body": "@bipll -- I'm not amazing with C++ :( Is there something incorrect with that line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:20:40.400", "Id": "476337", "Score": "0", "body": "It's just, .cpp is a traditional extension for compiled source files, not the included headers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T22:01:55.343", "Id": "476351", "Score": "0", "body": "`main.py`? This isn't Python..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T22:02:30.937", "Id": "476352", "Score": "0", "body": "I think you should `#include \"lritem.hpp\"` instead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T22:05:17.043", "Id": "476354", "Score": "0", "body": "@S.S.Anne -- My mistake-- python is my native language, so it slipped in :)" } ]
[ { "body": "<pre><code>#ifndef LRUTIL_H\n</code></pre>\n\n<p>This doesn't match the name of the file. If your compiler supports <code>#pragma once</code>, it's easier to use that instead of manual header guards.</p>\n\n<hr>\n\n<pre><code>template &lt;std::size_t RHS_SIZE, std::size_t LA_SIZE&gt;\nbool LR1Item&lt;RHS_SIZE, LA_SIZE&gt;::is_final_item() const { ...\n</code></pre>\n\n<p>Definitions for template functions should be <a href=\"https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file\">in the header file, not in a cpp file</a>.</p>\n\n<hr>\n\n<pre><code>int parsed_till;\n</code></pre>\n\n<p>You may be getting compiler warnings about comparing signed and unsigned numbers because of the type of this variable. Since this is an index, it would probably be better to use an unsigned type here (specifically <code>std::size_t</code>).</p>\n\n<hr>\n\n<pre><code>bool LR1Item::is_final_item() const\n</code></pre>\n\n<p><code>is_final_item</code> implies that our index points at the final item (<code>size() - 1</code>). But we actually have an invalid index at this point. Perhaps <code>is_at_end</code> would be a better name.</p>\n\n<hr>\n\n<pre><code>const char* LR1Item::move_forward() {\n if (is_final_item()) // added check!\n throw std::runtime_error(\"Invalid call to move_forward()!\");\n\n return rhs[parsed_till++];\n}\n</code></pre>\n\n<p>I'd suggest adding a check in <code>move_forward()</code>, something like the above.</p>\n\n<hr>\n\n<pre><code> template &lt;std::size_t FIRST_SIZE&gt;\n std::vector&lt;const char*&gt; first_of(\n std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets);\n\n template &lt;std::size_t FIRST_SIZE&gt;\n std::vector&lt;const char*&gt; get_following_items(\n std::unordered_map&lt;const char*, std::array&lt;const char*, FIRST_SIZE&gt;&gt; first_sets);\n</code></pre>\n\n<p>I think these two functions can both be <code>const</code>.</p>\n\n<hr>\n\n<p><code>parsed_till + 1 &lt;= rhs.size() - 1</code></p>\n\n<p>Is this guaranteed to be safe? I don't see anything ensuring that <code>rhs</code> isn't empty...</p>\n\n<hr>\n\n<p><code>first_sets[x].begin()</code></p>\n\n<p>Note that <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/operator_at\" rel=\"nofollow noreferrer\"><code>unordered_map::operator[]</code></a> will create a new entry at <code>x</code> if it doesn't already exist. We should probably use <code>first_sets.find(x)</code> instead.</p>\n\n<hr>\n\n<p>Consider using <code>std::string</code> and <code>std::vector</code> instead of <code>const char*</code> and <code>std::array</code>. This might be slower, but the code will be much simpler (no array template sizes) and easier to use (no string lifetime / ownership issues).</p>\n\n<hr>\n\n<p>Note: I haven't really checked the logic of what this actually does. I don't remember enough about parsers right now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:04:59.657", "Id": "242737", "ParentId": "242713", "Score": "2" } } ]
{ "AcceptedAnswerId": "242737", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T19:45:04.117", "Id": "242713", "Score": "1", "Tags": [ "c++", "performance", "parsing" ], "Title": "C++ Code structure & Optimization: LR1Item" }
242713
<p>I am a beginner in coding. I was doing this question today. </p> <blockquote> <p>A new movie has been released. Many people are buying tickets which costs 25 dollars. There are many people wanting a ticket but each person has either one of 25 dollar bill, 50 dollar bill or 100 dollar bill. </p> <p>People will only come in the order of queue. You initially have no money. Write a program to see if you can sell ticket to everyone or not.</p> </blockquote> <p>This is my solution </p> <pre><code>#include&lt;iostream.h&gt; #include&lt;conio.h&gt; #include&lt;stdlib.h&gt; void main() { clrscr(); int queue; int bill[100]; cout&lt;&lt;"Enter number of people in queue:"; cin&gt;&gt;queue; cout&lt;&lt;"\n(Bill value 25/50/100)"; for (int i=0;i&lt;queue;i++) { cout&lt;&lt;"Bill person "&lt;&lt;i+1&lt;&lt;" have:"; cin&gt;&gt;bill[i]; } int bill25=0; int bill50=0; int bill100=0; for(i=0;i&lt;queue;i++) { if(bill[i]==25) { bill25++; } else if(bill[i]==50) { if(bill25&gt;0) { bill25--; bill50++; } else { cout&lt;&lt;"No change"; exit(0); } } else if(bill[i]==100) { if(bill50&gt;0&amp;&amp;bill25&gt;0) { bill50--; bill25--; bill100++; } else if(bill25&gt;=3) { bill25-=3; bill100++; } else { cout&lt;&lt;"No change"; exit(0); } } else { cout&lt;&lt;"Wrong bill"; exit(0); } } cout&lt;&lt;"Tickets sold"; getch(); } </code></pre> <p>My testing has found this to be correct (maybe not the best but correct) solution. But I am not sure about it. Are there any possibilities in which this code fails. Also what would be a better solution at my level? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:58:21.220", "Id": "476342", "Score": "0", "body": "Apparently you're using a Turbo C++ compiler from the last century. The only advice I can give you is to use a modern compiler like the latest GCC or CLang. You code is far from modern C++ standards." } ]
[ { "body": "<p>Okay, first up, I'm a bit rusty with C++, so I apologize if this isn't formatted correctly.</p>\n\n<p>But, the first thing that leaps out is \"Single Responsibility Principle\". Aka - each function should be responsible for one thing and have one reason to change.</p>\n\n<p>Or in short: don't write everything in your Main().</p>\n\n<p>What is your Main() doing, at a high level? It's:</p>\n\n<ul>\n<li>Grabbing inputs for how many people and what bills they have</li>\n<li>It's setting up the register (with no bills in it)</li>\n<li>It's looping through each person</li>\n<li>It's checking how that person impacts the current register</li>\n<li>It's outputting the success/failure of the venture.</li>\n</ul>\n\n<p>Awesome! So... what should your main look like in an abstract sense?</p>\n\n<pre><code>main()\n{\n int patronCount = GetPatronCount();\n int[] billAmounts = GetBillAmounts();\n int[] register = SetUpRegister();\n for (i = 0; i &lt; patronCount; i++)\n {\n bool wasAbleToMakeChange = MakeChangeForPatron(register, billAmounts[i]);\n if (!wasAbleToMakeChange)\n {\n // code to return out with failure\n }\n }\n // code to return success\n}\n</code></pre>\n\n<p>So... why would we do this? Well, because right now, if you need to tweak a line of code in your code? That could have ramifications all throughout your function. You can't exactly digest it in small bits, because everything has 'scope' with everything else. And if you needed to <em>change</em> something, you'd have to consider how that change affects everything else in that function.</p>\n\n<p>This is incredibly important as you grow as a programmer - you're going to be <em>changing</em> code a lot more than you're going to be <em>composing</em> it - and the simpler you can make changing it, the better off you'll be.</p>\n\n<p>Also, it becomes much easier to see what the program does. Because the function names and variable names document exactly what it's doing at a high level. It's getting a patron count. Imagine someone reading your code (and only your code - no explanations)... how quickly would they figure out what it's doing? Contrast that to my version's main(). So if someone <em>else</em> needs to work with your code (or if <em>you</em> need to work with it, but don't remember it very well) it'll be able to be grok'ed a lot quicker.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:39:44.357", "Id": "242717", "ParentId": "242714", "Score": "4" } } ]
{ "AcceptedAnswerId": "242717", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:23:23.953", "Id": "242714", "Score": "1", "Tags": [ "c++" ], "Title": "Bill shortage: Basic Coding" }
242714
<p>This is a small web scraping project I made in 2 hours that targets the website remote.co . I am looking forward for improvements in my code. I know about the inconsistency with the WebDriverWait and time.sleep() waits, but when I used the WebDriverWait to wait until the load_more button was clickable and ran the program selenium crashed my webdriver window and continuously spammed my terminal window with 20-30 lines of seemingly useless text.</p> <pre><code>import scrapy from selenium import webdriver from selenium.common.exceptions import ElementNotInteractableException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import ElementClickInterceptedException from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep class ScrapeRemote(scrapy.Spider): name = 'jobs' start_urls = [f'https://remote.co/remote-jobs/search/?search_keywords={job_title}'] job_title = input('Enter your desired position: ').replace(' ', '+') def __init__(self): self.driver = webdriver.Chrome(r'C:\Users\leagu\chromedriver.exe') def parse(self, response): self.driver.get(response.url) try: load_more = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located((By.XPATH, '/html/body/main/div[2]/div/div[1]/div[3]/div/div/a')) ) except TimeoutException: self.log("Timeout - Couldn't load the page!") while True: try: sleep(1.5) load_more = self.driver.find_element_by_css_selector('a.load_more_jobs') load_more.click() except (ElementNotInteractableException, ElementClickInterceptedException): try: close_button = WebDriverWait(self.driver, 6).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '#om-oqulaezshgjig4mgnmcn-optin &gt; div &gt; button')) ) close_button.click() except TimeoutException: self.log('Reached Bottom Of The Page!') break selector = scrapy.selector.Selector(text=self.driver.page_source) listings = selector.css('li.job_listing').getall() for listing in listings: selector = scrapy.selector.Selector(text=listing) position = selector.css('div.position h3::text').get() company = selector.css('div.company strong::text').get() more_information = selector.css('a::attr(href)').get() yield { 'position': position, 'company': company, 'more_information': more_information } self.driver.close() </code></pre>
[]
[ { "body": "<h2>Combined imports</h2>\n\n<pre><code>from selenium.common.exceptions import ElementNotInteractableException\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import ElementClickInterceptedException\nfrom selenium.common.exceptions import TimeoutException\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>from selenium.common.exceptions import (\n ElementNotInteractableException,\n NoSuchElementException,\n ElementClickInterceptedException,\n TimeoutException,\n)\n</code></pre>\n\n<h2>Input-in-static</h2>\n\n<p>This:</p>\n\n<pre><code>job_title = input('Enter your desired position: ').replace(' ', '+')\n</code></pre>\n\n<p>creeps me out. I don't know a lot about <code>scrapy</code>, but see if you can initialize <code>job_title</code> in the constructor instead of as a static. What if this class were to be imported once and used twice, each with a different job title?</p>\n\n<h2>Hard-coded paths</h2>\n\n<p>This:</p>\n\n<pre><code>'C:\\Users\\leagu\\chromedriver.exe'\n</code></pre>\n\n<p>should be pulled out into a constant, or better yet, an environmental parameter, command-line argument or configuration file parameter. Surely a user of yours who downloads your script will not be named <code>leagu</code>.</p>\n\n<h2>XPath</h2>\n\n<pre><code>/html/body/main/div[2]/div/div[1]/div[3]/div/div/a\n</code></pre>\n\n<p>is extremely fragile and opaque. I loaded the <code>remote.co</code> search results, and a better selector - mind you, this is CSS and not XPath - is</p>\n\n<pre><code>div.card &gt; div.card-body &gt; div.card &gt; div.card-body &gt; a.card\n</code></pre>\n\n<p>You should not start from the root element, and you should attempt to use classes and IDs where possible. This markup is kind of a mess and so meaningful paths are hard to form.</p>\n\n<h2>Swallowing exceptions</h2>\n\n<p>You do this:</p>\n\n<pre><code> except TimeoutException:\n self.log(\"Timeout - Couldn't load the page!\")\n</code></pre>\n\n<p>but then continue with the rest of the method? Would you not want to re-throw, or at least return?</p>\n\n<h2>Non-guaranteed close</h2>\n\n<p>This:</p>\n\n<pre><code>self.driver.close()\n</code></pre>\n\n<p>will be skipped if there is any uncaught exception. First of all, I don't think the driver should be closed in <code>parse</code>, or else the class effectively can only support one invocation of <code>parse</code>. Implement <code>__enter__</code> and <code>__exit__</code>, and call <code>driver.close()</code> in <code>__exit__</code>. Have the instantiator of <code>ScrapeRemote</code> use it in a with-block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T16:12:41.243", "Id": "477129", "Score": "0", "body": "Thank you for dedicating your time to my code. Firstly I don't understand the term 're-throw an exception', I redid my code and now it throws and error on the first timeout, but I guess this isn't what you refered to. Secondly I don't know if it is possible to get the whole object inside a with statement when scrapy is calling the spider from the command line and doing a lot of work 'under the hood'. Here is a link to my refined code: [link](https://github.com/Viktor-stefanov/Scrapy-Selenium-Jobs-Crawler/blob/master/Scrape_Remote_With_Scrapy/Scrape_Remote_With_Scrapy/spiders/scrape.py)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T16:53:58.570", "Id": "477132", "Score": "0", "body": "_I don't understand the term 're-throw an exception'_ - If you write `throw` within an `except`, it rethrows the original exception." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T20:33:05.423", "Id": "242969", "ParentId": "242715", "Score": "3" } } ]
{ "AcceptedAnswerId": "242969", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T20:30:28.357", "Id": "242715", "Score": "3", "Tags": [ "python", "web-scraping", "selenium", "scrapy" ], "Title": "Web Scraping Dynamically Generated Content Python" }
242715
<p>I've decided to work on my Perl skills. I've written a small subroutine that splits a string based on an optional delimiter. I'd like any feedback on this program so I can kick bad habits to the curb. Written in Perl 5.</p> <pre><code>sub split_string { my $string = @_[0]; my $delimiter = @_[1] ? @_[1] : " "; my @result = (); my $temp = ""; for $i (0..length($string)) { my $char = substr($string, $i, 1); if (($char eq $delimiter) or $i == length($string)) { push(@result, $temp); $temp = ""; } else { $temp .= $char; } } return @result; } </code></pre> <p>And this is how I test this subroutine.</p> <pre><code>@test = split_string("This is a test to ensure this works correctly."); foreach $element (@test) { print $element . "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:38:21.280", "Id": "476417", "Score": "4", "body": "Why did you not use the builtin [`split`](https://perldoc.perl.org/functions/split.html) ?" } ]
[ { "body": "<h2>- Use the <code>strict</code> and <code>warnings</code> pragmas</h2>\n\n<p>This helps catch many errors at an early stage.</p>\n\n<h2>- Declare lexical variables with <code>my</code> instead of using package variables</h2>\n\n<p>If you define variables without having declared them they will be defined as package variables (which are seen by all code in your package). Note that if you use the <code>strict</code> pragma you need to declare package variables with <code>our</code>.</p>\n\n<h2>- use <code>say</code> instead of <code>print</code></h2>\n\n<p>Since <code>perl</code> version 5.10 you can use <code>say</code> to print a line and add the line terminator (newline character) automatically. Just remember to enable the the feature with <code>use feature qw(say)</code>.</p>\n\n<h2>- Unpack arguments to a function/method from the <code>@_</code> array for clarity</h2>\n\n<p>Prefer <code>my ($str, $delim) = @_</code> over <code>my $str = $_[0]; my $delim = $_[1]</code></p>\n\n<h2>- Use <code>$array[$N]</code> to refer to the (<code>$N+1</code>)th element of <code>@array</code>.</h2>\n\n<p>In you code you used <code>@_[1]</code> to refer to the second element of the <code>@_</code> array. The correct syntax is to use <code>$_[1]</code>.</p>\n\n<h2>- Do not use parenthesis around argument for builtin functions if not necessary.</h2>\n\n<p>In Perl parenthesis around function arguments is optional. A common style is to avoid parenthesis around builtin function calls. This reduces visual clutter and disambiguates built-in functions from user functions, see also <a href=\"https://stackoverflow.com/q/15772996/2173773\">What is the reason to use parenthesis-less subroutine calls in Perl?</a></p>\n\n<h2>- Don't declare empty arrays with empty parenthesis. Simply use <code>my @arr</code>;</h2>\n\n<h2>- Return a reference to an array and not an array value.</h2>\n\n<p>By returning a reference you avoid copying, but see also <a href=\"https://stackoverflow.com/q/47718928/2173773\">In perl, when assigning a subroutine's return value to a variable, is the data duplicated in memory?</a></p>\n\n<h2>- Don't reinvent the wheel, use the Perl builtin function <code>split</code></h2>\n\n<p>You tagged your question with [reinventing-the-wheel] so I assume this is for learning purposes only. </p>\n\n<p>Here is a revised version of your code that implements the above comments:</p>\n\n<pre><code>use feature qw(say);\nuse strict;\nuse warnings;\n\n{ # &lt;-- create a scope so lexical variable does not \"leak\" into the subs below\n\n my $test = split_string(\"This is a test to ensure this works correctly.\");\n foreach my $element (@$test) {\n say $element;\n }\n}\n\nsub split_string {\n my ( $string, $delimiter ) = @_;\n\n $delimiter //= \" \";\n my @result;\n my $temp = \"\";\n\n for my $i (0..(length $string)) {\n my $char = substr $string, $i, 1;\n if (($char eq $delimiter) or $i == (length $string)) {\n push @result, $temp;\n $temp = \"\";\n } else {\n $temp .= $char;\n }\n }\n return \\@result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T02:59:43.037", "Id": "476682", "Score": "0", "body": "Coming from python, I was wondering how to make unpacking items from arrays cleaner. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T12:22:59.353", "Id": "242744", "ParentId": "242719", "Score": "8" } }, { "body": "<p>I agree with the previous answer, especially the remarks about using the <a href=\"https://perldoc.perl.org/5.32.0/strict.html\" rel=\"nofollow noreferrer\">strict</a> and <a href=\"https://perldoc.perl.org/5.32.0/warnings.html\" rel=\"nofollow noreferrer\">warnings</a> pragmas. I fixed so many Perl bugs which could be seen easily using these pragmas.</p>\n<p>First of all you should know that Perl's split command uses regular expression as the delimiter, would you like to dare and write a regular expression based split_string?</p>\n<p>Secondly, to make it look more as the Perl's split you could use <a href=\"https://perldoc.perl.org/perlsub.html#Prototypes\" rel=\"nofollow noreferrer\">prototypes</a> (which will also check for correct parameter passing):</p>\n<pre><code>sub split_string ($;$);\n</code></pre>\n<p>Than you can call the function as following (note that there is no need for parenthesis):</p>\n<pre><code>my $test = split_string &quot;This is a test to ensure this works correctly.&quot;;\n</code></pre>\n<p>I like to use prototypes when I write basic functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:57:56.017", "Id": "245517", "ParentId": "242719", "Score": "3" } }, { "body": "<p>All the main code comments you've had so far are solid.</p>\n<p>I thought I would address your approach to testing.</p>\n<p>If you write your code as a module that can be loaded with &quot;use&quot; it's very easy to use Perl's extensive testing toolset.</p>\n<p>You can use the classical Test::Simple and Test::More modules that are built in with many versions of Perl. But if you are comfortable with CPAN module installation (it's worth learning, if you aren't) you can install the newer Test2 suite which makes writing tests even easier.</p>\n<p>Check out <a href=\"https://metacpan.org/pod/Test2::V0\" rel=\"nofollow noreferrer\">Test2::V0</a> which is a nice big bundle of testing functions.</p>\n<p>Also see <a href=\"https://metacpan.org/pod/Test2::Manual::Testing::Introduction\" rel=\"nofollow noreferrer\">the introduction</a> to the tools.</p>\n<p>In short write your code like:</p>\n<pre><code>package MySplit;\n\nuse Exporter qw&lt;import&gt;;\nour @EXPORT_OK = qw( split_string );\n\nsub split_string {\n # do stuff\n}\n\n1;\n</code></pre>\n<p>Then write tests like:</p>\n<pre><code>#!/bin/env perl\nuse strict;\nuse warnings;\nuse Test::V0;\n\nuse MySplit qw&lt; split_string &gt;;\n\nis split_string('1,2,4'),\n array {\n item 1;\n item 2;\n item 4;\n end();\n }, \n &quot;Basic split works&quot;;\n\ndone_testing();\n</code></pre>\n<p>The above sample doesn't really dig into the expressiveness and power of the comparator constructors. You can see more <a href=\"https://metacpan.org/pod/Test2::Tools::Compare#ARRAY-BUILDER\" rel=\"nofollow noreferrer\">in the docs</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T05:19:25.650", "Id": "246224", "ParentId": "242719", "Score": "2" } } ]
{ "AcceptedAnswerId": "242744", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T23:06:21.900", "Id": "242719", "Score": "2", "Tags": [ "strings", "reinventing-the-wheel", "perl" ], "Title": "Perl - Splitting a string" }
242719
<p>I've implemented tic-tac-toe in TypeScript <a href="https://codereview.stackexchange.com/questions/203427/tic-tac-toe-game-game-logic-no-ui">before</a>; now I'm porting it to Elixir. As before, this is pure game logic, no UI involved. I'm very new to Elixir, so any suggestions are appreciated.</p> <p>The actual game logic:</p> <pre><code>defmodule MassivelyMultiplayerTtt.Game do defstruct current_player: :player_x, winning_player: :unfinished, board: Tuple.duplicate(:empty, 9) def make_move(game, cell_num) do case elem(game.board, cell_num) do :x -&gt; {:square_filled, game} :o -&gt; {:square_filled, game} :empty -&gt; if game.winning_player != :unfinished do {:game_already_over, game} else game = if game.current_player == :player_x do %{game | board: put_elem(game.board, cell_num, :x), current_player: :player_o} else %{game | board: put_elem(game.board, cell_num, :o), current_player: :player_x} end game = check_for_end(game) case game.winning_player do :unfinished -&gt; {:waiting_for_move, game} _ -&gt; {:game_finished, game} end end end end defp check_for_end(game) do case game.board do {:x, :x, :x, _, _, _, _, _, _} -&gt; %{game | winning_player: :player_x} {_, _, _, :x, :x, :x, _, _, _} -&gt; %{game | winning_player: :player_x} {_, _, _, _, _, _, :x, :x, :x} -&gt; %{game | winning_player: :player_x} {:x, _, _, :x, _, _, :x, _, _} -&gt; %{game | winning_player: :player_x} {_, :x, _, _, :x, _, _, :x, _} -&gt; %{game | winning_player: :player_x} {_, _, :x, _, _, :x, _, _, :x} -&gt; %{game | winning_player: :player_x} {:x, _, _, _, :x, _, _, _, :x} -&gt; %{game | winning_player: :player_x} {_, _, :x, _, :x, _, :x, _, _} -&gt; %{game | winning_player: :player_x} {:o, :o, :o, _, _, _, _, _, _} -&gt; %{game | winning_player: :player_o} {_, _, _, :o, :o, :o, _, _, _} -&gt; %{game | winning_player: :player_o} {_, _, _, _, _, _, :o, :o, :o} -&gt; %{game | winning_player: :player_o} {:o, _, _, :o, _, _, :o, _, _} -&gt; %{game | winning_player: :player_o} {_, :o, _, _, :o, _, _, :o, _} -&gt; %{game | winning_player: :player_o} {_, _, :o, _, _, :o, _, _, :o} -&gt; %{game | winning_player: :player_o} {:o, _, _, _, :o, _, _, _, :o} -&gt; %{game | winning_player: :player_o} {_, _, :o, _, :o, _, :o, _, _} -&gt; %{game | winning_player: :player_o} board -&gt; if Enum.any?(Tuple.to_list(board), &amp;match?(:empty, &amp;1)) do game else %{game | winning_player: :drawn} end end end end </code></pre> <p>Unit tests:</p> <pre><code>defmodule MassivelyMultiplayerTtt.GameTest do use ExUnit.Case, async: true import MassivelyMultiplayerTtt.Game test "recognizes X's victory" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {_, game} = make_move(game, 6) {_, game} = make_move(game, 1) {_, game} = make_move(game, 7) {result, game} = make_move(game, 2) # Assert assert(result == :game_finished) assert(game.winning_player == :player_x) end test "recognizes O's victory" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {_, game} = make_move(game, 6) {_, game} = make_move(game, 1) {_, game} = make_move(game, 7) {_, game} = make_move(game, 5) {result, game} = make_move(game, 8) # Assert assert(result == :game_finished) assert(game.winning_player == :player_o) end test "recognizes a drawn game" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {_, game} = make_move(game, 1) {_, game} = make_move(game, 3) {_, game} = make_move(game, 4) {_, game} = make_move(game, 7) {_, game} = make_move(game, 6) {_, game} = make_move(game, 2) {_, game} = make_move(game, 5) {result, game} = make_move(game, 8) # Assert assert(result == :game_finished) assert(game.winning_player == :drawn) end test "returns an error when attempting to move to an already-filled cell" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {result, _} = make_move(game, 0) # Assert assert(result == :square_filled) end test "returns an error when attempting to move in an already completed game" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {_, game} = make_move(game, 6) {_, game} = make_move(game, 1) {_, game} = make_move(game, 7) {_, game} = make_move(game, 2) {result, _} = make_move(game, 5) # Assert assert(result == :game_already_over) end test "recognizes X's turn" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {_, game} = make_move(game, 0) {result, game} = make_move(game, 1) # Assert assert(result == :waiting_for_move) assert(game.current_player == :player_x) end test "recognizes O's turn" do # Arrange game = %MassivelyMultiplayerTtt.Game{} # Act {result, game} = make_move(game, 0) # Assert assert(result == :waiting_for_move) assert(game.current_player == :player_o) end end </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:06:23.643", "Id": "242720", "Score": "1", "Tags": [ "beginner", "tic-tac-toe", "elixir" ], "Title": "Tic Tac Toe game logic" }
242720
<p>i'm a beginner in C++<br> i decided to learn the <strong>Scary</strong> <em>C++ Programing Language</em><br> i am a slow learner and after 2 Months learning C++ i saw the need to have a Nice and Tidy progress bar for my programs.</p> <p>Here what i wrote:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;iomanip&gt; #include &lt;unistd.h&gt; // That function controls the inner Bar void printProgressBar(char fill = '.', char highlight = '*', int barSize = 10, float startingProgress = 0.0f ) { for (int pos = 0; pos &lt; (barSize-(startingProgress*10)); ++pos) { std::cout &lt;&lt; "\r[" &lt;&lt; std::string(pos, fill) &lt;&lt; highlight &lt;&lt; std::flush; usleep(50000); } } // That function controls the outer Bar void progressBarBox(char highlight = '*', float endPoint = 1.0f){ std::cout &lt;&lt; std::string(endPoint*10, highlight); std::cout &lt;&lt; ']' &lt;&lt; std::flush; } int main(int argc, char* argv[]) { const int barSize{3}; const char barFill{'.'}; const char barHighlight{'*'}; progressBarBox(barFill, barSize+0.1f); float progress {0.0f}; while (progress &lt; barSize) { printProgressBar(barFill, barHighlight, barSize*10, progress); progressBarBox(barHighlight, progress); progress += 0.1; } std::cout &lt;&lt; "\nDone" &lt;&lt; std::endl; return 0; } </code></pre> <p>The problem is: with python i never cared about best practices, clean of code or code readbility </p> <p>I Have many questions about my solution</p> <h1> My Questions: </h1> <ol> <li>How would you rate my code, what to improve ?</li> <li>how to improve his readbility?</li> <li>this code would be fine to work with or a headache to mantain, how to improve?</li> <li>is there Better ways ( that are not so complex too ) to achieve the same ? with the star moving and everything.</li> <li>Is there a best practice i'm not following or missing ?</li> <li>i hardcoded some values is that bad ?</li> <li>a friend of mine said that this code will have a bad performance because of my use of string, is that true ?</li> </ol> <p>I know thats a lot of questions and i am grateful for any contribution or help.</p> <p><a href="https://i.stack.imgur.com/YOtfL.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOtfL.gif" alt=" Got it ?"></a></p>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has inconsistent indentation which makes it a bit harder to read and understand. Pick a style and apply it consistently. </p>\n\n<h2>Think carefully about requirements</h2>\n\n<p>You wrote:</p>\n\n<blockquote>\n <p>a friend of mine said that this code will have a bad performance because of my use of string, is that true ?</p>\n</blockquote>\n\n<p>Maybe, but it's important to think about the requirements <em>first</em> before chasing phantoms of imagined performance gains. The first question is, \"does it matter how fast it is?\" I'd say that any code that contains <code>usleeep(50000);</code> within a loop probably isn't performance-critical and so it doesn't much matter. </p>\n\n<p>So then that leads to the question of what <em>does</em> matter which directly leads to the topic of requirements. What does the code need to do? Is there a performance requirement? A memory footprint requirement? An efficiency requirement? My usual advice is to create the simplest thing that works. This allows you (and others) to more easily understand the code and to avoid wasting your time on \"optimizing\" things that don't need to be optimal.</p>\n\n<h2>Use object-oriented programming</h2>\n\n<p>In this case, there's a thing called a \"progress bar\" that is expected to indicate the progress of some user-controlled process. This suggests that it might be better to create a <code>ProgressBar</code> object. That way, the current state of the bar, including the particular characters used, and its representation could be separate aspects of the same object. This would be much cleaner and also have the advantage of making it easier to create alternative output formats.</p>\n\n<h2>Consider the user(s)</h2>\n\n<p>Consider the user of this progress bar (presumably another programmer, or perhaps yourself). You might want to have some actual lengthy work done by the computer, and the progress bar is just an indicator. However, with the loop and <code>usleep</code> in the <code>printProgressBar</code> function, it's entirely possible that the progress bar itself would take up more time than the lengthy process that led the user to want a progress bar in the first place! There are a couple of ways to address this. The simplest would be to abandon the current look of the progress bar with its animation-like bar and adopt a simpler proportional bar. Another option would be to keep the existing visual effect, but to allow the percentage complete to be indicated by both how many stars are to the right, but also where the advancing star is within the empty space. </p>\n\n<p>That leads to the next consideration, which is the <em>other</em> user of this code, which is not the programmer, but a person using the program that includes this progress bar. For that person, how clear is the intent of this progress bar?</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>This code declares <code>main</code> with arguments <code>argc</code> and <code>argv</code> in the usual way, but neither <code>argc</code> nor <code>argv</code> are actually used. This could be addressed by either declaring <code>int main()</code> or by modifying the code to actually use the variables. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T22:01:56.703", "Id": "476489", "Score": "0", "body": "Thanks, but before accepting the answer, can you please point out what exactly i'm doing in a inconsistent way.<p>a" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T22:03:21.080", "Id": "476490", "Score": "1", "body": "The indentation within `main`, and specifically the `while` loop is probably not what you intended. Also, the two functions each have slightly different brace style (inline vs. start on next line)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T03:08:18.790", "Id": "476507", "Score": "1", "body": "@BunnyGuy Also, the contents of the for loop in `printProgressBar` should be indented." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:49:13.807", "Id": "242771", "ParentId": "242721", "Score": "4" } } ]
{ "AcceptedAnswerId": "242771", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:49:49.580", "Id": "242721", "Score": "4", "Tags": [ "c++", "console" ], "Title": "Animated progress bar in C++ | How to simplify or alternatives using strings" }
242721
<p>I am using hourly weather data to estimate performance of commercial refrigeration systems under various parameters. The formula for estimating co-efficient of performance (COP) of these systems is repeated for each hour. </p> <p>I defined a formula to do this calculation:</p> <pre><code>Public Function estimatedCOP(dischargeTemp As Double, suctionTemp As Double) Dim a As Double, b As Double, c As Double, d As Double, e As Double, f As Double a = 9.12808037 b = 0.15059952 c = 0.00043975 d = -0.09029313 e = 0.00024061 f = -0.00099278 estimatedCOP = a + b * suctionTemp + c * suctionTemp * suctionTemp + _ d * dischargeTemp + e * dischargeTemp * dischargeTemp + _ f * suctionTemp * dischargeTemp End Function </code></pre> <p>The function is repeated twice in a column with 8,760 rows (each hour of the year).</p> <p>This gives the expected result, but takes a long time to calculate and update (as it's repeated ~17,000 times). <strong>How can I improve the performance of this function?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:21:11.150", "Id": "476414", "Score": "1", "body": "Hi, there are a few things that can probably be optimized in this function if appropriate. 1) use constants if the values of a-f if they are static. 2) provide a return type for the function, it is variant right now. That being said, those are pretty minor. This is just basic math ops, this should be fast (less than 1 second) for 10,000 items. What are you doing with the result of the function, writing it a worksheet? I suspect that might be where the slowdown is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:38:23.900", "Id": "476434", "Score": "0", "body": "@RyanWildry it's used a in a column with 8760 rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:57:47.943", "Id": "476443", "Score": "0", "body": "Ahh, I gotcha. Try reworking the update as a sub and update the column by storing the results of the function to an array, then dump those values to the sheet in one shot. This should be faster." } ]
[ { "body": "<p>You are using the <code>Double</code> data type for all variables. I think this is a good thing since it should avoid conversions. But it is probably too large for your purpose.</p>\n\n<p>From the doc:</p>\n\n<blockquote>\n <p>Double (double-precision floating-point) 8 bytes\n -1.79769313486231E308 to -4.94065645841247E-324 for negative values</p>\n</blockquote>\n\n<p>Source: <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary\" rel=\"nofollow noreferrer\">Data type summary</a></p>\n\n<p>Perhaps using the <code>single</code> data type is enough ?</p>\n\n<blockquote>\n <p>Single (single-precision floating-point) 4 bytes -3.402823E38 to\n -1.401298E-45 for negative values\n 1.401298E-45 to 3.402823E38 for positive values</p>\n</blockquote>\n\n<p>You can try and compare results.</p>\n\n<p>For reference a response I made on another topic, that includes comments about data types: <a href=\"https://codereview.stackexchange.com/a/240534/219060\">Adding qty If duplicates keys found VBA</a></p>\n\n<hr>\n\n<p>It is unfortunate that the variable names (a..f) are not descriptive and \n<strong>meaningful</strong>. That makes logic errors harder to spot since the variables look all the same. Surely all those values have a meaning ?</p>\n\n<hr>\n\n<p>Something else: if you are doing calculations in a loop and assuming this is in Excel, you can <strong>suspend automatic recalculation</strong> at the beginning of your procedure:</p>\n\n<pre><code>Application.Calculation = xlManual\n</code></pre>\n\n<p>Turn it back on when you are done:</p>\n\n<pre><code>Application.Calculation = xlAutomatic\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:44:18.203", "Id": "242756", "ParentId": "242722", "Score": "2" } }, { "body": "<p>You can reduce the number of operations from 5 additions, 8 multiplications to 5 additions, 5 multiplications using this (incorporating the advice to use constants, declared at module level):</p>\n<pre><code> Const a = 9.12808037\n Const b = 0.15059952\n Const c = 0.00043975\n Const d = -0.09029313\n Const e = 0.00024061\n Const f = -0.00099278\n \n Public Function estimatedCOP(dischargeTemp As Double, suctionTemp As Double)\n ' estimatedCOP = a + b * suctionTemp + c * suctionTemp * suctionTemp + _\n ' d * dischargeTemp + e * dischargeTemp * dischargeTemp + _\n ' f * suctionTemp * dischargeTemp\n \n estimatedCOP = (e * dischargeTemp + d + f * suctionTemp) * dischargeTemp + (c * suctionTemp + b) * suctionTemp + a\n End Function\n</code></pre>\n<p>Optimization like this nearly always looks ugly. That's why I've left the original formula as a comment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T15:26:35.217", "Id": "244947", "ParentId": "242722", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:51:25.730", "Id": "242722", "Score": "3", "Tags": [ "performance", "vba", "excel" ], "Title": "User-defined function for estimating coefficient of performance" }
242722
<p>I am scrapping html pages. Part of the page has a table which has acts and sections of those acts mentioned in table format. For some other project I need to convert them to Dictionary. The key values are previously set (in the other project). I want to use the same key values for the dictionary and then replace corresponding sections with each new input. The code I have designed works but I am looking for better way to write it. Presently the code looks quite lengthy. The code: </p> <pre><code>from bs4 import BeautifulSoup as bs, NavigableString openFile = open('/some path/samplePage.html') soup = bs(openFile, 'html.parser') acts = soup.select('#act_table td:nth-of-type(1)') sections = soup.select('#act_table td:nth-of-type(2)') dictionary = {} ipc = 'indian penal code' poa = 'prevention of atrocities' pcso = 'protection of children from sexual' pcr = 'protection of civil rights' if len(acts) &lt; 1: print('no act mentioned') elif len(acts) &lt; 2: act1 = tuple(acts[0].contents) sections1 = tuple(sections[0].contents) elif len(acts) &lt; 3: act1 = tuple(acts[0].contents) sections1 = tuple(sections[0].contents) act2 = tuple(acts[1].contents) sections2 = tuple(sections[1].contents) elif len(acts) &lt; 4: act1 = tuple(acts[0].contents) sections1 = tuple(sections[0].contents) act2 = tuple(acts[1].contents) sections2 = tuple(sections[1].contents) act3 = tuple(acts[2].contents) sections3 = tuple(sections[2].contents) elif len(acts) &lt; 5: act1 = tuple(acts[0].contents) sections1 = tuple(sections[0].contents) act2 = tuple(acts[1].contents) sections2 = tuple(sections[1].contents) act3 = tuple(acts[2].contents) sections3 = tuple(sections[2].contents) act4 = tuple(acts[3].contents) sections4 = tuple(sections[3].contents) else: act1 = tuple(acts[0].contents) sections1 = tuple(sections[0].contents) act2 = tuple(acts[1].contents) sections2 = tuple(sections[1].contents) act3 = tuple(acts[2].contents) sections3 = tuple(sections[2].contents) act4 = tuple(acts[3].contents) sections4 = tuple(sections[3].contents) act5 = tuple(acts[4].contents) if len(acts) == 0: pass # for first act in list elif len(acts) == 1: if ipc in str(act1).lower(): dictionary['IPC'] = sections1 elif poa in str(act1).lower(): dictionary['PoA'] = sections1 elif pcso in str(act1).lower(): dictionary['PCSO'] = sections1 elif pcr in str(act1).lower(): dictionary['PCR'] = sections1 else: dictionary['Any Other Act'] = str(act1).lower() print(dictionary) # for 2nd act in list elif len(acts) == 2: if ipc in str(act1).lower(): dictionary['IPC'] = sections1 elif poa in str(act1).lower(): dictionary['PoA'] = sections1 elif pcso in str(act1).lower(): dictionary['PCSO'] = sections1 else: dictionary['Any Other Act'] = str(act1).lower() if ipc in str(act2).lower(): dictionary['IPC'] = sections2 elif poa in str(act2).lower(): dictionary['PoA'] = sections2 elif pcso in str(act2).lower(): dictionary['PCSO'] = sections2 else: dictionary['Any Other Act'] = act2 print(dictionary) # for 3rd act in list elif len(acts) == 3: if ipc in str(act1).lower(): dictionary['IPC'] = sections1 elif poa in str(act1).lower(): dictionary['PoA'] = sections1 elif pcso in str(act1).lower(): dictionary['PCSO'] = sections1 elif pcr in str(act1).lower(): dictionary['PCR'] = sections1 else: dictionary['Any Other Act'] = str(act1).lower() if ipc in str(act2).lower(): dictionary['IPC'] = sections2 elif poa in str(act2).lower(): dictionary['PoA'] = sections2 elif pcso in str(act2).lower(): dictionary['PCSO'] = sections2 elif pcr in str(act2).lower(): dictionary['PCR'] = sections2 else: dictionary['Any Other Act'] = act2 #for 3rd option if ipc in str(act3).lower(): dictionary['IPC'] = sections3 elif poa in str(act3).lower(): dictionary['PoA'] = sections3 elif pcso in str(act3).lower(): dictionary['PCSO'] = sections3 elif pcr in str(act3).lower(): dictionary['PCR'] = sections3 else: dictionary['Any Other Act'] = act3 print(dictionary) # for 4th act in list elif len(acts) == 4: if ipc in str(act1).lower(): dictionary['IPC'] = sections1 elif poa in str(act1).lower(): dictionary['PoA'] = sections1 elif pcso in str(act1).lower(): dictionary['PCSO'] = sections1 elif pcr in str(act1).lower(): dictionary['PCR'] = sections1 else: dictionary['Any Other Act'] = str(act1).lower() if ipc in str(act2).lower(): dictionary['IPC'] = sections2 elif poa in str(act2).lower(): dictionary['PoA'] = sections2 elif pcso in str(act2).lower(): dictionary['PCSO'] = sections2 elif pcr in str(act2).lower(): dictionary['PCR'] = sections2 else: dictionary['Any Other Act'] = act2 # for 3rd option if ipc in str(act3).lower(): dictionary['IPC'] = sections3 elif poa in str(act3).lower(): dictionary['PoA'] = sections3 elif pcso in str(act3).lower(): dictionary['PCSO'] = sections3 elif pcr in str(act3).lower(): dictionary['PCR'] = sections3 else: dictionary['Any Other Act'] = act3 # 4th Option if ipc in str(act4).lower(): dictionary['IPC'] = sections4 elif poa in str(act4).lower(): dictionary['PoA'] = sections4 elif pcso in str(act4).lower(): dictionary['PCSO'] = sections4 elif pcr in str(act4).lower(): dictionary['PCR'] = sections4 else: dictionary['Any Other Act'] = act4 elif len(acts) == 5: if ipc in str(act1).lower(): dictionary['IPC'] = sections1 elif poa in str(act1).lower(): dictionary['PoA'] = sections1 elif pcso in str(act1).lower(): dictionary['PCSO'] = sections1 elif pcr in str(act1).lower(): dictionary['PCR'] = sections1 else: dictionary['Any Other Act'] = str(act1).lower() if ipc in str(act2).lower(): dictionary['IPC'] = sections2 elif poa in str(act2).lower(): dictionary['PoA'] = sections2 elif pcso in str(act2).lower(): dictionary['PCSO'] = sections2 elif pcr in str(act2).lower(): dictionary['PCR'] = sections2 else: dictionary['Any Other Act'] = act2 # for 3rd option if ipc in str(act3).lower(): dictionary['IPC'] = sections3 elif poa in str(act3).lower(): dictionary['PoA'] = sections3 elif pcso in str(act3).lower(): dictionary['PCSO'] = sections3 elif pcr in str(act3).lower(): dictionary['PCR'] = sections3 else: dictionary['Any Other Act'] = act3 # 4th Option if ipc in str(act4).lower(): dictionary['IPC'] = sections4 elif poa in str(act4).lower(): dictionary['PoA'] = sections4 elif pcso in str(act4).lower(): dictionary['PCSO'] = sections4 elif pcr in str(act4).lower(): dictionary['PCR'] = sections4 else: dictionary['Any Other Act'] = act4 print(dictionary) </code></pre> <p>The HTML code of one of the files is here:</p> <p><a href="https://github.com/sangharshbyss/EcourtsData/blob/master/samplePage.html" rel="nofollow noreferrer">link to the source code</a></p>
[]
[ { "body": "<p>You're repeating <em>a lot</em> of code in this program. It seems like as the length of <code>acts</code> gets larger, you expand to analyzing acts. This is a perfect opportunity for a loop. What I did was get the length of <code>acts</code> at the very beginning, then base my loop of that. Since you always want the last element you find, this works great. I'll explain below what I did in places that seem confusing.</p>\n\n<pre><code>from bs4 import BeautifulSoup as bs\n\nsite_file = open('samplePage.html')\nsoup = bs(site_file, 'html.parser')\n\nacts = soup.select('#act_table td:nth-of-type(1)')\nsections = soup.select('#act_table td:nth-of-type(2)')\ndictionary = {}\n\nipc = 'indian penal code'\npoa = 'prevention of atrocities'\npcso = 'protection of children from sexual'\npcr = 'protection of civil rights'\n\ncode_dict = {ipc: \"IPC\", poa: \"PoA\", pcso: \"PCSO\", pcr: \"PCR\"}\n\nACT_LENGTH = len(acts) if len(acts) &lt; 5 else 5\n\nif len(acts) &gt; 0:\n collected_acts = [tuple(acts[i].contents) for i in range(ACT_LENGTH)]\n collected_sections = [tuple(sections[i].contents) for i in range(ACT_LENGTH)]\nelse:\n print(\"No Act Mentioned\")\n\nfor i in range(ACT_LENGTH):\n act = str(collected_acts[i]).lower()\n accepted = [code_dict[code] for code in code_dict.keys() if code in act]\n for code in accepted:\n dictionary[code] = collected_sections[i]\nprint(dictionary)\n\nsite_file.close()\n</code></pre>\n\n<h1>ACT_LENGTH</h1>\n\n<p>The reason <code>ACT_LENGTH</code> is written that way is because once the length of <code>acts</code> is bigger than <code>5</code>, you only go a set amount instead of the length. Because of this, we want to only loop up to <strong>four</strong> because of how range works. (<code>range(INCLUSIVE, EXCLUSIVE)</code>).</p>\n\n<h1>Use lists!</h1>\n\n<p>Instead of defining new variables based on how big <code>acts</code> is, we can simply use list comprehension to create a list of variables as big as <code>acts</code>.</p>\n\n<h1>Shorten your code with loops</h1>\n\n<p>Instead of checking each individual key with its own <code>if</code> statement, we can organize all the \"accepted\", meaning codes that are in <code>act</code>, into a list and loop through those to add to the dictionary.</p>\n\n<h1>File handling</h1>\n\n<p>It's always good practice to close a file once you're done using it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T02:45:22.873", "Id": "476362", "Score": "0", "body": "Thanks. I haven't tried it. Please give me some time and I will get back to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:55:49.917", "Id": "476399", "Score": "0", "body": "This is \"the answer\", I was wondering how can I use the loop, but the list comprehension solved the issue. Especially two variables the code_dict and accepted are nice idea. Thanks again. I have edited few lines to adjust as per the requirement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T02:41:03.357", "Id": "242725", "ParentId": "242723", "Score": "1" } } ]
{ "AcceptedAnswerId": "242725", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T00:53:29.790", "Id": "242723", "Score": "2", "Tags": [ "python", "python-3.x", "beautifulsoup" ], "Title": "Better way to extract html table to dictionary using beautifulsoup in python" }
242723
<p>I have written the code for implementation of system() function using fork(), exec() and waitpid(). Could someone please review this code and provide feedback. Thanks a lot.</p> <pre><code> #include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;unistd.h&gt; #include&lt;sys/types.h&gt; #include&lt;sys/wait.h&gt; #include&lt;error.h&gt; #include&lt;errno.h&gt; #define size 30 char *get_command(int argc, char *argv[]); int my_system(const char *command); int my_system(const char *command) { pid_t pid; int wstatus = 0; int ret = 0; if (command == NULL) return 1; pid = fork(); if (pid == -1) { return -1; } else if (pid == 0) { ret = execle("/bin/sh", "sh", "-c",command, (char *)NULL); if (ret == -1) return wstatus; } else { ret = waitpid(-1, &amp;wstatus, 0); if (ret == -1) return -1; } return wstatus; } char *get_command(int argc, char **argv) { int i = 0; static char command[size]; if (argc == 1) return NULL; strcpy(command, argv[1]); for (i = 2; i &lt; argc; i++) { strcat(command, " "); strcat(command, argv[i]); } return command; } int main(int argc, char *argv[]) { int ret; char *command; command = get_command(argc, argv); ret = my_system(command); if (ret == 1) printf("Command is NULL, shell is available\n"); else if (ret == -1) printf("Child process could not be created or error in the wait system call\n"); else if (ret == 127) printf("The Child process could not be executed in the shell\n"); else printf("The status of the child process is :%d\n", ret); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T08:29:09.343", "Id": "476529", "Score": "0", "body": "Welcome to CodeReview. While I hope that you get good reviews, I wonder why you've tagged it as [tag:kernel]. Your code is neither part of a kernel nor of a kernel module. Try to keep the tags to the essentials :)" } ]
[ { "body": "<p>Here is my contribution, you are using two functions that are no safe and can create security problems. Im taking about strcpy and strcat, you should use the <strong>strncpy</strong> and <strong>strncat</strong> in order to avoid a buffer overflow on the variable commmands.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T05:35:57.407", "Id": "476790", "Score": "0", "body": "Please don't use `strncat`. Instead use `snprintf`, which is much easier to use correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T05:58:04.320", "Id": "476793", "Score": "1", "body": "`strncpy` and `strncat` are _not_ for string processing, they are for _array_ processing. Look them up in the C standard and note the careful distinction between array and string in their wording. And the footnotes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T09:31:04.850", "Id": "242791", "ParentId": "242727", "Score": "2" } }, { "body": "<p>I think the biggest mistake is the return after the exec. If you reach that point, and return, you have returned to the calling function in the subprocess. Use exit() instead. Note that the value you pass to exit should come out in wstatus. Note also, if execle returns, it must have failed, so don't even both checking the status. (For this to happen, the path must be invalid. Change it for testing, and set it back afterwards.)</p>\n\n<p>The use of execle() is a mistake. You didn't pass an environment. Use execl() instead.</p>\n\n<p>You have at least one case where you return -1 without having set errno. Set errno. (Many cases, something else has already set errno for you.)</p>\n\n<p>One other thing that can bite you: If the caller has made another subprocess, and it terminates while you are waiting for your subprocess, you will return the result of the wrong subprocess. To fix this, pass the pid as the first parameter to waitpid().</p>\n\n<p>As a style issue, I would recommend moving wstatus completely into the last block. And nothing should ever come out of the compound if statement.</p>\n\n<p>As a personal style point: I tend to use switch to test for -1, 0, or other. if statements work equally well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:15:55.263", "Id": "242847", "ParentId": "242727", "Score": "6" } }, { "body": "<p>In addition to the other answers, I'd add a couple of things: </p>\n\n<p>• <code>size</code> is only used in one place. You can just put the number there rather than the macro. It should also be considerably larger than 30. Consider that <code>find /home/user/Desktop/directory</code> is already too long, and that's not even considering long pipelines and loops.<br>\n• In addition, you should perform checking that the command entered is not too long. As it is now, you run the apparent risk of <a href=\"https://en.wikipedia.org/wiki/Buffer_overflow\" rel=\"nofollow noreferrer\">buffer overflow</a>. Even if you protect against that by means of copying a maximum of <code>n</code> bytes, there is still a possible bug that can cause serious problems. If one were to enter <code>rm -Pdrf --no-preserve-root /tmp</code> into their terminal, it would overwrite and delete everything in <code>/tmp</code> as well as deleting <code>/tmp</code> itself. Great. But what if you only executed 30 bytes of that? You'd be left with <code>rm -Pdrf --no-preserve-root /</code> and a really bad day.<br>\n• As a matter of personal preference, I would separate <code>if (pid == -1)</code> from the chain of <code>if - else if - else</code>. If you return -1, you're not executing any of the other code, so it can be rewritten as</p>\n\n<pre><code>if (pid == -1)\n return -1;\nif (pid == 0) //some say (!pid)\n ...\nelse\n ...\n</code></pre>\n\n<p>• Finally, I'd prefer to see command in <code>get_command()</code> be declared globally at the top of the file or, better, <code>malloc()</code>ed since you're returning the pointer anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T22:49:04.053", "Id": "242926", "ParentId": "242727", "Score": "3" } }, { "body": "<p>In <code>get_command</code>, the function name is wrong. It should be <code>build</code> instead of <code>get</code>.</p>\n\n<p>You also forgot to properly escape the parameters.</p>\n\n<pre><code>./my_system printf '%n\\n' 'It'\\''s a nice day.'\n</code></pre>\n\n<p>The above call must output a single line of text.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T05:44:07.537", "Id": "242928", "ParentId": "242727", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T06:53:18.160", "Id": "242727", "Score": "8", "Tags": [ "c", "linux", "unix" ], "Title": "Implementation of system() function in Linux using fork() , exec() and waitpid() system calls" }
242727
<p>I'm trying to write a function that takes a sports bet and returns its Net result.</p> <p>If you are not familiar with betting, an exhaustive test suite should help with understanding what the program is supposed to do. How can I solve this problem in a way distinct from enumerating all of the possible cases?</p> <pre><code>SUPPORTED_BET_TYPES = ['total', 'handicap'] SIDES = ['home', 'away', 'over', 'under'] BET_OUTCOMES = ['Won', 'Lost', 'Cancelled', 'Half Won', 'Half Lost'] def settle_bet(bet_type, side, points, price, bet_amount, home_score, away_score): '''Returns a result of the bet''' if bet_type == 'total': return settle_total_bet(side, points, price, bet_amount, home_score, away_score) elif bet_type == 'handicap': return settle_handicap_bet(side, points, price, bet_amount, home_score, away_score) def settle_total_bet(side, points, price, bet_amount, home_score, away_score): '''Returns Net result of the bet on total''' outcome = determine_total_bet_outcome(side, points, home_score, away_score) if outcome == 'Won': return bet_amount * (price - 1) elif outcome == 'Half Won': return bet_amount * ((price - 1) / 2) elif outcome == 'Cancelled': return 0 elif outcome == 'Half Lost': return bet_amount * (-1 / 2) else: return bet_amount * -1 def determine_total_bet_outcome(side, points, home_score, away_score): '''Returns the appropriate outcome of the bet from BET_OUTCOMES''' total_score = home_score + away_score points_score_diff = points - total_score if points_score_diff == 0: return 'Cancelled' elif points_score_diff == 0.25: if side == 'over': return 'Half Lost' else: return 'Half Won' elif points_score_diff == -0.25: if side == 'over': return 'Half Won' else: return 'Half Lost' elif points_score_diff &gt;= 0.5: if side == 'over': return 'Lost' else: return 'Won' elif points_score_diff &lt;= -0.5: if side == 'over': return 'Won' else: return 'Lost' def test(): # Bets on Total # Won or Lost assert settle_bet('total', 'over', 2.5, 1.90, 100, 3, 2) == 100 * (1.90 - 1) assert settle_bet('total', 'over', 3.5, 1.85, 100, 0, 1) == 100 * -1 assert settle_bet('total', 'under', 2.5, 1.94, 100, 0, 0) == 100 * (1.94 - 1) assert settle_bet('total', 'under', 3.5, 1.75, 100, 1, 3) == 100 * -1 # Won or Lost Or Cancelled assert settle_bet('total', 'over', 3.0, 1.82, 100, 2, 2) == 100 * (1.82 - 1) assert settle_bet('total', 'over', 3.0, 1.82, 100, 1, 2) == 100 * 0 assert settle_bet('total', 'over', 3.0, 1.82, 100, 0, 0) == 100 * -1 assert settle_bet('total', 'under', 3.0, 1.82, 100, 2, 2) == 100 * -1 assert settle_bet('total', 'under', 3.0, 1.82, 100, 1, 2) == 100 * 0 assert settle_bet('total', 'under', 3.0, 1.82, 100, 0, 0) == 100 * (1.82 - 1) # Won or Lost or Half Won or Half Lost assert settle_bet('total', 'over', 2.25, 1.95, 100, 2, 1) == 100 * (1.95 - 1) assert settle_bet('total', 'over', 2.25, 1.90, 100, 0, 0) == 100 * -1 assert settle_bet('total', 'over', 2.25, 1.80, 100, 1, 1) == 100 * (-1 / 2) assert settle_bet('total', 'under', 2.25, 1.95, 100, 2, 1) == 100 * -1 assert settle_bet('total', 'under', 2.25, 1.90, 100, 0, 0) == 100 * (1.90 - 1) assert settle_bet('total', 'under', 2.25, 1.80, 100, 1, 1) == 100 * ((1.80 - 1) / 2) assert settle_bet('total', 'over', 2.75, 1.90, 100, 3, 3) == 100 * (1.90 - 1) assert settle_bet('total', 'over', 2.75, 1.88, 100, 1, 2) == 100 * ((1.88 - 1) / 2) assert settle_bet('total', 'over', 2.75, 1.90, 100, 1, 0) == 100 * -1 assert settle_bet('total', 'under', 2.75, 1.90, 100, 3, 3) == 100 * -1 assert settle_bet('total', 'under', 2.75, 1.88, 100, 1, 2) == 100 * (-1 / 2) assert settle_bet('total', 'under', 2.75, 1.90, 100, 1, 0) == 100 * (1.90 - 1) print("All tests passed.") if __name__ == '__main__': test() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:06:35.000", "Id": "476389", "Score": "0", "body": "Your question is off-topic here, because we require code to be completely working (to the best of the authors knowledge), before we review it. You can ask these kind of questions on stackoverflow.com" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:08:08.413", "Id": "476390", "Score": "0", "body": "The code is working! The tests pass. That's funny, that I asked the same question on stackoverlow and some user suggested that it should have been asken on codereview! Please take a look https://stackoverflow.com/questions/61951015/how-to-write-a-bet-settling-function-in-python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:29:08.470", "Id": "476407", "Score": "0", "body": "\"I couldn't finish settling bets on handicap since it led to some enormous wall of nested if/else statements\". That doesn't sound like the code is working. If your code really is working completely, I suggest to edit your question. That will help to prevent misunderstandings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:33:05.730", "Id": "476408", "Score": "0", "body": "I had deleted unfinished part before posting and posted a complete working program (though without a part that I had initially intended to do) so that formally everything is ok." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:43:14.080", "Id": "476410", "Score": "0", "body": "The problem is that you are writing about a part of the code that you couldn't complete yet, so most people probably won't even read the rest of your question here, because they think it is off-topic. I highly suggest to delete this part. It will help your question to get more attention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:46:27.697", "Id": "476412", "Score": "2", "body": "Fine, I have deleted that part. Feel free to go ahead :)" } ]
[ { "body": "<h2>Tests</h2>\n\n<p>You've written some - great! Keep that up. If you want to add more structure, consider Python's <code>unittest</code> library.</p>\n\n<h2>Unused globals</h2>\n\n<p><code>BET_OUTCOMES</code>, <code>SUPPORTED_BET_TYPES</code> and <code>SIDES</code> are not used. My assumption is that this is related to the other segment of your code that you deleted. If it stays deleted, then delete these, too.</p>\n\n<p>Similarly, this docstring:</p>\n\n<pre><code>'''Returns the appropriate outcome of the bet from BET_OUTCOMES'''\n</code></pre>\n\n<p>is now incorrect.</p>\n\n<h2>Stringly-typed variables</h2>\n\n<p><code>bet_type</code> being either <code>total</code> or <code>handicap</code> should not be represented as a string. It should be represented as an <code>Enum</code>, or maybe if there will remain only two states, a boolean such as <code>is_handicap_bet</code>. The same applies to <code>outcome</code>.</p>\n\n<h2>Negation</h2>\n\n<p><code>bet_amount * -1</code> should be <code>-bet_amount</code>. \n<code>bet_amount * (-1 / 2)</code> should be <code>-bet_amount / 2</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T19:28:01.200", "Id": "476660", "Score": "1", "body": "Thanks for you review!\nGlobals are provided for readers which are not familiar with gambling rather than to be used in the code itself.\n\nThe docstring should be fine because the function returns only the values listed in BET_OUTCOMES.\n\nAgree that stringly-typed variables could be replaced with enum. Enum seems more suitable than boolean because it allows to add other bet types such as \"individual total\" or \"to qualify\".\n\nNegation in tests is used in order to show how the result is obtained." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T02:27:39.107", "Id": "242831", "ParentId": "242728", "Score": "4" } }, { "body": "<p>This problem appears to be a <a href=\"https://en.wikipedia.org/wiki/Poster_child\" rel=\"nofollow noreferrer\">poster child</a> for basic object-oriented programming. But please note that I don't know anything about sports betting, so I'll probably get some of the details wrong. </p>\n\n<p>A good rule of thumb is this: If you find yourself switching on internal data, look for a class instead.</p>\n\n<p>In your case, you switch on <code>bet_type</code>, you switch on <code>outcome</code>, you switch on <code>side</code>, and you switch on <code>points_scored_diff</code>. I'm willing to <em></em> ... bet ... that there are some class behaviors to be found in all that.</p>\n\n<p>Since you aren't using classes in your code, I'm going to assume you might not be familiar with them. So I'll keep this as straightforward as possible. (If you are doing this for homework and forbidden to use classes, you should have mentioned that -- some of this could be tuples with lambdas.</p>\n\n<pre><code>class WagerOutcome:\n \"\"\" Base class for wager outcomes.\n \"\"\"\n def __init__(self, name, price):\n self.price = price\n self.name = name\n\n def __str__(self) -&gt; str:\n return self.name\n\nclass TotalWagerWon(WagerOutcome):\n def __init__(self, price):\n super().__init__(\"Won\", price)\n\n def payout(self, bet_amount: float) -&gt; float:\n return bet_amount * (self.price - 1)\n\n def __str__(self) -&gt; str:\n \"\"\" Stringify this object. Because the price affects the payout for this \n outcome, I am including price in the display.\n \"\"\"\n return f\"{self.name}({self.price})\"\n</code></pre>\n\n<p>You can figure out the rest, I suspect.</p>\n\n<p>With outcomes now a class, let's turn to the bet types. You didn't include any examples of handicap bets, which is unfortunate. Other than simple point handicaps, I can't imagine what else there would be. So I'm ignoring handicap types.</p>\n\n<pre><code>class Wager:\n \"\"\" Base class for all wager types.\n \"\"\"\n def __init__(self, *, type: str, side: str, points: SupportsFloat = None, price: SupportsFloat, amount: SupportsFloat):\n self.type = type\n self.side = side\n self.points = float(points)\n self.price = float(price)\n self.amount = float(amount)\n\nclass WagerTotalHome(Wager):\n \"\"\" Total wager on home team.\n \"\"\"\n def __init__(self, *, price: SupportsFloat, amount: SupportsFloat, points: int = None):\n super().__init__(type='total', side='home', price=price, amount=amount, points=points)\n\n def get_outcome(self, home_points, away_points):\n \"\"\" Determine outcome by points scored. Return a WagerOutcome.\n \"\"\"\n if home_points &gt; away_points:\n return TotalWagerWon(self.price)\n else:\n return TotalWagerLost(self.price)\n</code></pre>\n\n<p>Now I can write a factory function that maps the strings into types:</p>\n\n<pre><code>def make_wager(type, side, points, price, amount) -&gt; Wager:\n \"\"\" Construct and return Wager objects of a type determined by the arguments.\n \"\"\"\n wager_classes = {\n ('total', 'home'): WagerTotalHome,\n ('total', 'away'): WagerTotalAway,\n ('total', 'over'): WagerTotalOver,\n ('total', 'under'): WagerTotalUnder,\n }\n\n klass = wager_classes[(type, side)]\n wager = klass(points=points, price=price, amount=amount)\n return wager\n</code></pre>\n\n<p>Then I can say:</p>\n\n<pre><code>bet = make_wager('total', 'home', price=2, amount=100)\noutcome = bet.get_outcome(3, 0)\npayout = outcome.payout(bet.amount)\n</code></pre>\n\n<p>That last bit is a little shaky: I really shouldn't have to feed in the <code>bet.amount</code> if the <code>outcome</code> is returned by the <code>bet</code>. But I'm not clear where your trouble with handicap bets lies, so I left things loose.</p>\n\n<p>The point, really, is that using objects/classes, I can move the \"wall of if/else\" statements into a collection of discrete behaviors. Once we know the bet type is \"WagerTotalHome\", there is no more need for if/else statements involving the type or the side. All that remains is to determine the outcome of the wager and return that.</p>\n\n<p>Knowing the outcome, there is no need for if/else statements about anything. Simply encode the computation of the payout using the price and bet amount, and return that.</p>\n\n<p>The one remaining bit of complexity is mapping input strings (or dropdown menu items or whatever) onto wager classes. The factory function uses a dictionary of tuples for that, so it's not as bad as it might first seem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T21:01:19.600", "Id": "476666", "Score": "0", "body": "First of all, thanks for taking time to write such a detailed review! \nLet's start with `Outcome` classes and in order to keep things simple lets ignore handicap bets for now and focus on totals, I have tried to go on on your suggestion and create a class for all of the 5 possible outcomes, here is my code: \n https://pastebin.com/DQnr19cU \nAs far as `Wager` class is concerned I don't understand what `*` parameter means in `__init__` method and why `points` parameter has an `int` type whereas it can be 2.5 or 3.25. \nRegarding to `make_wager()`: is it a stand-alone function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T11:08:03.753", "Id": "476710", "Score": "0", "body": "The `*` [froces named args](https://stackoverflow.com/a/14298976/4029014). `points` was `int` because I don't know sports betting -- I'll edit it to `float`. Yes, `make_wager` is an example of a factory function. You could also use a *factory method* on a base class, if you prefer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:31:02.393", "Id": "242853", "ParentId": "242728", "Score": "4" } } ]
{ "AcceptedAnswerId": "242853", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:07:27.013", "Id": "242728", "Score": "4", "Tags": [ "python" ], "Title": "Bet settling function in Python" }
242728
<p>I was doing <a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">3sum question on leetcode</a></p> <h2>Question</h2> <p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p> <p><strong>Note:</strong></p> <p>The solution set must not contain duplicate triplets.</p> <p>Example:</p> <p>Given array nums = <code>[-1, 0, 1, 2, -1, -4]</code></p> <p>A solution set is:</p> <pre><code>[ [-1, 0, 1], [-1, -1, 2] ] </code></pre> <h2>My solution</h2> <p>For this I wrote the following solution but this is giving me <code>Time Limit Exceeded</code> error.</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 threeSum = function(nums) { // Creating triplet memory so there are any duplicates const triplet_memory = {} // num occurrence will have all the numbers in the input array and number of time they occured const num_occurence = {} nums.forEach((element) =&gt; { if (!num_occurence.hasOwnProperty(element)) { num_occurence[element] = 1 } else { num_occurence[element] += 1 } }) // iterating over input array nums.forEach((elParent, indexParent) =&gt; { // Nested loop so that I try all possible combination nums.forEach((elChild, indexChild) =&gt; { if (indexParent !== indexChild) { // decreasing the value of current element from our object // created copied_num_mem so that we don't change main object memeory const copied_num_mem = {...num_occurence} // We are decreasing the elParent and elChild value because for currentSum we are utilizing those value // For example if elParent is 1 and elChild = 2, we would be using those value in our currentSum hence we are decreasing their count by 1 copied_num_mem[elParent] = copied_num_mem[elParent] - 1 copied_num_mem[elChild] = copied_num_mem[elChild] - 1 // multiplying by -1 because suppose we have elParent as -1 and elChild as -1, their sum would give us -2 and we would need the reciprocal of -2 i.e 2 to make it positive const currentSum = (parseInt(elParent) + parseInt(elChild))*-1 // Checking if 2 exist in our copied_num_mem and if yes, it's value is greater than 0 if (copied_num_mem.hasOwnProperty(currentSum.toString()) &amp;&amp; copied_num_mem[currentSum.toString()] &gt; 0) { // 2, -1, -1 and -1, 2, -1 all are triplets, we are sorting it so that the order of triplet is always the same and we are going to then store that triplet in our triplet_memory const tripletInt = [currentSum, parseInt(elParent), parseInt(elChild)].sort((a, b) =&gt; a -b) const tripletStringified = tripletInt.join('/') triplet_memory[tripletStringified] = true } } }) }) const finalErr = [] Object.keys(triplet_memory).forEach(el =&gt; { const elements = el.split('/').map((element) =&gt; { return parseInt(element) }) finalErr.push(elements) }) return finalErr }; console.dir(threeSum([0,0,0])) console.dir(threeSum([-1,0,1,2,-1,-4]))</code></pre> </div> </div> </p> <p>Can someone help me in optimizing the algorithm? I have added comments so it should be easy to understand the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:20:32.850", "Id": "476383", "Score": "0", "body": "Does this actually return sets in the format specified? When I test this, the output is on a single line and not in sets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:29:34.413", "Id": "476385", "Score": "0", "body": "@Mast It does. Made it a code snippet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:33:28.667", "Id": "476386", "Score": "0", "body": "Thank you. The output in the snippet puts *everything* on new lines though, not a line per set as specified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:38:53.253", "Id": "476387", "Score": "0", "body": "@Mast sorry, unable to comprehend what you are saying?" } ]
[ { "body": "<h2>Current code</h2>\n<p>Before discussing the algorithm I want to discuss the current code.</p>\n<p>The code currently uses functional approaches - like <code>forEach()</code> methods. This is great for readability but because a function is called for every iteration of each loop, performance can be worse than a regular <code>for</code> loop - e.g. each function adds to the <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Call_stack\" rel=\"nofollow noreferrer\">call stack</a>.</p>\n<p>The current code also uses <code>hasOwnProperty</code>. For a plain object the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"nofollow noreferrer\"><code>in</code> operator</a> could be used since it doesn't matter if the property would be inherited or not.</p>\n<p>The last block is this:</p>\n<blockquote>\n<pre><code>const finalErr = []\n</code></pre>\n</blockquote>\n<pre><code>Object.keys(triplet_memory).forEach(el =&gt; {\n const elements = el.split('/').map((element) =&gt; {\n return parseInt(element)\n })\n finalErr.push(elements)\n})\nreturn finalErr\n</code></pre>\n<p>It is interesting that there is a <code>.map()</code> call nested inside a <code>.forEach()</code> loop that pushes elements into an array - the latter is the essence of a <code>.map()</code> call. So the <code>.forEach()</code> could be simplified to a <code>.map()</code> call:</p>\n<pre><code>return Object.keys(triplet_memory).map(el =&gt; {\n return el.split('/').map((element) =&gt; {\n return parseInt(element)\n })\n})\n</code></pre>\n<p>This way there is no need to manually create <code>finalErr</code>, push elements into it and then return it at the end.</p>\n<h2>Different Algorithm</h2>\n<p>There are <a href=\"https://codereview.stackexchange.com/search?q=3sum\">multiple posts about this problem on code review</a> (and <a href=\"https://stackoverflow.com/search?q=3sum\">SO as well</a>). This buzzfeed article explains multiple approaches including <a href=\"https://fizzbuzzed.com/top-interview-questions-1/#the-hash-map-solution\" rel=\"nofollow noreferrer\"><em>The hash map solution</em></a> and <a href=\"https://fizzbuzzed.com/top-interview-questions-1/#twopointer\" rel=\"nofollow noreferrer\"><em>the two pointer trick</em></a>, the latter of those two is a great solution.</p>\n<blockquote>\n<h3>Two pointer trick</h3>\n<p>The ‘two pointer trick’ gives a really nice solution to 3sum that doesn’t require any extra data structures. It runs really quickly and some interviewers ‘expect’ this solution (which might be somewhat unfair, but now that you’re seeing it, it’s to your advantage).<br><br>\nFor the two pointer solution, the array must first be sorted, then we can use the sorted structure to cut down the number of comparisons we do. The idea is shown in this picture:<br><br>\n<a href=\"https://fizzbuzzed.com/assets/img/2pointer3sum.svg\" rel=\"nofollow noreferrer\"><img src=\"https://fizzbuzzed.com/assets/img/2pointer3sum.svg\" alt=\"1\" /></a></p>\n</blockquote>\n<blockquote>\n<pre><code>vector&lt;vector&lt;int&gt;&gt; threeSum(vector&lt;int&gt;&amp; nums) {\n vector&lt;vector&lt;int&gt;&gt; output;\n sort(nums.begin(), nums.end());\n for (int i = 0; i &lt; nums.size(); ++i) {\n // Never let i refer to the same value twice to avoid duplicates.\n if (i != 0 &amp;&amp; nums[i] == nums[i - 1]) continue;\n int j = i + 1;\n int k = nums.size() - 1;\n while (j &lt; k) {\n if (nums[i] + nums[j] + nums[k] == 0) {\n output.push_back({nums[i], nums[j], nums[k]});\n ++j;\n // Never let j refer to the same value twice (in an output) to avoid duplicates\n while (j &lt; k &amp;&amp; nums[j] == nums[j-1]) ++j;\n } else if (nums[i] + nums[j] + nums[k] &lt; 0) {\n ++j;\n } else {\n --k;\n }\n }\n }\n return output;\n</code></pre>\n</blockquote>\n<p><sup><a href=\"https://fizzbuzzed.com/top-interview-questions-1/#twopointer\" rel=\"nofollow noreferrer\">1</a></sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-27T20:12:24.837", "Id": "480260", "Score": "0", "body": "Your hashset approach would yield false positives. Your O(1) check would return true even if `c` was from the same index of the input array as `a` or `b`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T21:15:22.127", "Id": "481285", "Score": "0", "body": "@patrickRoberts thanks for the tip - I have updated that section" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T13:07:54.280", "Id": "243664", "ParentId": "242729", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:36:47.543", "Id": "242729", "Score": "4", "Tags": [ "javascript", "programming-challenge", "time-limit-exceeded", "ecmascript-6", "k-sum" ], "Title": "Leetcode three sum in Javascript" }
242729
<p>This is my first test, I think it's testing what I need it to test but wanted to get some feedback.</p> <p>I wanted to test to make sure the controller action returns a view with a certain ViewModel.</p> <p>The code that it will be testing:</p> <p>Controller:</p> <pre><code>public class UserController : Controller { private readonly ILogger&lt;UserController&gt; _logger; private readonly IViewModelService _vmService; public UserController(ILogger&lt;UserController&gt; logger, IViewModelService vmService) { _logger = logger; _vmService = vmService; } public async Task&lt;IActionResult&gt; Index() { return View(await _vmService.GetIndexVM()); } } </code></pre> <p>ViewModel</p> <pre><code>public class UserListVM { public IQueryable&lt;DimUser&gt; UserList { get; set; } } </code></pre> <p>ViewModelService</p> <pre><code>public async Task&lt;UserListVM&gt; GetIndexVM() { return new UserListVM() { UserList = await _userRepo.GetUserList() }; } </code></pre> <p>The Test:</p> <pre><code>public class UserControllerTests { [Fact] public async Task Index_ReturnsAViewResult_WithUserListVM() { // Arrange var logger = new Mock&lt;ILogger&lt;UserController&gt;&gt;(); var vmService = new Mock&lt;IViewModelService&gt;(); var myList = new List&lt;DimUser&gt; { new DimUser() { UserId = 1, FirstName = "Test", Surname = "TestSur", RefNumber = "ABC1111111", DateOfBirth = DateTime.Now } }; vmService.Setup(x =&gt; x.GetIndexVM()).ReturnsAsync(new UserListVM() { UserList = myList.AsQueryable() }); var userController = new UserController(logger.Object, vmService.Object); // Act var result = await userController.Index(); var viewResult = Assert.IsType&lt;ViewResult&gt;(result); var model = Assert.IsType&lt;UserListVM&gt;(viewResult.ViewData.Model); // Assert Assert.IsType&lt;UserListVM&gt;(model); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:53:40.127", "Id": "476419", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If you have additional concerns, please wait a day and upload your revised code as a new question." } ]
[ { "body": "<p>Let's review each code segment one by one:</p>\n\n<pre><code>public class UserController : Controller\n{\n private readonly ILogger&lt;UserController&gt; _logger;\n private readonly IViewModelService _vmService;\n\n public UserController(ILogger&lt;UserController&gt; logger, IViewModelService vmService)\n {\n _logger = logger;\n _vmService = vmService;\n }\n\n public async Task&lt;IActionResult&gt; Index()\n {\n return View(await _vmService.GetIndexVM());\n }\n}\n</code></pre>\n\n<p>I would generally recommend to avoid code like this:</p>\n\n<pre><code>return View(await _vmService.GetIndexVM());\n</code></pre>\n\n<p>It is hard to add proper error handling, add transformation logic, add conditional branching, etc. A better approach would be to separate these two operations:</p>\n\n<pre><code>var indexViewModel = await _vmService.GetIndexVM();\nreturn View(indexViewModel);\n</code></pre>\n\n<hr>\n\n<pre><code>public async Task&lt;UserListVM&gt; GetIndexVM()\n{\n return new UserListVM()\n {\n UserList = await _userRepo.GetUserList()\n };\n}\n</code></pre>\n\n<p>First of all the same applies here as above, do not mix object creation logic and async calls.</p>\n\n<p>Secondly, in this simple code you have repeated four times the underlying collection type, which is an implementation detail. If you need to change that implementation detail in the lower layer that would propagate through several layers. Remember that hiding implementation details will help you minimize the scope of a change. A better approach would be:</p>\n\n<pre><code>public async Task&lt;UsersVM&gt; GetIndexVM()\n{\n return new UsersVM()\n {\n User = await _userRepo.GetUsers()\n };\n}\n</code></pre>\n\n<p>There is another thing, this service now has two responsibilities:\n1) Retrieve data via a lower layer\n2) Transform data to the presentation layer</p>\n\n<p>In other words, this layer is an <strong>adapter</strong> between your presentation layer and repository layer. Generally speaking the service layer is the place where your business logic should reside. Because there is no business logic here, that's why it acts as an adapter.</p>\n\n<p>I have seen the following two approaches regarding object mapping:</p>\n\n<ol>\n<li>Each layer transforms its objects to the lower layer's object\nmodel</li>\n<li>Each layer accepts upper layer's object model and it\ntransforms it into its own model </li>\n</ol>\n\n<p>The first one fits nicely into the n-layer architecture model where each layer only knows about that layer, which is directly beneath it. So, presentation layer knows about service layer. Service layer knows about repository layer.</p>\n\n<p>The second approach violates this rule. Service layer knows about repository layer and knows about presentation layer's domain model. It is not bad, but the first approach (in my opinion) separates the concerns better. </p>\n\n<hr>\n\n<pre><code>public class UserListVM\n{\n public IQueryable&lt;DimUser&gt; UserList { get; set; }\n}\n</code></pre>\n\n<p>Here your naming and data type is not matching. With this name you are stating that it should contain a <code>List</code>, which implies that you could use such operators like <code>Add</code>, <code>Remove</code>, etc. <code>IQueryable</code> does not provide such API. </p>\n\n<p><code>IQueryable</code> is a type, which is used for <em>deferred execution</em>. In other words it indicates that <strong>this is just a query not the materialised form of the query</strong>. The problem with this is that it will execute the query when you somehow iterate through it (via <code>foreach</code> or calling <code>.Count</code>, etc.) If you do this in your view then your repository's <strong>datacontext</strong> might already be disposed.</p>\n\n<p>A better approach would be to expose it like this:</p>\n\n<pre><code>public class UsersVM\n{\n public IList&lt;DimUser&gt; Users{ get; set; }\n}\n</code></pre>\n\n<hr>\n\n<p>Your test's <em>Arrange</em> part looks good, so I will spend some thought on the rest:</p>\n\n<pre><code>// Act\nvar result = await userController.Index();\nvar viewResult = Assert.IsType&lt;ViewResult&gt;(result);\nvar model = Assert.IsType&lt;UserListVM&gt;(viewResult.ViewData.Model);\n\n// Assert\nAssert.IsType&lt;UserListVM&gt;(model);\n</code></pre>\n\n<p>Your <em>Act</em> section should consist <strong>only</strong> of the call of the <code>Index</code> function of the <code>userController</code>. The assertions should go the under the <em>Assert</em> section.</p>\n\n<p>I would also consider to use <code>IsAssignableForm&lt;T&gt;</code> instead of <code>IsType&lt;T&gt;</code>, because the former supports inheritance as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:51:50.490", "Id": "476418", "Score": "0", "body": "Thanks Peter, this is great. I've made some changes based on your suggestions and edited my original post with the revisions if you get a moment at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T12:12:58.663", "Id": "476421", "Score": "0", "body": "@mattfullerdev You are welcome. :D As Mast pointed out you should not change the question with the revised version." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:51:42.490", "Id": "242735", "ParentId": "242731", "Score": "3" } } ]
{ "AcceptedAnswerId": "242735", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T07:49:22.173", "Id": "242731", "Score": "3", "Tags": [ "c#", "asp.net-core", "moq", "xunit" ], "Title": "Testing an action returns a View with a ViewModel using xUnit and Moq" }
242731
<p>I'm still new to C++ and I am very open to any kind of suggestion on how write proper and understandable C++ code. I decided to create a class for the code to have everything closely tided together. Don't know if that was a good idea.</p> <p>About signature scanners (aka. pattern matchers), see <a href="https://en.wikipedia.org/wiki/Pattern_matching" rel="nofollow noreferrer">see wiki</a>. Signature scanners are commonly used in anti-virus. Basically a signature scanner can be used to identify a sequence of bytes that matches a sequence of bytes one already identified.</p> <p>Masks are used to identify which bytes represent wildcards in the signature. If the pattern is "ff45b3" and the mask is "ff??b3" then the second byte, the "45" is a wildcard and should be skipped by the pattern scan function.</p> <p>Main.cpp:</p> <pre><code>int main() { SigScan scan("C:\\SimplePayload.dll"); // could be any dll right now. // Find the MZ DOS header: "MZ", but with a masked '??' scan.FindSignature("4d5a", "4d??", true); scan.PrintDictionary(); // Find the PE file header: "PE". scan.FindSignature("5045", "5045", true); scan.PrintDictionary(); } </code></pre> <p>SignatureScan.h:</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;windows.h&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; #include &lt;map&gt; class SigScan { private: std::string DllFile; // path to dll file. e.g.: "C:\\File.dll" std::string Sig; // full signature: e.g.: "4d5a90" std::string Mask; // full signature incl. mask: e.g.: "4d??90" std::string FirstSigByte; // we start by comparing each byte with the signature's initial bytes. std::string Buffer; // holds the signature found byte by byte. unsigned int i; // is iterating over all bytes. unsigned int j; // is starting to iterate when the initial byte signature is found. unsigned int currentAddress; // the current address of where the currentByte is at. unsigned int fileSize; BYTE* byteData; // contains the binary data std::map&lt;int, std::string&gt; Dictionary; // will be used if "fullscan" is enabled. In case there are more signatures. // Convert byte data to readable string (hex) std::string hexStr(BYTE*, int); // Get current byte std::string CurrentByte(); void CountAddress(unsigned int); // Read file void ReadFile(); // Print address in uppercase hex format with 8 digits. void PrintCurrentAddress(); public: // Prints at what address the signature was found in binary void PrintDictionary(); // Constructor SigScan(std::string); void FindSignature(std::string, std::string, bool); }; </code></pre> <p>SignatureScan.cpp:</p> <pre><code>#include "SignatureScan.h" // Converts bytes to a readable string (hex representation). std::string SigScan::hexStr(BYTE* data, int len) { std::stringstream ss; ss &lt;&lt; std::hex; for (int i(0); i &lt; len; ++i) ss &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; (int)data[i]; return ss.str(); } // Reads binary data byte by byte. std::string SigScan::CurrentByte() { // Wrapper around hexStr, which can otherwise also be used to print // - i and j are adjusting the placement (see the function 'FindSignature'). return hexStr(byteData + i + j, 1); } // Bytes per row. We count for every 16th bytes void SigScan::CountAddress(unsigned int count) { if (count % 16 == 0) { currentAddress = count; } } // Read file void SigScan::ReadFile() { std::ifstream File(DllFile, std::ios::binary | std::ios::ate); auto FileSize = File.tellg(); fileSize = (unsigned int)FileSize; byteData = new BYTE[static_cast&lt;UINT_PTR&gt;(FileSize)]; File.seekg(0, std::ios::beg); File.read(reinterpret_cast&lt;char*&gt;(byteData), FileSize); File.close(); } void SigScan::PrintCurrentAddress() { // Print address in uppercase hex format with 8 digits. std::cout &lt;&lt; std::uppercase &lt;&lt; std::hex &lt;&lt; std::setw(8) &lt;&lt; std::setfill('0') &lt;&lt; currentAddress &lt;&lt; std::endl; } // public: void SigScan::PrintDictionary() { for (auto&amp; x : Dictionary) { std::cout &lt;&lt; "[ Address: " &lt;&lt; std::uppercase &lt;&lt; std::hex &lt;&lt; std::setw(8) &lt;&lt; std::setfill('0') &lt;&lt; x.first &lt;&lt; " | Signature: " &lt;&lt; x.second &lt;&lt; " ]" &lt;&lt; std::endl; } } // Constructor SigScan::SigScan(std::string InDllFile) { DllFile = InDllFile; // saves dll ReadFile(); // takes dll path and store binary data in 'byteData' } void SigScan::FindSignature(std::string Sig, std::string Mask, bool fullscan) { FirstSigByte = Sig.substr(0, 2); // Get the first byte from Sig. Dictionary.clear(); // Clear the dictionary for patterns before initiation. for (i = 0; i &lt; fileSize; i++) { CountAddress(i); // Counts every 16th byte // If first byte of signature is equal to current byte, we may have a pattern. // (e.g.: FirstSigByte: "4d", CurrentByte(): "4d" if (FirstSigByte.compare(CurrentByte()) == 0) { // We compare pair-wise, so we only need half of the iterations for (j = 0; j &lt; (Sig.length() / 2); j++) { // Success if the next byte in signature is equal to current byte if (Sig.substr(j * 2, 2).compare(CurrentByte()) == 0) { // Append "??" if it's mask if (Mask.substr(j * 2, 2).compare("??") == 0) { Buffer.append("??"); } // Append CurrentByte if it's not a mask. else { Buffer.append(CurrentByte()); } } else { // No match anyway, clear buffer and reset Buffer.clear(); break; } } // If mask and buffer are equal (e.g.: "4d??90" == "4d??90" if (Mask.compare(Buffer) == 0) { // If we want to find all patterns if (fullscan) { // Appends address and buffer (holding the signature), then clear buffer and continue. Dictionary.insert(std::pair&lt;int, std::string&gt;(currentAddress, Buffer)); Buffer.clear(); } else { // If we are fine with stopping when one signature is found, break loop. break; } } } } } </code></pre>
[]
[ { "body": "<h2>Overall Observations</h2>\n<p>It is important to remember when writing code professionally that you may not be the only one writing the code or maintaining and debugging the code. If the project is a high priority then there may be a team of programmers working on it. If the code is shipped, it may have a life span of a decade or more and you may not still be at the company (think winning the lottery or getting a better paying job with another company). Code should be easy to read, write, and be maintained by others.</p>\n<p>The file extension <code>.dll</code> has a very specific meaning in the Microsoft Windows world, it is a Dynamically Loaded Library (DLL), it would be less confusing for anyone who has to maintain the code if the signature data file had a different file extension. By definition on Windows platforms you are linking your code to <code>.dll</code> files such as the C++ STL files so that it can run. There are <a href=\"https://docs.microsoft.com/en-us/windows/win32/dlls/using-run-time-dynamic-linking\" rel=\"nofollow noreferrer\">special functions for loading DLL files at runtime</a>. If you are scanning for virus signatures, then this program should also be able to search other types of files such as <code>.exe</code>, <code>.doc</code>, <code>.docx</code>, etc. and not just <code>.dll</code>.</p>\n<p>Generally in when editing C++ programs one uses an <a href=\"https://www.codecademy.com/articles/what-is-an-ide\" rel=\"nofollow noreferrer\">Interactive Development Environment (IDE)</a> such as <code>Visual Studio</code>, <code>eclipse</code> or <code>CLion</code>. These IDEs provide wizards for creating classes, and will automatically add header files and source files to the program that match the exact name of the class. For the files to have the same name as the class makes it easier for people who have to maintain the code to find the source code for the class. In this code the name of the header and source files are different from the name of the class and that can be confusing.</p>\n<h2>Private Versus Public in C++ Classes</h2>\n<p>Given the current organization of the file, where the <code>private</code> variables and functions precede the <code>public</code> variables and functions the keyword <code>private</code> is not required because by default all variables and functions are private in a C++ Class, this is different from a <code>struct</code> where all variables and functions are public by default.</p>\n<p>That said, in object oriented programming the public interfaces in an object declaration are generally listed first so that the users of the class (other developers that may be working in parallel to you) can find the public interfaces quickly. In most of the C++ code I have seen the constructors and destructors are listed first (when they exist).</p>\n<p>The function organization in <code>SignatureScan.cpp</code> should list Constructors first, then destructors (when needed), then the public functions, and finally the private functions.</p>\n<p>Very short public or private functions that probably won't be modified don't need to be in the <code>.cpp</code> file, they can be in the header file. Examples of these kinds of functions <code>std::string SigScan::CurrentByte()</code> and <code>void SigScan::CountAddress(unsigned int count)</code>. Doing this will allow an optimizing compiler to decide what should be inlined so that the code will run faster.</p>\n<h2>Header Files</h2>\n<p>Within header files, only include header files that are necessary for the code to compile, this will decrease the compile / build time for those source files that include the header file. In the code presented, there are 6 header files included but only 3 of these files are necessary for the code to compile in a source file that includes the header file (<code>windows.h</code>, <code>string</code> and <code>map</code>). Include the other headers necessary in the source file <code>SignatureScan.h</code>.</p>\n<h2>Variable Names</h2>\n<p>There are 2 private variables declared in the header file that have questionable names, <code>i</code> and <code>j</code>. This forced added comments in both the header file and the source file. Write self documenting code as much as possible using more descriptive variable names so that comments are not as necessary. The problem with comments is that they also need to be maintained, and therefore add cost to the maintenance of the software.</p>\n<p>Based on my earlier comment about DLLs, the variable name could be changed to <code>fileToScan</code>.</p>\n<p>The variable names in the function prototypes are important, especially in the <code>public</code> function prototypes. These variable names will give the users of the functions an idea of what the variable is to be used for.</p>\n<h2>Use C++ Container Classes Rather Than Old Style C Arrays or Pointers</h2>\n<p>The class definition of SigScan contains the variable declarations</p>\n<pre><code> unsigned int fileSize;\n\n BYTE* byteData; // contains the binary data\n</code></pre>\n<p>While <code>fileSize</code> may be needed for multiple reasons, the most important reason seems to be that it is the size of <code>byteData</code>. There are 2 different ways these 2 variables could be combined into 1 complex variable, the first would be to use the C++ type <code>array</code> and the second would be to use the C++ type <code>vector</code>. On of the values of using a C++ container type is being able to pass both variables in a single parameter. A second value of using a C++ container type is that you can use a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range based for loop</a> that would reduce the code necessary in <code>std::string SigScan::hexStr(BYTE* data, int len)</code> and possibly run faster because it is using <code>iterators</code>.</p>\n<pre><code>std::string SigScan::hexStr(std::vector&lt;BYTE&gt; data)\n{\n std::stringstream ss;\n ss &lt;&lt; std::hex;\n\n for (BYTE byte: data)\n {\n ss &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; (int)byte;\n }\n\n return ss.str();\n}\n</code></pre>\n<p>Note that there is no need to specify the index <code>i</code> in the above loop.</p>\n<p>Another reason is that raw pointers are frowned upon in modern C++ because they lead to bugs.</p>\n<p>I may have time to review <code>void FindSignature(std::string, std::string, bool)</code> later, but there is enough information now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T17:01:20.553", "Id": "476459", "Score": "0", "body": "Thank you so much, @pacmaninbw. I noted everything you said. Also, it makes sense.\n\nIf you have time for `FindSignature` I'd appreciate it, but there's more than enough to get me started right now. Thanks again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T19:41:17.457", "Id": "476472", "Score": "0", "body": "The paragraph about the missing destructor is misleading up to wrong: If not specified otherwise, every class has a destructor. For classes which do not deal with ownership, it is encouraged to use [the rule of zero](https://www.fluentcpp.com/2019/04/23/the-rule-of-zero-zero-constructor-zero-calorie/). Explicitly defaulting the destructor even implicitly deletes the move-constructors (see same link), which is very bad for a class holding something large like a map! Please correct your answer accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:32:31.650", "Id": "476475", "Score": "0", "body": "@EmmaX anything else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T23:37:05.243", "Id": "476498", "Score": "0", "body": "@pacmaninbw I’m not aware of any reason why iterators would be faster than indexes in cases of contiguous memory, but one should prefer iterators nonetheless due to being more generic. Other than that I’m quite fond of your review." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:44:16.467", "Id": "242760", "ParentId": "242733", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:16:24.303", "Id": "242733", "Score": "3", "Tags": [ "c++" ], "Title": "Signature scanner (aka. pattern matcher), is there are more beautiful way to write this?" }
242733
<p>Currently my code works but I wanted to know if I'm going about this the right way. I want to be able to individually call variables from method 'data_by_name' in 'otherfile.py' . At the moment I import 'otherfile.py' and put the elements into a list within 'main.py' and use tuple unpacking to give each element a variable name.</p> <p>Could I go about this a better way?</p> <p>otherfile.py</p> <pre><code>import requests import json API_KEY = "XXX" PROJECT_TOKEN = "XXX" RUN_TOKEN = "XXX" class Data: def __init__(self, api_key, project_token): self.api_key = api_key self.project_token = project_token self.params = {"api_key":api_key} self.get_data() def get_data(self): r = requests.get('https://www.parsehub.com/api/v2/projects/PROJECT_TOKEN/last_ready_run/data', params={"api_key": API_KEY}) self.data = json.loads(r.text) def data_by_name(self,country): data = self.data['country'] for content in data: if content['Cname'].lower() == country.lower(): print(content) name = content['Cname'] pop = content['population'] popRank = content['popRank'] growth = content['growthRate'] per = content['worldPer'] area = content['area'] capital = content['capital'] region = content['region'] gpd = content['gpd'] return(name,pop,popRank,growth,per,area,capital,region,gpd) if __name__ == '__main__': data = Data(API_KEY,PROJECT_TOKEN) data.data_by_name('Russia') </code></pre> <p>main.py</p> <pre><code>from ParsehubCode import Data,API_KEY,PROJECT_TOKEN country = Data(API_KEY,PROJECT_TOKEN) test = country.data_by_name("china") list1 = [] for element in test: list1.append(element) for x in list1: A,B,C,D,E,F,G,H,I = list1 print(A,B,C) </code></pre> <p>country.json</p> <pre><code>{ "country": [ { "Cname": "China", "name": "China Population 2020 (Live)", "population": "1,438,719,354", "popRank": "1", "growthRate": "0.39%", "worldPer": "18.47%", "area": "9,706,961 km²", "capital": "Beijing", "region": "Asia", "gpd": "$10,746.78" } { </code></pre>
[]
[ { "body": "<p>Instead of</p>\n\n<pre><code>list1 = []\nfor element in test:\n list1.append(element)\nfor x in list1:\n A,B,C,D,E,F,G,H,I = list1\n</code></pre>\n\n<p>you could simply write </p>\n\n<pre><code>A,B,C,D,E,F,G,H,I = test\n</code></pre>\n\n<hr>\n\n<p>Regardless, here's a slightly different approach.</p>\n\n<p>Assuming that the input <code>json</code> structure is <code>{ 'country': [{ }, ..., { }] }</code>, \nI'd slightly modify <code>self.data</code>:</p>\n\n<pre><code> self.data = {country['Cname'].lower(): country\n for country in json.loads(r.text)['country']}\n</code></pre>\n\n<p>then access this dictionary whenever required. Possibly by overwriting <code>__getitem__</code>:</p>\n\n<pre><code>def __getitem__(self, key):\n return self.data[key.lower()]\n</code></pre>\n\n<p>Then you can access the inner dictionary using <code>[ ]</code>:</p>\n\n<pre><code>GlobalDataLoader(API_KEY,PROJECT_TOKEN)['china']\nGlobalDataLoader(API_KEY,PROJECT_TOKEN)['china']['population']\n</code></pre>\n\n<p>Here I've renamed the <code>Data</code> class: I don't expect the constructor of a class named <code>Data</code> to access the internet, and the data seems to be global.\nStill, I'd remove the <code>self.get_data()</code> call from <code>__init__</code>.</p>\n\n<p>On the other hand, if you are not planning to reuse the <code>(API_KEY, PROJECT_TOKEN)</code> for a specific <code>GlobalDataLoader</code> instance, then I wouldn't store these in the instances. Instead do something like</p>\n\n<pre><code>data = GlobalDataLoader(project_secrets)\n</code></pre>\n\n<p>where</p>\n\n<pre><code>class GlobalDataLoader: \n def __init__(self, project_secrets):\n self.load_data(project_secrets)\n\n def load_data(self, project_secrets):\n url = f\"https://www.parsehub.com/api/v2/projects/{project_secrets['project_token']}/last_ready_run/data\"\n r = requests.get(url, params={\"api_key\": project_secrets['api_key']})\n self.data = {country['Cname'].lower(): country\n for country in json.loads(r.text)['country']}\n\n def __getitem__(self, key):\n return self.data[key.lower()]\n</code></pre>\n\n<hr>\n\n<p>That being said, don't hard-code secrets into the source code.</p>\n\n<pre><code>API_KEY = \"XXX\"\nPROJECT_TOKEN = \"XXX\"\nRUN_TOKEN = \"XXX\"\n</code></pre>\n\n<p>You don't want this as a habit when you start using version control systems. Store these in a separate file. If you <em>have to</em> store that in a VCS, then encrypt it (e.g. use <code>gitcrypt</code>). </p>\n\n<p>To reuse the idea of a wrapped dictionary, you could write a</p>\n\n<pre><code>class ProjectSecretsLoader:\n def __init__(self, config_file_path):\n self.load_config(config_file_path)\n\n def load_config(self, config_file_path):\n self.config_data = dict() # TODO\n\n def __getitem__(self, key):\n return self.config_data[key]\n</code></pre>\n\n<p>then do</p>\n\n<pre><code>config_file_path = \"...\"\nproject_secrets = ProjectSecretsLoader(config_file_path)\ndata = GlobalDataLoader(project_secrets)\n</code></pre>\n\n<hr>\n\n<p>Last, but not least <code>requests.get</code> might fail, <code>json.loads</code> might fail. The result of <code>json.loads</code> might not have the structure you expect, or might be missing the country you will eventually try to look up, etc. In these cases specific exceptions will be raised, which ideally should be handled, otherwise the program will crash.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T12:46:18.477", "Id": "476425", "Score": "1", "body": "It's somewhat common to have secrets in a `secrets.py` this way you can just `import secrets` and then do `GlobalDataLoader(secrets)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T12:30:34.150", "Id": "242745", "ParentId": "242734", "Score": "4" } }, { "body": "<p>Since you download the data about all countries from the API, why not save it such that getting the countries by name is easy and fast? Like a dictionary with <code>content['Cname'].lower()</code> as key?</p>\n\n<pre><code>class Data:\n keys = ['Cname', 'population', 'popRank', 'growthRate', 'worldPer', 'area',\n 'capital', 'region', 'gdp']\n\n def __init__(self, api_key, project_token):\n self.url = f'https://www.parsehub.com/api/v2/projects/{project_token}/last_ready_run/data'\n self.params = {\"api_key\": api_key}\n self.get_data()\n\n def get_data(self):\n r = requests.get(self.url, params=self.params)\n r.raise_for_status()\n self.data = r.json()\n self.countries = {item['Cname'].lower():\n {key: item[key] for key in self.keys}\n for item in self.data}\n\n def data_by_name(self,country):\n return self.countries(country.lower())\n</code></pre>\n\n<p>Note that I did not replicate your returning of a tuple, but just returned the dict.If you do need them in local variables, you have multiple options:</p>\n\n<ol>\n<li>Just use <code>test[\"gdp\"]</code> instead of <code>I</code>.</li>\n<li>Use a <code>collections.namedtuple</code> as return value and do <code>test.gdp</code>.</li>\n<li>Use <code>locals().update(test)</code> and the afterwards just <code>gdp</code>.</li>\n</ol>\n\n<p>The first two I would prefer over the third and over your code.</p>\n\n<p>Note that <code>A,B,C,D,E,F,G,H,I</code> are really bad names. For one, they don't follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends <code>lower_case</code> for variables and functions. It also does note make it clear what each variable contains.</p>\n\n<hr>\n\n<p>This</p>\n\n<pre><code>test = country.data_by_name(\"china\")\nlist1 = []\nfor element in test:\n list1.append(element)\nfor x in list1:\n A,B,C,D,E,F,G,H,I = list1\n</code></pre>\n\n<p>can also be shortened to</p>\n\n<pre><code>A,B,C,D,E,F,G,H,I = country.data_by_name(\"china\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T12:31:04.427", "Id": "242746", "ParentId": "242734", "Score": "3" } }, { "body": "<ol>\n<li><p><code>self.data</code> is a bad way to cache data. There are two ways to address this.</p>\n\n<ul>\n<li>Leave <code>get_data</code> roughly as is and use <a href=\"https://docs.python.org/3/library/functools.html#functools.cached_property\" rel=\"nofollow noreferrer\"><code>functools.cached_property</code></a>.</li>\n<li>Take a url segment and cache it with <a href=\"https://docs.python.org/3.8/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>functools.lru_cache</code></a> or <a href=\"https://beaker.readthedocs.io/en/latest/caching.html#decorator-api\" rel=\"nofollow noreferrer\">Beaker</a>. Beaker is probably better as it allows you to have more than just an LRU cache.</li>\n</ul></li>\n<li><p>We can use a <a href=\"https://requests.readthedocs.io/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\">session object</a> to remove the need for passing <code>params</code> in <code>get_data</code>. It also gives some other nice benefits, but we're not really using them here.</p></li>\n<li><code>data_by_name</code> doesn't belong on <code>Data</code>. This should be created and stored outside the class.</li>\n</ol>\n\n<p><code>parsehub.py</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\nimport requests\n\n\nclass Parsehub:\n def __init__(self, api_key, project_token):\n self._session = s = requests.Session()\n s.params.update({'api_key': api_key})\n self._project_token = project_token\n\n @functools.lru_cache\n def get(self, path):\n return self._session.get(\n f'https://www.parsehub.com/api/v2/projects/'\n f'{self._project_token}'\n f'/{path}'\n )\n\n def get_data(self):\n # Code to format the countries to your desired format goes here\n return self.get('last_ready_run/data').json()\n</code></pre>\n\n<p><code>__main__.py</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from .settings import API_KEY, PROJECT_TOKEN\nfrom .parsehub import Parsehub\n\n\ndef main():\n parse_hub = Parsehub(API_KEY, PROJECT_TOKEN)\n # The other answers have shown how to get this in the format you want.\n countries = {\n country['Cname'].lower(): country\n for country in parse_hub.get_data()\n }\n country = countries['russia']\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:07:23.737", "Id": "476440", "Score": "0", "body": "You are missing the `json` conversion, probably in `get_data`. Otherwise, I agree, this is more maintainable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:09:18.503", "Id": "476441", "Score": "2", "body": "@Graipher Aw shucks, how'd I miss that! Thank you :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:54:20.520", "Id": "242749", "ParentId": "242734", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T08:50:13.063", "Id": "242734", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Is there a better way to retrieve variables from class method" }
242734
<p>I have written a timer class.</p> <p>Here it is in all its &quot;glory&quot; with some functions around it to test it: <a href="https://rextester.com/LQSXUA43758" rel="nofollow noreferrer">https://rextester.com/LQSXUA43758</a></p> <p>Below is the class on its own, note it also relies on another class called stop_watch (which can be seen in the link), but stop watch is quite simple and just relies on <code>std::chrono::steady_clock::now();</code> to get time differences.</p> <p>The items I want to check (but happy for all of it to be reviewed!) are:</p> <ul> <li>With <code>cv.wait_for(...</code> do i need the loop around it to catch spurious wakes? I was reading this: <a href="https://stackoverflow.com/questions/31871267/how-does-condition-variablewait-for-deal-with-spurious-wakeups">https://stackoverflow.com/questions/31871267/how-does-condition-variablewait-for-deal-with-spurious-wakeups</a>, but I could not quite fathom the answer. It suggests that with the predicate I do not need the spurious-catch loop around it?</li> <li>I am re-calculating the amount of time to wait each time based on the total time so that if the timer is running continuously (i.e. not one shot) it does not lose time - just want to check this approach.</li> <li>The timeout handler function is called within the timer thread. This is ok if the handler just sets a flag or puts an event on a queue - but what if someone wants to do a load of work here? Like what if I set timeout to 100ms and the work takes 110ms? - should I try to run that in another thread detatched?</li> <li>Finally, the wait time calculation is working well, but I am not sure if I need to worry about if the time calculated is negative. In the previous point I mentioned if the work took longer then the timeout, that means on the next iteration the time to wait calculation might -10ms! - what then?</li> </ul> <h3>Timer class:</h3> <pre><code>/// @brief timer class to call a callback function after a specified amount of time has expired class timer { private: /// the timer thread std::thread timer_thread; /// atomic bool used to stop the timer std::atomic&lt;bool&gt; timer_running; /// condition var mutex std::mutex mtx; /// condition var used for waiting std::condition_variable cv; public: /// @brief Construct a new timer object timer() = default; /// @brief Destroy the timer object - ensures the timer has stopped ~timer() { stop(); } /// @brief Starts the timer /// @param timeout_ms the amount of time until the timer expires in milliseconds /// @param timeout_handler the function callback which is called if/when the timer expires template &lt;typename Functor&gt; void start(unsigned int timeout_ms, const Functor &amp;timeout_handler, bool oneshot = true) { /// Start the timer_running = true; timer_thread = std::thread([timeout_handler, timeout_ms, oneshot, this]() { stopwatch sw; uint64_t interval_ms = static_cast&lt;uint64_t&gt;(timeout_ms); // Keep a running total of the time required time to wait uint64_t total_time_ms = 0; // Keep running the timer until it is no longer running while (timer_running) { // increment the total time required to wait by the interval total_time_ms += interval_ms; // Keep waiting until we have reached the elapsed time (in case of spurious wake) // or the timer is stopped. Note the wait_for will handle timer_running = false // so we don't need to check that in this loop while (sw.get_elapsed_time() &lt; total_time_ms) { std::unique_lock&lt;std::mutex&gt; lock{mtx}; // Re-calculate the time we need to wait for so that we are not losing time // returns true if timer was stopped, returns false if timer expired if (cv.wait_for(lock, std::chrono::milliseconds{total_time_ms - sw.get_elapsed_time()}, [this] { return (bool)!timer_running; })) { // timer stopped return; } } // Timer expired - Call timeout handler timeout_handler(); // if oneshot stop the timer if (oneshot) { return; } } }); } /// @brief Stops the timer - the callback will not be called. void stop() { // Set the running flag to false so the timer does not continue timer_running = false; // wake the timer cv.notify_all(); // Join the thread if (timer_thread.joinable()) { timer_thread.join(); } } }; </code></pre> <p>All hints / tips most welcome :)</p>
[]
[ { "body": "<p>I see two main problems in this approach</p>\n\n<ol>\n<li>Creating a thread for each timer is extremely wasteful</li>\n<li>Running the callback synchronously with the timer can lead to all sorts of problems as you mention.</li>\n</ol>\n\n<p>The usual design for a high-performance timer is to have a single thread that waits for the next timer to fire and queues the callback to some work-queue. The examples would be boost::asio::deadline_timer or windows' timerQueueTimer</p>\n\n<p>Your time calculation of course would not work, there is no way you can expect a clock time to match exactly with any constant and you are going to get negative values. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:47:28.940", "Id": "476394", "Score": "0", "body": "ah, that makes sense. The \"worker\" queue (I assume) would be on another thread - I could implement that in another class and add it as a member into the timer class. Then I assume that when the timer is stopped I would need to also empty the queue of any remaining items (at least these are my first thoughts) thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:49:39.787", "Id": "476397", "Score": "0", "body": "Also with regard to the time calculation. Just added some tests to try a worker that takes 1000ms with a timer of 100, of course the timer can't keep up, but it handles the negative value (by luck, not design) due to the inner while loop: `while (sw.get_elapsed_time() < total_time_ms)` - that was meant to stop spurious wakes, but seems to go a good job catching potentially negative time calcs :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:37:15.437", "Id": "242740", "ParentId": "242738", "Score": "1" } }, { "body": "<blockquote>\n <p>With <code>cv.wait_for(...</code> do i need the loop around it to catch spurious wakes?</p>\n</blockquote>\n\n<p>You should've read the answer better or checked the C++ reference for <code>std::condition_variable</code>. When you supply a predicate (the condition lambda) to <code>wait, wait_for, wait_until</code> the function already has a loop inside it to deal with spurious wake ups. It will exit only once the condition is met or the timeout was reached.</p>\n\n<blockquote>\n <p>Finally, the wait time calculation is working well, but I am not sure if I need to worry about if the time calculated is negative. In the previous point I mentioned if the work took longer then the timeout, that means on the next iteration the time to wait calculation might -10ms! - what then?</p>\n</blockquote>\n\n<p>You decide what to do when the time passed, either trigger the handler immediately or skip for the next round. The timer class is meaningless if executing the handler takes more time than the trigger time.</p>\n\n<p>Note 1: To avoid dealing with negative times - use <code>wait_until</code> and supply a time point instead of the unnecessary work around calculation. Just store a <code>steady_clock::time_point</code> and increment by the duration.</p>\n\n<p>Another solution is to have access to an executor class (a thread pool) and request the executor class to execute the task given by the handler. So <code>timer</code>'s thread doesn't do anything besides waiting.</p>\n\n<p>Note 2: It is advisable to not mix synchronizations of <code>std::atomic</code> with <code>std::mutex</code> as from time to time there are timing issues easy to miss. You should have <code>timer_running</code> be just a <code>bool</code> and use the mutex <code>mtx</code> for synchronizing it. This is a general rule. In this timer class it might cause only mild issues but in some cases it might result in serious and hard-to-catch errors as they are extremely rare and hard to reproduce. In your timer class it might cause the timer to wait the whole timeout even if <code>stop</code> method was called and only then exiting.</p>\n\n<hr>\n\n<p>Overall design: it is wasteful to have a separate thread for just a timer. Consider making a singleton class (alarm clock?) with a single thread that deals with all the timers you run and wakes them up on when asked. It should only triggers waking up not executing the handlers. It can also be utilized for other classes and services.</p>\n\n<p>Note: Honestly, I don't like singletons and prefer context pattern but it requires a throughout integration of the context into the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T11:59:14.910", "Id": "476711", "Score": "0", "body": "Thanks ALX23z. Some really interesting points and concepts here for me to start adding into my timer. I have a few questions though - i'll add each as a separate comment..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T11:59:21.180", "Id": "476712", "Score": "0", "body": "1. I can't find any reference to issues with mixing atomic and mutex. I don't see atomics as a synchronisation mechnism at all, it just guarantees you can write / read to the value in multiple threads without corruption." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T12:02:40.473", "Id": "476713", "Score": "0", "body": "2. (and more importantly for me) I just don't see how you can have a timer without a thread. I totally get your alarm clock idea, timer can say alarm_clock, wake me in 100ms, that is all good... but now the timer actually has to sleep. If the timer has to sleep, that means its thread has to sleep. If the timer has no thread of its own, then this must be the thread that owns the timer object. Lets call it the main thread. So in main thread if I do `m_timer.start(1000)` (milliseconds) if the timer has no thread, it will block main for 1000 ms. Can you explain your concept a bit further? thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:46:41.883", "Id": "476752", "Score": "0", "body": "@code_fodder (1) I didn't write it accurately. It isn't about mixing mutexes and atomics. It is about `condition_variable`. `condition_variable` is meant to utilize a given mutex for data synchronization. But you modify the data it accesses via an unrelated atomic variable that no clue about mutex. This is what leads to the issues. The mutex is needed to ensure that condition variable operates properly and it is needed that data of the condition isn't modified while the mutex is locked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:11:34.363", "Id": "476756", "Score": "0", "body": "@code_fodder (2) Yeah, you still need some thread to wait for the alarm clock - sometimes this is the main thread as this is what you want. However, you can also utilize the idea of executors. Make a thread pool, give the alarm clock access to the executor and make it schedule a task in the thread pool once the time is reached. This way you have a fixed number of threads for all timers and whoever else utilizes the thread pool (1 for alarm clock and #core_count for the executors) for the whole duration of the program. That being said, you'll need some API to check for status of executed tasks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T22:18:41.577", "Id": "476776", "Score": "0", "body": "Thanks for the clarification. (1) I have read up a bit more on this, so I think all you are saying (and matches what i was reading) is that I need to protect writer to my bool (regardless of atomic-ness) since it is used in the cond-var wait loop. (2) Since I need to use threads somewhere!, I will stay with my 1 thread per timer for now and leave thread pools to a future enhancement - I just don't have that many timers : )" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T11:50:50.890", "Id": "242794", "ParentId": "242738", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:09:38.490", "Id": "242738", "Score": "1", "Tags": [ "c++", "c++11", "timer" ], "Title": "sleepless timer that does not lose time and handles spurious wakes" }
242738
<p>I tried a <a href="https://www.hackerrank.com/challenges/journey-to-the-moon" rel="nofollow noreferrer">Hackerrank problem</a> and it gives me a successful message, it works fine for Hackerrank criteria.</p> <blockquote> <p>The member states of the UN are planning to send <strong>2</strong> people to the moon. They want them to be from different countries. You will be given a list of pairs of astronaut ID's. Each pair is made of astronauts from the same country. Determine how many pairs of astronauts from different countries they can choose from.<br> For example, we have the following data on 2 pairs of astronauts, and 4 astronauts total, numbered <strong>0</strong> through <strong>3</strong>.<br> 1 2, 2 3<br> Astronauts by country are [<strong>0</strong>] and [<strong>1,2,3</strong>]. There are <strong>3</strong> pairs to choose from: [<strong>0,1</strong>], [<strong>0,2</strong>] and [<strong>0,3</strong>].</p> </blockquote> <p>There I used a DFS method to check for the connected components and get the answer using the sum of the products of each disjoint elements (<span class="math-container">\$ab + ac + ad + bc + bd + cd = ab + (a+b)c + (a+b+c)d\$</span>).</p> <p>Although it passes all test cases in the Hackerrank platform as required for 10^5 nodes, it fails in time for graphs with more nodes (for 10^9) as it takes more than 1.5ms of time. Can I have some improvement here to work this for more nodes?. As I have already mentioned, this works perfectly for Hackerrank and it passed all. But for my knowledge I need to have some further improvements to work in linear time.</p> <p>Here's my code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; #define For(i,a,n) for (int i=a; i&lt;n; i++) typedef vector&lt;int&gt; vi; // returns no. of connected nodes to a given node int connected(int node, vector&lt;vi&gt; &amp;adj, bool visited[]){ int count = 0; for(auto x: adj[node]){ if(visited[x]) continue; visited[x] = true; count += connected(x, adj, visited) + 1; } return count; } void dfs(int nodes, vector&lt;vi&gt; &amp;adj, bool visited[]){ long long ans = 0; visited[nodes] = true; int current_sum = connected(nodes, adj, visited) + 1; while(nodes--){ if(visited[nodes]) continue; visited[nodes] = true; int out = connected(nodes, adj, visited) + 1; ans += current_sum*out; current_sum += out; } cout&lt;&lt; ans; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int a,b,edges,nodes; cin&gt;&gt;nodes&gt;&gt;edges; bool visited[nodes]; fill(visited, visited + nodes, 0); vector&lt;vi&gt; adj(nodes); // adj[i] gives the directly connected nodes to i while(edges--){ cin&gt;&gt;a&gt;&gt;b; adj[a].push_back(b); adj[b].push_back(a); } dfs(nodes-1, adj, visited); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:58:19.770", "Id": "476420", "Score": "2", "body": "Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please include a complete description of the challenge as well. Links can rot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T22:16:44.040", "Id": "476492", "Score": "0", "body": "`[the code presented] fails for graph with more nodes` *fails to provide the correct answer* or *fails to meet some hackerrank.com criterion*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T08:21:24.737", "Id": "476526", "Score": "0", "body": "It is fine if the code does not work for large graphs, if it works in principle and only fails because it runs out of time/ressources. In that case there are the [tag:time-limit-exceeded] and [tag:memory-optimization] tags, respectively." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T08:25:10.437", "Id": "476527", "Score": "0", "body": "You might also want to contact a moderator if you want to merge your two accounts (i.e. the one you used to ask the question and the one you use to edit it), because otherwise you will need to wait for approval for every edit you make. Just click the `flag` link under the question and use a custom \"in need of moderator intervention\" flag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T10:29:03.130", "Id": "476536", "Score": "0", "body": "(Reputation should not be keeping you from commenting to a post of your own.)" } ]
[ { "body": "<p>It would be good to have some test graph to try the code, I've generated an overly simple graph (one edge per node, 7MB file generated) using the following Python script (output redirected to file):</p>\n\n<pre><code>nodes = 1000000\nedges = nodes/2\nprint(\"{} {}\".format(nodes, edges))\nfor i in range(1, nodes+1, 2):\n print(\"{} {}\".format(i, i+1))\n</code></pre>\n\n<p>Additionally, in order to profile data in Visual Studio, I've done following changes:</p>\n\n<ol>\n<li>At the start of main(), I've redirected cin to read from input file (needed to automate profiling):\nstd::ifstream in(\"graph.dat\");\nstd::cin.rdbuf(in.rdbuf());</li>\n<li>To placate Visual Studio C++ compiler, I've changed the visited array to:\n bool *visited = new bool[nodes];\n ...\n delete[] visited;</li>\n</ol>\n\n<p>With these changes, profiler shows that 86.5% of CPU time is spent in basic_istream (mostly in _Lock/_Unlock buffer methods, could be MSVC specific), i.e. reading the data.\ndfs algorithm itself takes only 0.45% of CPU time!\nIf the entire program run time is measured at the competition, the obvious place is to refactor the data input to something much faster, possibly using low-level APIs like scanf.</p>\n\n<p>Perhaps the profiling results will be different on Linux, my general advice is to use profiler.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T19:49:09.303", "Id": "477044", "Score": "0", "body": "See here for faster input: https://stackoverflow.com/questions/15036878/c-fastest-cin-for-reading-stdin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T20:32:47.953", "Id": "477050", "Score": "0", "body": "How did you check each of these times. Is there a way to do this in Visual Studio Code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T09:03:40.167", "Id": "477093", "Score": "0", "body": "I don't use Visual Studio Code, but as far as I know it doesn't have a profile feature. You can install Visual Studio 2019 Community edition, it does feature profiler. Or if on Linux, use \"perf\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T19:41:32.287", "Id": "243077", "ParentId": "242741", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:39:01.317", "Id": "242741", "Score": "-2", "Tags": [ "c++", "algorithm", "programming-challenge", "time-limit-exceeded", "graph" ], "Title": "How to work in linear time with DFS" }
242741
<p>I am looking to have a code review on <a href="https://github.com/Dmitry-N-Medvedev/algorithms/tree/quick-find" rel="nofollow noreferrer">this tiny repository</a>.</p> <p>The code seems to work, but I am not sure if I have written it in idiomatic Rust.</p> <pre class="lang-rust prettyprint-override"><code>#[derive(Debug)] pub struct QuickFind { items: Vec&lt;u64&gt;, } impl QuickFind { pub fn new(length: u64) -&gt; QuickFind { let mut result: QuickFind = QuickFind { items: Vec::new() }; for i in 0..length { result.items.push(i); } result } pub fn union(&amp;mut self, left_index: u64, right_index: u64) { let left_group_id = self.items[left_index as usize]; self.items[right_index as usize] = left_group_id; } pub fn get_items(&amp;self) -&gt; &amp;[u64] { &amp;self.items } pub fn is_connected(&amp;self, left_index: u64, right_index: u64) -&gt; bool { self.items[left_index as usize] == self.items[right_index as usize] } } </code></pre>
[]
[ { "body": "<h3>Collect the iterator into the new vector</h3>\n\n<p>You don't need to loop over a range to populate a vector with elements. The <code>collect</code> method has enough information to construct a <code>Vec&lt;u64&gt;</code> on the spot. This also makes the <code>result</code> variable unnecessary.</p>\n\n<pre><code> pub fn new(length: u64) -&gt; QuickFind {\n QuickFind {\n items: (0..length).collect(),\n }\n }\n</code></pre>\n\n<h3>C-GETTER</h3>\n\n<p>The <a href=\"https://rust-lang.github.io/api-guidelines/naming.html#c-getter\" rel=\"nofollow noreferrer\">convention for getter names</a> is <em>without</em> the prefix <code>get_</code>, unless <code>get</code> makes up the entire method name. <code>get_items(&amp;self)</code> becomes <code>items(&amp;self)</code>.</p>\n\n<h3>Reconsider <code>usize</code> as the index type.</h3>\n\n<p>There appear to be multiple conversions from <code>u64</code> to <code>usize</code> in the code. Indeed, <code>usize</code> is the common integral type for referring to a relative (non-negative) position of a value in memory. With that done, the only integer cast is in <code>new</code>, so as to turn the range (0..length) into a range of values rather than a range of indices.</p>\n\n<h3>The final code:</h3>\n\n<p><a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=4b9df5a715adc1d86985f540207df20c\" rel=\"nofollow noreferrer\">Playground</a></p>\n\n<pre><code>#[derive(Debug)]\npub struct QuickFind {\n items: Vec&lt;u64&gt;,\n}\n\nimpl QuickFind {\n pub fn new(length: usize) -&gt; QuickFind {\n QuickFind {\n items: (0..length as u64).collect(),\n }\n }\n\n pub fn union(&amp;mut self, left_index: usize, right_index: usize) {\n let left_group_id = self.items[left_index];\n\n self.items[right_index] = left_group_id;\n }\n\n pub fn items(&amp;self) -&gt; &amp;[u64] {\n &amp;self.items\n }\n\n pub fn is_connected(&amp;self, left_index: usize, right_index: usize) -&gt; bool {\n self.items[left_index] == self.items[right_index]\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T11:00:14.390", "Id": "242743", "ParentId": "242742", "Score": "4" } } ]
{ "AcceptedAnswerId": "242743", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T10:47:07.120", "Id": "242742", "Score": "2", "Tags": [ "rust" ], "Title": "changing values in a vector" }
242742
<p>Is there any way I could make my Tic-Tac-Toe board more aesthetically pleasing?</p> <p>Is there anything else I can improve besides the look of the board?</p> <pre><code>from AskUser import ask_user as As from random import randint Choice = 0 Player1 = None Player2 = None #Introduction def intro(): global Choice while True: Choice = As("Press 1 for Multiplayer\nPress 2 for Single player: ", int) if Choice != (1 or 2): print("Invalid Input") continue else: break return Choice #Players def choosenplayer(): # Defines whos going first if Choice == 1: def whofirst(): global q q = randint(1, 2) if q == 1: print(f"Player 1 ({Player1}) is going first") else: print(f"Player 2 ({Player2}) is going first") # Defines the player while True: global Player2 global Player1 Player = As("Press 1 if you want to be 'X'\nPress 2 if you want to be 'O': ", int) if Player == 1: Player1 = "X" Player2 = "O" break elif Player == 2: Player1 = "O" Player2 = "X" break else: print("Invalid Input") continue print(f"Player 1 is {Player1}, Player 2 is {Player2}") whofirst() return Player1 and Player2 board = list (range(0,9)) #Initialise The Tic Tac Toe Board def t_Board(): print(f"| {board[0]} | {board[1]} | {board[2]} |\n_____________") print(f"| {board[3]} | {board[4]} | {board[5]} |\n_____________") print(f"| {board[6]} | {board[7]} | {board[8]} |") #Stops the game if theres a win def stops_board(): if (board[0] == board[1] == board[2]) or (board[3] == board[4] == board[5]) or ( board[6] == board[7] == board[8]) or (board[0] == board[3] == board[6]) or ( board[1] == board[4] == board[7]) or (board[2] == board[5] == board[8]) or ( board[0] == board[4] == board[8]) or (board[2] == board[4] == board[6]): return True #Ask for X User input x_data = [] def xuser_input(): def over_ride(): global x while True: x = As("Player X, Please enter a number to place: ",int) if board[x] == "X" or board[x] == "O": print("You can't place here, it is already used") continue else: break while True: over_ride() if (x &gt; 10) or (x &lt; 0): print("Input must be Bigger than 0 and Smaller than 9") continue try: board[x] = "X" x_data.append(x) except (IndexError): print("Invalid input") continue t_Board() break #Ask for Y User input O_data = [] def yuser_input(): def over_rideo(): global O while True: O = As("Player O, Please enter a number to place: ",int) if board[O] == "X" or board[O] == "O": print("You can't place here, it is already used") continue else: break while True: over_rideo() if (O &gt; 10) or (O &lt; 0): print("Input must be Bigger than 0 and Smaller than 9") continue try: board[O] = "O" O_data.append(O) except (IndexError): print("Invalid input") continue t_Board() break print("Welcome to TicTacToe simulator") intro() choosenplayer() t_Board() if ((q == 1) and (Player1 == "X")) or ((q == 2) and (Player2 =="X")): for i in range(5): xuser_input() if stops_board(): print(f"Congrats X, You are the winner") break if i == 4: print("This is a tie") break yuser_input() if stops_board(): print(f"Congrats Y, You are the winner") break elif ((q == 1) and (Player1 == "O")) or ((q == 2) and (Player2 == "O")): for i in range(5): yuser_input() if stops_board(): print(f"Congrats O, You are the winner") break if i == 4: print("This is a tie") break xuser_input() if stops_board(): print(f"Congrats X, You are the winner") break </code></pre> <p>This is the <code>As</code> function</p> <pre><code>def ask_user(message, type_= str, valid=lambda x: True, invalid_message="Invalid"): while True: try: user_input = type_(input(message)) except (ValueError, TypeError): print("Invalid input") continue if valid(user_input): return user_input else: print(invalid_message) </code></pre> <p>This code is fully functional, but only for local multiplayer. No AI is in place as of yet.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T23:34:10.703", "Id": "476497", "Score": "1", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/242747/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T07:03:01.693", "Id": "476521", "Score": "0", "body": "An immediate bug I see is `if Choice != (1 or 2):`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:18:30.693", "Id": "476630", "Score": "0", "body": "you were right it wasn't working when i type 2" } ]
[ { "body": "<p>Check out the pyinputplus module. It's good for when you are asking for specific user input, such as when you want the user to answer with 'yes' or 'no', or in your case, 'X' or 'O'.</p>\n\n<p>So in that case you would do something like this:</p>\n\n<pre><code>from pyinputplus import *\n\ninputChoice(('X', 'O'))\n</code></pre>\n\n<p>Which will return:</p>\n\n<pre><code>Please select one of: X, O\n</code></pre>\n\n<p>Alternatively, as a second argument for inputChoice(), you can enter a string for the prompt:</p>\n\n<pre><code>from pyinputplus import *\n\ninputChoice(('X', 'O'), 'Please enter your letter: X or O)\n</code></pre>\n\n<p>Which will return:</p>\n\n<pre><code>Please enter your letter: X or O\n</code></pre>\n\n<p>The input will act as a while loop until one of the provided choices are input(typecase is not taken into account by default, though I think this can be changed within the function's arguments). If an invalid choice is input, the code will return (assuming your input was 'x')</p>\n\n<pre><code>'x' is not a valid choice.\n</code></pre>\n\n<p>pyinputplus and its various functions are great when requiring specific user input, as it keeps you from having to have a bunch of if/elif/else statements under a while loop. It saves a lot of time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:05:01.547", "Id": "476628", "Score": "0", "body": "i know that it is a good module but i still need to assign player 1 as \"X\" or \"Y' and same for player 2, so i think i still need the if else statement. Unless its for the single player mode where i just need it to be 1 letter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:34:17.117", "Id": "476728", "Score": "0", "body": "In that case, have the pyinputplus inputChoice command assign the letter to player 1, and use and if/else statements to assign the other letter to player 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T14:15:41.273", "Id": "476921", "Score": "0", "body": "@JoelV\n[Don't do `from ... import *`.](https://stackoverflow.com/questions/2386714/why-is-import-bad)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T14:41:33.113", "Id": "242803", "ParentId": "242747", "Score": "1" } }, { "body": "<p>Your first question &quot;can the board be made more aesthetically pleasing&quot; is subjective, but I would prefer, for only ASCII characters, something like:</p>\n<pre><code> X | O | 2 \n---+---+---\n 3 | X | 5 \n---+---+---\n 6 | 7 | O \n</code></pre>\n<p>But you could make it even more fancier by using <em>Unicode Box-drawing characters</em>, you can copy and paste these from the <a href=\"https://en.wikipedia.org/wiki/Box-drawing_character\" rel=\"nofollow noreferrer\">Wikipedia page 'Box-drawing character'</a>:</p>\n<pre><code> X │ O │ 2 \n───┼───┼───\n 3 │ X │ 5 \n───┼───┼───\n 6 │ 7 │ O \n</code></pre>\n<p>Some other remarks:</p>\n<ul>\n<li>The function <code>ask_user</code> could be just as good in the main file and renaming it in the import statement to <code>As</code> does not make its use clearer.</li>\n<li>You could use a <em>main guard clause</em> to indicate, amongst others, where the main part of the code begins, see for example this <a href=\"https://stackoverflow.com/questions/19578308/what-is-the-benefit-of-using-main-method-in-python\">StackOverflow Question</a> and links therein.</li>\n<li>Think of more descriptive function names, for instance <code>t_Board</code> would be better called <code>print_board</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-22T16:59:18.310", "Id": "244336", "ParentId": "242747", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:36:22.220", "Id": "242747", "Score": "5", "Tags": [ "python", "python-3.x", "game", "tic-tac-toe" ], "Title": "CLI Tic-Tac-Toe in python" }
242747
<p>I'm learning <code>The essence of SQL</code> by Rozenshtein indirectly from the <code>SQL Cookbook</code> which has a section on it with modern SQL operators introduced after the book was released.</p> <p>The exercise:</p> <p>Given:</p> <pre><code>create table student ( sno integer, sname varchar(10), age integer ); -- /* table of courses */ create table courses ( cno varchar(5), title varchar(10), credits integer ); /* table of students and the courses they take */ create table take ( sno integer, cno varchar(5) ); </code></pre> <p>The question is: <code>Find students who do not take CS112</code></p> <p>I came up with:</p> <pre><code>with s1 as ( select sno from student except select s.sno from student s inner join take t on s.sno = t.sno where t.cno = 'CS112' ) select s.* from student s inner join s1 on s.sno = s1.sno </code></pre> <p>Rozenshtein:</p> <pre><code>select * from student where sno not in (select sno from take where cno = 'CS112') </code></pre> <p>SQL Cookbook style 1: Group by</p> <pre><code>select s.sno, s.sname, s.age from student s left join take t on (s.sno = t.sno) group by s.sno, s.sname, s.age having max(case when t.cno = 'CS112' then 1 else 0 end) = 0; </code></pre> <p>SQL Cookbook style 2: Window function</p> <pre><code>select distinct sno, sname, age from ( select s.sno, s.sname, s.age, max(case when t.cno = 'CS112' then 1 else 0 end) over (partition by s.sno, s.sname, s.age) as takes_CS112 from student s left join take t on (s.sno = t.sno) ) as x where takes_CS112 = 0; </code></pre> <p>I just wanted your opinion on how my query would perform compared to the other queries and if they are in the same ballpark, especially the SQL Cookbook queries. I'm targeting PostgreSQL.</p>
[]
[ { "body": "<p>I would personally use the <code>JOIN</code>, because the query here is fairly simple. You are just matching two tables.<br />\nA subselect is handy for more complex lookups though.</p>\n\n<p>But each DBMS has its own way of parsing and optimizing queries.<br />\nYou should run the <strong>execution plan</strong> on each query and compare results.</p>\n\n<p>Like with Mysql, use the <code>EXPLAIN</code> command to determine which one would perform better. To get representative results you should fill up the tables with sample data. Add a least a few thousand records.\nAlso add <strong>indexes</strong> where appropriate. It could be interesting to run the tests with and without indexes.</p>\n\n<p>The presence (or lack) of indexes will affect the query optimizer. Sometimes you have to provide hints, if the query optimizer does not choose the 'best' index.</p>\n\n<p>It should be noted that performance is related to good DB design. These table examples have no primary key, no index etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:10:56.237", "Id": "242751", "ParentId": "242748", "Score": "2" } } ]
{ "AcceptedAnswerId": "242751", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:42:50.840", "Id": "242748", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "SQL Negation: Find X when X does not do Y" }
242748
<p>I have a React/Redux/Router/Reselect app in which I am syncing some parts of the redux state with the URL. As an interim, hacky measure (I've only been learning how to write wepapps for about 6 months so I'm very much a n00b right now) I’m currently implementing that sync as follows: </p> <p>A selector provides the parts of the state which deviate from the default (e.g. the tab has changed from default and the filter bar is open and one of the filters has been changed from the default):</p> <pre><code>export const getStateConfiguration = createSelector( [getAllActiveFilters, getFilterBarVisible, getSelectedChart, getCurrentTab], (filters, filterBarVisible, selectedChart, currentTab) =&gt; { // inspect filters to create for deviations to default and return a config object with the stuff i need to write to the URI return config; } ); </code></pre> <p>A <code>useEffect()</code> in <code>App.js</code> is listening to that selector and when it changes calls a function in which JSON stringifies the selector's result to <code>history</code>. (I get that history object from <code>router</code>, because if I use <code>uesHistory()</code> from, say, <code>BrowserRouter</code>, I can't seem to escape infinite loop dependencies in <code>useEffect()</code>.)</p> <pre><code>useEffect(() =&gt; { // some lines omitted for brevity writeToHistory(currentJsonConfig, stateConfiguration); }, [dispatch, dbStatus, currentJsonConfig, decodedPathname, stateConfiguration]); </code></pre> <p>At app startup, another <code>useEffect()</code> in <code>App.js</code> calls a function which inspects the location and passes that to initialise the Redux reducers. </p> <pre><code>useEffect(() =&gt; { // some lines omitted for brevity dispatch(initialise(config)); } }, [dispatch, dbStatus, currentJsonConfig, location]); </code></pre> <p>As you can probably already see, all of this performs horrifically. Every time a single thing in state changes, the selector has to examine the whole state model, reparse it, provide that to <code>useEffect()</code>, which stringifies the whole thing again and writes it to <code>history</code>.</p> <p>Due to performance and the hacky nature of my bespoke solution, I now plan to refactor it all to use a 3rd party library(s) which does all this for me. I’ve looked at things like use-query-params (<a href="https://github.com/pbeshai/use-query-params" rel="nofollow noreferrer">https://github.com/pbeshai/use-query-params</a>) and connected-router (<a href="https://www.npmjs.com/package/connected-react-router" rel="nofollow noreferrer">https://www.npmjs.com/package/connected-react-router</a>) but I was wondering if anyone has any experience, guidance, or opinions they can offer on the subject, for the most efficient, straightforward and current solution to the problem.</p> <p>If it helps, you can <a href="https://github.com/adybaby/taskmaster" rel="nofollow noreferrer">see my source code here</a>. The most relevant files which contain my hacky solutions are probably <code>/App.js</code>, <code>/state/selectors/StateConfigurationSelector.js</code> and <code>/HistoryWriter.js</code>. More generaly, if you do take a look and see any other n00b issues, do feel free to tell me!</p> <p>Thanks :)</p>
[]
[ { "body": "<p>I ended up choosing the use-query-params library and writing a class which has several useEffects to sync state. One of the useEffects fires once at load, to update the redux state with the query params in the URL, and the others each hang off one aspect of the state and update the query params when that item changes. It works on the general rule that if the state element is not the default state, it should not add (or remove) the related query param, but if it is not default, then add the query param.</p>\n\n<p>I couldn't just replace the relevant redux state with state in the query params for various reasons: 1) It's useful to keep state elements using the same pattern throughout, for modularity, and so that they benefit from redux dev tools; 2) the query params don't remember the state when the url changes; 3) the state does not care whether or not the item is default - it will always write it.</p>\n\n<p>For those interested, my implementation is here: <a href=\"https://github.com/adybaby/taskmaster/blob/master/src/HistoryWriter.js\" rel=\"nofollow noreferrer\">https://github.com/adybaby/taskmaster/blob/master/src/HistoryWriter.js</a> and a demo here: <a href=\"https://master.d29jyoh6h48gjm.amplifyapp.com/\" rel=\"nofollow noreferrer\">https://master.d29jyoh6h48gjm.amplifyapp.com/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T14:57:32.370", "Id": "243148", "ParentId": "242752", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:15:17.697", "Id": "242752", "Score": "3", "Tags": [ "javascript", "react.js", "redux" ], "Title": "Syncing Redux state with the URI in 2020" }
242752
<p>This is the first Time implementing a Binary Search Tree, based on how it works from the visualgo website. I made this algorithm purely based on what I saw, and the remove method was quite challenging. How can I improve the speed/efficiency and make the code look better?</p> <p>Methods:</p> <ul> <li>Inorder: basically an inorder traversal through the BST Ex: 1 3 4 6 19 25</li> <li>Insert: inserts a node with a certain value</li> <li>lookup: returns the value if it exists in the BST else returns None</li> <li>getMin: returns the min value in the specified node</li> <li>remove: removes a value, and if current_node is not specified then, it starts from the root node, a bit recursive, even though I wanted to implement a way without recursion, but I couldn't see it working without it in any way.</li> </ul> <pre class="lang-py prettyprint-override"><code>class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def inorder(self, current_node): if current_node: self.inorder(current_node.left) print(current_node.value, end=' ') self.inorder(current_node.right) def insert(self, value): NewNode = Node(value) current_node = self.root if current_node is None: self.root = NewNode else: while True: if value &lt; current_node.value: #Left if not current_node.left: current_node.left = NewNode return self current_node = current_node.left else: if not current_node.right: current_node.right = NewNode return self current_node = current_node.right def lookup(self, value): current_node = self.root if current_node is None: return None while current_node: current_value = current_node.value if value &lt; current_value: current_node = current_node.left elif value &gt; current_value: current_node = current_node.right else: return current_node def getMin(self, current_node): while current_node.left is not None: current_node = current_node.left return current_node.value def remove(self, value, current_node=False): if not current_node: current_node = self.root if not current_node: # if the root is None return None parent_node = None while current_node: current_value = current_node.value if value &lt; current_value: parent_node = current_node current_node = current_node.left elif value &gt; current_value: parent_node = current_node current_node = current_node.right else: # No Child if not current_node.left and not current_node.right: if parent_node is None: self.root = None elif current_node == parent_node.left: parent_node.left = None else: parent_node.right = None # One Child elif current_node.right and not current_node.left: if parent_node is None: self.root = current_node.right elif current_node == parent_node.left: parent_node.left = current_node.right else: parent_node.right = current_node.right elif current_node.left and not current_node.right: if parent_node is None: self.root = current_node.left elif current_node == parent_node.left: parent_node.left = current_node.left else: parent_node.right = current_node.left # Two Child else: in_order_successor = self.getMin(current_node.right) self.remove(in_order_successor, current_node) if parent_node is None: self.root.value = in_order_successor elif current_node == parent_node.left: parent_node.left.value = in_order_successor else: parent_node.right.value = in_order_successor return True # if removed return False # if value doesnt exist </code></pre>
[]
[ { "body": "<blockquote>\n<p>How can I…make the code look better?</p>\n</blockquote>\n<p>Follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>.<br />\nAdd <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a>, at least for &quot;everything to be used externally&quot;.<br />\nAdd (<a href=\"https://docs.python.org/library/doctest.html\" rel=\"nofollow noreferrer\">doc</a>)tests. Or, at least, a start for tinkering:</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n t = BinarySearchTree()\n for c in &quot;badcef&quot;:\n t.insert(c)\n t.remove(&quot;d&quot;)\n</code></pre>\n<p>provide amenities like an <code>__str__</code> for node</p>\n<pre><code> def is_leaf(self):\n return self.left is None and self.right is None\n\n def __str__(self):\n return &quot;(&quot; + (self.value if self.is_leaf() else (\n (str(self.left.value + &quot;&lt;&quot;) if self.left else &quot;^&quot;)\n + self.value\n + (&quot;&lt;&quot; + str(self.right.value) if self.right else &quot;^&quot;))) + &quot;)&quot;\n</code></pre>\n<p>(It is somewhat rare that I don't provide docstrings. It felt right <em>here</em>.)</p>\n<p>Keep classes and functions short.<br />\n Say, 24 lines for &quot;heads&quot;, 48 for a function body, 96 for a class.</p>\n<p>Where not impeding readability, keep nesting level low.<br />\n This includes <em>early out</em>s, <code>continue</code>s, <code>breaks</code> &amp; <code>else</code> in loops; <code>return</code>s</p>\n<pre><code> def insert(self, value):\n &quot;&quot;&quot; Insert value into this tree.\n ToDo: document behaviour with identical keys\n (what about lookup()?)\n &quot;&quot;&quot;\n latest = Node(value)\n current = self.root\n previous = None # the parent for latest, if any\n left = None # the child latest is going to be in parent\n while current is not None:\n previous = current\n left = value &lt; current.value\n current = current.left if left else current.right\n if previous is None:\n self.root = latest\n elif left:\n previous.left = latest\n else:\n previous.right = latest\n return self\n</code></pre>\n<p>(what an awful example for changing entirely too many things at once)</p>\n<p>Python naming style is CapWords for classes, only: that would be <code>new_node</code>.<br />\nThe <code>left = None</code> statement is there for the comment.<br />\nThe paranoid prefer <code>is None</code>/<code>is not None</code> over just using what <em>should</em> be a reference in a boolean context.\nAbove rendition tries to keep DRY and avoids some of what looks repetitious in the <code>insert()</code> you presented.<br />\nBut, wait, doesn't that <em>descend left or right thing</em> look just the same in <code>lookup()</code> and <code>remove()</code>?<br />\nIf I had a method</p>\n<pre><code> def _find(self, value):\n &quot;&quot;&quot; Find node with value, if any.\n Return this node and setter for (re-)placing it in this tree.\n &quot;&quot;&quot;\n pass\n</code></pre>\n<p>, <code>insert()</code> was simple, and <code>lookup()</code> trivial (if questionable: wording<br />\n• lookup: returns the value if it exists in the BST else returns None<br />\n, implementation returns a <code>Node</code>):</p>\n<pre><code> def insert(self, value):\n &quot;&quot;&quot; Insert value into this tree.\n ToDo: document behaviour with identical keys\n &quot;&quot;&quot;\n existing, place = self._find(value)\n if existing is not None:\n pass\n place(Node(value))\n return self\n \n def lookup(self, value):\n &quot;&quot;&quot; Return node with value, if any. &quot;&quot;&quot;\n return self._find(value)[0]\n</code></pre>\n<p>Remove can profit from a modified <em>successor</em> method</p>\n<pre><code> @staticmethod\n def leftmost(child, parent=None):\n &quot;&quot;&quot; Return the leftmost node of the tree rooted at child,\n and its parent, if any. &quot;&quot;&quot;\n if child is not None:\n while child.left is not None:\n child, parent = child.left, child\n return child, parent\n \n def deleted(self, node): # node None?\n &quot;&quot;&quot; Return root of a tree with node's value deleted. &quot;&quot;&quot;\n successor, parent = BinarySearchTree.leftmost(node.right, node)\n if successor is None:\n return node.left\n node.value = successor.value\n if node is not parent:\n parent.left = successor.right\n else:\n node.right = successor.right\n return node\n \n def remove(self, value):\n &quot;&quot;&quot; Remove value.\n Return 'tree contained value'. &quot;&quot;&quot;\n node, place = self._find(value)\n if node is None:\n return False\n place(self.deleted(node))\n return True\n</code></pre>\n<p>My current rendition of <code>_find()</code> adds in <code>Node</code></p>\n<pre><code> def _set_left(self, v):\n self.left = v\n \n def _set_right(self, v):\n self.right = v\n</code></pre>\n<p>, in <code>BinarySearchTree</code></p>\n<pre><code> def _set_root(self, v):\n self.root = v\n \n def _find(self, value):\n &quot;&quot;&quot; Find node with value, if any.\n Return this node and setter for (re-)placing it in this tree.\n &quot;&quot;&quot;\n if self.root is None or self.root.value == value:\n return self.root, self._set_root\n child = self.root\n while True:\n node = child\n smaller = value &lt; child.value\n child = child.left if smaller else child.right\n if child is None or child.value == value:\n return child, node._set_left if smaller else node._set_right\n</code></pre>\n<hr />\n<blockquote>\n<p>How can I improve the speed/efficiency?</p>\n</blockquote>\n<p>Don't spend effort there before measurements suggesting it's a bottleneck.</p>\n<hr />\n<p>Guide-line for easy-to-use types: Don't <em>make</em> me think.</p>\n<p>You define <code>inorder()</code> to print the values in order.<br />\nWouldn't it be cute to be able to use, for a tree <code>ascending</code><br />\n<code>for item in ascending: …</code>? While it was <em>possible</em> to not touch <code>Node</code>, add</p>\n<pre><code> def __iter__(self):\n &quot;&quot;&quot; Yield each node in the tree rooted here in order. &quot;&quot;&quot;\n if self.left is not None:\n yield from self.left\n yield self.value\n if self.right is not None:\n yield from self.right\n</code></pre>\n<p>there, and in the tree</p>\n<pre><code> def __iter__(self):\n &quot;&quot;&quot; Yield each node in the tree in order. &quot;&quot;&quot;\n if self.root is not None:\n yield from self.root\n</code></pre>\n<p>, enabling <code>print(*ascending)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T08:22:36.890", "Id": "531379", "Score": "0", "body": "Why it felt right to omit the docstrings: you don't need a docstring for `__str__`, because everybody knows the expected behaviour; and for `is_leaf`, I think the name provides all the documentation necessary!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T07:56:09.570", "Id": "269351", "ParentId": "242754", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:21:44.683", "Id": "242754", "Score": "4", "Tags": [ "python", "python-3.x", "linked-list", "binary-search-tree" ], "Title": "Binary Search Tree (BST) Implementation" }
242754
<p>Good afternoon,</p> <p>I have a set of working code, which works as a loop between values i = 0-90 step 0.25. It gives 360 combinations exactly.</p> <p>I used to do this loop separately column by column. It takes time and I must repeat the process exactly 9 times.</p> <p><a href="https://i.stack.imgur.com/hg9UC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hg9UC.png" alt="enter image description here"></a></p> <p>So, red bounded is the column first, which I am currently working on. The blue bounds apply to different columns. The value comes from a completely different worksheet. The output is stored in a complete worksheet too (as below). <a href="https://i.stack.imgur.com/67cl8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/67cl8.png" alt="enter image description here"></a></p> <p>My working codes look as follows:</p> <pre><code> Sub calc4() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("b1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i * (-1) With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("B371").Value End With Next I End With End Sub Sub calc3() Dim i As Single With Worksheets("9") .UsedRange.clear '.Range("a1").Value = "Input" .Range("c1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("D371").Value End With Next I End With End Sub Sub calc2() Dim i As Single With Worksheets("9") .UsedRange.clear ' .Range("a1").Value = "Input" .Range("d1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("F371").Value End With Next I End With End Sub Sub calc1() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("e1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("H371").Value End With Next I End With End Sub Sub calc085() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("f1").Value = "Output" For i = 0 To 490 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("I371").Value End With Next I End With End Sub Sub calc06() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("g1").Value = "Output" For i = 0 To 45 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("L371").Value End With Next I End With End Sub Sub calc17() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("h1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("N371").Value End With Next I End With End Sub Sub calc276a() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("i1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("P371").Value End With Next I End With End Sub Sub calc38a() Dim i As Single With Worksheets("9") .UsedRange.clear .Range("a1").Value = "Input" .Range("j1").Value = "Output" For i = 0 To 90 Step 0.25 Worksheets("1_GENERAL").Range("A2").Value = i With .Cells(Rows.Count, 1).End(xlUp) .Offset(1, 0).Value = i .Offset(1, 1).Value = Worksheets("4.MINUTES").Range("R371").Value End With Next I End With End Sub </code></pre> <p>basically it's every 2 columns as you can see. The exception is column H and I, next to each other. In this event even split this loop into 2 separate will help me a lot. Is it possible?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:40:09.930", "Id": "476448", "Score": "0", "body": "You will want to iterate rows 1-90 (0-90 is 91 iterations) *once*, regardless of how many columns you have to work with. The macro is a sheet traversal; coding it as such would slash its execution time big time - or do you need 9 separate outputs? If not, then why does every output procedure begin with clearing the used range of the output sheet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:44:36.600", "Id": "476450", "Score": "0", "body": "Also you're working out where to write next at each iteration; tracking which row you're at instead, would eliminate that worksheet operation and speed things up too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:44:54.603", "Id": "476488", "Score": "0", "body": "Your code is not matching up with your output worksheet \"9\". In each of your `calc` routines, you are simply assigning the loop variable `i` to column A and the *exact same value from `Worksheets(\"4.MINUTES\").Range(x371).Value`. How is the value is column B changing? Plus, as you're looping, you are updating the loop value to a single cell on \"1_GENERAL\" worksheet. It's unclear how your VBA logic works to produce the output shown." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T20:15:36.837", "Id": "476663", "Score": "0", "body": "OK let me do the explanation:\nI am doing these calculations for 360 records exactly. They refer to latitude 0-90 divided by 4, hence step 0.25. The step value comes from the 1_GENERAL sheet, which links values in 4.MINUTES. This is why the loop is going this way. As the value in 1_GENERAL changes, all the calculations change in 4.MINUTES sheet bringing the different summary calculated in .Range(x371).Value. Because each loop is related to a separate columns in 4.MINUTES (B371, D371, F371, etc), I need 9 separate outputs in Sheet \"9\" columns B-J." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T15:00:11.450", "Id": "242757", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "VBA Excel bulk data loop for few columns at once" }
242757
<p>I have a feature with feature flagging enabled, basis the condition I want to load different pages in my screen, to achieve this I have the following enum: </p> <pre><code>enum class ImageHolderEnum( val titleId: Int, val qFragment: BaseFragment, val fragment: BaseFragment ) : IPageHolder { PAGE1(R.string.tab_shop_baby, BabyTwoFragment(), BabyThreeFragment()) { override fun getTitle(): Int = titleId override fun getFragmentToAdd(): BaseFragment = if (isFeatureAllowed()) qFragment else fragment }, PAGE2(R.string.tab_shop_mom, MomThreeFragment(), MomTwoFragment()) { override fun getTitle(): Int = titleId override fun getFragmentToAdd(): BaseFragment = if (isFeatureAllowed()) qFragment else fragment }, PAGE3(R.string.tab_shop_dad, DadTwoFragment(), DadThreeFragment()) { override fun getTitle(): Int = titleId override fun getFragmentToAdd(): BaseFragment = if (isFeatureAllowed()) qFragment else fragment }; fun isFeatureAllowed(): Boolean { val qSlideConfig: QSlideConfig by remoteFeatureFlag() // Kind of dependency injection here return qSlideConfig.isQSlideEnabled() } } </code></pre> <p>The interface is as follows: </p> <pre><code>interface IPageHolder { fun getTitle(): Int fun getFragmentToAdd(): BaseFragment } </code></pre> <p>I am concerned if I am using the dependency injection inside the enum and breaking some principles. </p>
[]
[ { "body": "<p>Why are you giving seperate implementations for each enum value? All <code>getTitle()</code> and <code>getFragmentToAdd()</code> implementations are the same.</p>\n\n<pre><code>enum class ImageHolderEnum(\n val titleId: Int,\n val qFragment: BaseFragment,\n val fragment: BaseFragment\n) : IPageHolder {\n PAGE1(R.string.tab_shop_baby, BabyTwoFragment(), BabyThreeFragment()),\n PAGE2(R.string.tab_shop_mom, MomThreeFragment(), MomTwoFragment()),\n PAGE3(R.string.tab_shop_dad, DadTwoFragment(), DadThreeFragment()),\n ;\n\n override fun getTitle(): Int = titleId\n override fun getFragmentToAdd(): BaseFragment = if (isFeatureAllowed()) qFragment else fragment\n\n fun isFeatureAllowed(): Boolean {\n val qSlideConfig: QSlideConfig by remoteFeatureFlag() // Kind of dependency injection here \n return qSlideConfig.isQSlideEnabled()\n }\n}\n</code></pre>\n\n<p>Interfaces can also have properties, so there's no need to have <code>getTitle()</code> as a function, when it can just be a value.</p>\n\n<pre><code>interface IPageHolder {\n val titleId: Int\n fun getFragmentToAdd(): BaseFragment\n}\n</code></pre>\n\n<p>And you can then use it like this in the enum class:</p>\n\n<pre><code>enum class ImageHolderEnum(\n override val titleId: Int,\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:24:14.323", "Id": "476484", "Score": "1", "body": "Thanks, I was not aware if I could do that, this looks much cleaner!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T19:24:55.643", "Id": "242765", "ParentId": "242762", "Score": "2" } } ]
{ "AcceptedAnswerId": "242765", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T18:42:07.023", "Id": "242762", "Score": "1", "Tags": [ "enum", "kotlin" ], "Title": "Would my implementation of this enum pass?" }
242762
<p>Below code just for assemble data into network packet. but the code logic has many repeat parts to convert integer for byte array. what's the best method for such purpose to simplify below logic?</p> <pre><code>typedef struct _INFO { int pid; int score; } INFO; void send_packet(int connfd,INFO* info,int len) { int buflen = len*8 + 8; unsigned char* buf = (int*)malloc(buflen); int p = 0; buf[p++] = 0x55; buf[p++] = 0x55; buf[p++] = 0x55; buf[p++] = 0x55; buf[p++] = buflen &amp; 0xFF; buf[p++] = (buflen &gt;&gt; 8) &amp; 0xFF; buf[p++] = (buflen &gt;&gt; 16) &amp; 0xFF; buf[p++] = (buflen &gt;&gt; 24) &amp; 0xFF; for (int i=0;i&lt;len;i++) { buf[p++] = info[i].pid &amp; 0xFF; buf[p++] = (info[i].pid &gt;&gt; 8) &amp; 0xFF; buf[p++] = (info[i].pid &gt;&gt; 16) &amp; 0xFF; buf[p++] = (info[i].pid &gt;&gt; 24) &amp; 0xFF; buf[p++] = info[i].score &amp; 0xFF; buf[p++] = (info[i].score &gt;&gt; 8) &amp; 0xFF; buf[p++] = (info[i].score &gt;&gt; 16) &amp; 0xFF; buf[p++] = (info[i].score &gt;&gt; 24) &amp; 0xFF; } write(connfd, buf, buflen); free(buf); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:45:43.230", "Id": "476477", "Score": "0", "body": "What is the potential range of `len`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:26:58.280", "Id": "476485", "Score": "0", "body": "BTW, a leading `0x55555555` looks like it has some weakness for the `read()` side to synchronize with. I look forward to seeing the read code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:35:23.790", "Id": "476487", "Score": "0", "body": "@chux - Reinstate Monica, for synchronize purpose, any keyword can be used I guess. some hardware guy tell me use 0x55555555. what's your suggestion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T01:38:50.957", "Id": "476503", "Score": "0", "body": "Ideally the start-of-frame bytes never/rarely occur in the payload and don't look like a start-of-frame shifted with the beginning/trailing byte. Yet there is more than just good start-of-frame selection such as [What type of framing to use in serial communication](https://stackoverflow.com/q/17073302/2410359)" } ]
[ { "body": "<p>A 0xFF character is all ones. So <code>AnyChar &amp; 0xFF</code> will always return the same char. Also you can simplify the first 4 lines with <code>memset()</code>. You can also simplify a few of the lines with for loops:</p>\n\n<pre><code>#include &lt;string.h&gt;\nvoid send_packet(int connfd,INFO* info,int len) {\n int buflen = len*8 + 8;\n unsigned char* buf = malloc(buflen);\n int p = 4;\n memset(buf, 0x55, 4);\n\n for (int i=0; i&lt;4; i++) {\n buf[p++] = buflen &gt;&gt; i*8;\n }\n for (int i=0;i&lt;len;i++) {\n for (int i=0; i&lt;4; i++) {\n buf[p++] = info[i].pid &gt;&gt; i*8;\n buf[p++] = info[i].score &gt;&gt; i*8;\n }\n }\n write(connfd, buf, buflen);\n free(buf);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:10:18.040", "Id": "476479", "Score": "0", "body": "memset is awesome!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:15:40.737", "Id": "476481", "Score": "0", "body": "@lucky1928 Indeed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:18:50.467", "Id": "476483", "Score": "1", "body": "`for (int i=0; i<4; i++) {\n buf[p++] = info[i].pid >> i*8;\n buf[p++] = info[i].score >> i*8;\n }` needs to be 2 loops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:41:33.440", "Id": "476548", "Score": "0", "body": "The code contains way too many `for` loops that have exactly the same structure." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:44:41.230", "Id": "242770", "ParentId": "242763", "Score": "1" } }, { "body": "<blockquote>\n <p>what's the best method for such purpose to simplify below logic?</p>\n</blockquote>\n\n<p>With a helper function as there is repetitive code.</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\n// Write 32-bit integer in little endian order to buf\nunsigned char *u32tobuf(unsigned char *buf, uint32_t value) {\n buf[0] = value;\n buf[1] = value &gt;&gt; 8;\n buf[2] = value &gt;&gt; 16;\n buf[3] = value &gt;&gt; 24;\n return buf + 4;\n}\n</code></pre>\n\n<p>I'd also 1) add some error checking, 2) drop the unneeded cast 3) prevent <code>int</code> overflow 4) use <code>const</code>.</p>\n\n<pre><code>// Return error status\nint send_packet(int connfd, const INFO* info, int len) {\n uint32_t buflen = len*8lu + 8;\n unsigned char* buf = malloc(buflen);\n if (buf == NULL) {\n return 1; // or perhaps some enum\n }\n unsigned char* p = u32tobuf(buf, 0x55555555);\n p = u32tobuf(p, buflen);\n for (int i=0; i&lt;len; i++) {\n p = u32tobuf(p, info[i].pid);\n p = u32tobuf(p, info[i].score);\n }\n ssize_t write_count = write(connfd, buf, buflen);\n free(buf);\n if (write_count != buflen) [\n return 1; // or perhaps some enum\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:09:24.713", "Id": "476478", "Score": "0", "body": "Great, the cast is means & 0xFF? I saw java use such cast always. for C, I am not sure if we need it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:17:50.963", "Id": "476482", "Score": "0", "body": "@lucky1928 _Casting_ does has its place, yet it is often a sign of brittle learner's.code. With converting a `void *` to/from some other `object *`, it is not needed in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:33:31.077", "Id": "476486", "Score": "0", "body": "Oh, the buf pointer has been moved to the end, so the write will be overflow. need to add a variable to remember the pointer header." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T12:35:06.407", "Id": "476544", "Score": "0", "body": "@lucky1928 Yes code was amended" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:51:00.937", "Id": "476772", "Score": "0", "body": "could a union be used to simplify the u32tobuf function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T00:35:55.817", "Id": "476785", "Score": "0", "body": "As the goal is to take a 32-bit of host endian into a serial buffer for transmission, I doubt a `union` will provide a performance increase nor simplification." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:59:03.633", "Id": "242773", "ParentId": "242763", "Score": "3" } } ]
{ "AcceptedAnswerId": "242773", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T18:59:06.660", "Id": "242763", "Score": "3", "Tags": [ "c" ], "Title": "Simplify data packet assemble in C" }
242763
<p>I have a geojson file with results for each province and one that gives other results for each constituency (an administrative part of the province). I would like to make a third one that puts the results of the first one for each 'constituency' level of the second one that has the same <code>province</code> with the first one, so I did the following code. It works but it's not optimized at all for the actual file which is far bigger, and which I can share with you if you think it can help me optimize the code.</p> <pre><code>import json import pandas as pd def find_segment(province_queried): with open('research.geojson', encoding='utf-8-sig') as f: dct_research = json.load(f) for feature in dct_research['features']: for key in feature.get("properties", {}).get("results", {}): province = feature.get("properties", {}).get("name") segments = feature.get("properties", {}).get("segments") if province == province_queried: return segments def main(): with open('maroc-swing.json') as f: dct_constituencies = json.load(f) i = 0 j = 0 d = [] for feature in dct_constituencies['features']: for key in feature.get("properties", {}).get("results", {}): province = feature.get("properties", {}).get("name_1") constituency = feature.get("properties", {}).get("name_4", {}) segments = find_segment(province) d.append({"Party Affiliation": key, "Province": province, "Constituency Name": constituency, "segments": segments}) column_names = ["Province", "Constituency Name", "Party Affiliation", "segments"] df = pd.DataFrame(d, columns=column_names) df.to_csv("constituencies_with_segments.csv") if __name__ == '__main__': main() </code></pre> <p>If you prefer it with drawings I'm basically transformint the right hand file:</p> <p><a href="https://i.stack.imgur.com/F2Pym.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F2Pym.png" alt="enter image description here"></a></p> <p>Into:</p> <p><a href="https://i.stack.imgur.com/Qct8O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qct8O.png" alt="enter image description here"></a></p> <p>It means that all the constituents of the same province will have the same results that come from 'research.json'. Right now I'm trying to do it in the key name_2.</p> <p>Here it is <code>constituences.json</code>:</p> <pre><code>{ "type": "FeatureCollection", "totalFeatures": 1515, "features": [ { "type": "Feature", "id": "fd597jf1799.1", "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -7.27163887, 33.24041367 ], [ -7.27286911, 33.24623871 ], [ -7.26732922, 33.25904083 ] ] ] ] }, "geometry_name": "geom", "properties": { "id_0": 152, "iso": "MAR", "name_0": "Morocco", "id_1": 1, "name_1": "Chaouia - Ouardigha", "id_2": 1, "name_2": "Ben Slimane", "id_3": 1, "name_3": "Ben Slimane", "id_4": 1, "name_4": "Ahlaf", "varname_4": null, "ccn_4": 0, "cca_4": null, "type_4": "Commune Rural", "engtype_4": "Rural Commune", "bbox": [ -7.27286911, 33.22112656, -6.93353081, 33.38970184 ], "swing_count": 1, "polling_station_count": 15, "turnout": 0.4780299144225693, "results": { "PI": 187, "PJD": 88, "PAM": 59, "USFP": 1530, "APFGD": 2, "PPS": 15, "RNI": 708, "MP": 56, "UC": 3, "FFD": 0, "MDS": 0, "AAR": 0, "P Neo-Democrates": 8, "PEDD": 0, "PRD": 2, "PRV": 0, "PDI": 0, "PGVM": 0, "PALAMAL": 0, "PCS": 0, "PUD": 0, "PDN": 1, "PLJS": 0, "PSD": 0, "P Annahda": 0, "PA": 0, "UMD": 0, "USAPMD": 10 }, "voter_file": { "nbre_sieges": 3, "nbre_inscrits": 5953, "nbre_votants": 2997, "nbre_nuls": 328, "nbre_exprimees": 2669 }, "swing_ratio": 0.06666666666666667 } }, { "type": "Feature", "id": "fd597jf1799.2", "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -7.00001287, 33.63414383 ], [ -7.00081205, 33.6269989 ], [ -6.99825382, 33.60465622 ] ] ] ] }, "geometry_name": "geom", "properties": { "id_0": 152, "iso": "MAR", "name_0": "Morocco", "id_1": 1, "name_1": "Chaouia - Ouardigha", "id_2": 1, "name_2": "Ben Slimane", "id_3": 1, "name_3": "Ben Slimane", "id_4": 2, "name_4": "Ain Tizgha", "varname_4": null, "ccn_4": 0, "cca_4": null, "type_4": "Commune Rural", "engtype_4": "Rural Commune", "bbox": [ -7.12737417, 33.57954407, -6.99144888, 33.78071213 ], "swing_count": 11, "polling_station_count": 23, "turnout": 0.3912592182242994, "results": { "PI": 1837, "PJD": 366, "PAM": 143, "USFP": 22, "APFGD": 44, "PPS": 773, "RNI": 109, "MP": 111, "UC": 9, "FFD": 0, "MDS": 0, "AAR": 0, "P Neo-Democrates": 76, "PEDD": 27, "PRD": 2, "PRV": 0, "PDI": 0, "PGVM": 0, "PALAMAL": 0, "PCS": 0, "PUD": 0, "PDN": 1, "PLJS": 0, "PSD": 0, "P Annahda": 0, "PA": 0, "UMD": 2, "USAPMD": 514 }, "voter_file": { "nbre_sieges": 3, "nbre_inscrits": 8262, "nbre_votants": 4479, "nbre_nuls": 443, "nbre_exprimees": 4036 }, "swing_ratio": 0.4782608695652174 } } ], "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4326" } }, "bbox": [ -13.2287693, 27.62881088, -0.93655348, 35.96390533 ] } </code></pre> <p>And here's 'research.json':</p> <pre><code>{ "type": "FeatureCollection", "features": [ { "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -7.18458319, 33.81124878 ], [ -7.18458319, 33.81097412 ], [ -7.18319511, 33.81097412 ] ] ] ] }, "type": "Feature", "id": "md898kw3185.1", "properties": { "name": "Ben Slimane", "type": "Province", "segments": { "UND": { "I don't know yet": 16, "No": 3, "Yes": 5, "total": 24, "intention_rate": 20.83 }, "ABS": { "I don't know yet": 1, "No": 10, "Yes": 1, "total": 12, "intention_rate": 8.33 }, "PJD": { "I don't know yet": 1, "Yes": 3, "total": 4, "intention_rate": 75 }, "PAM": { "I don't know yet": 1, "Yes": 1, "total": 2, "intention_rate": 50 }, "OTH": { "I don't know yet": 1, "No": 4, "Yes": 4, "total": 9, "intention_rate": 44.44 }, "RNI": { "Yes": 2, "total": 2, "intention_rate": 100 }, "IST": { "I don't know yet": 1, "Yes": 1, "total": 2, "intention_rate": 50 } }, "sample_size": 55 } }, { "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -6.3649292, 33.22292328 ], [ -6.38369083, 33.21116257 ], [ -6.39487886, 33.19342422 ] ] ] ] }, "type": "Feature", "id": "md898kw3185.2", "properties": { "name": "Khouribga", "type": "Province", "segments": { "UND": { "I don't know yet": 46, "No": 12, "Yes": 13, "total": 71, "intention_rate": 18.31 }, "ABS": { "I don't know yet": 4, "No": 79, "Yes": 1, "total": 84, "intention_rate": 1.19 }, "PJD": { "I don't know yet": 14, "No": 1, "Yes": 4, "total": 19, "intention_rate": 21.05 }, "PAM": { "I don't know yet": 12, "No": 1, "Yes": 7, "total": 20, "intention_rate": 35 }, "OTH": { "I don't know yet": 3, "No": 3, "Yes": 2, "total": 8, "intention_rate": 25 }, "RNI": { "I don't know yet": 3, "Yes": 3, "total": 6, "intention_rate": 50 }, "IST": { "I don't know yet": 5, "Yes": 1, "total": 6, "intention_rate": 16.67 } }, "sample_size": 214 } }, { "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -3.77662611, 34.86683655 ], [ -3.7705431, 34.86468506 ], [ -3.75482011, 34.86924362 ] ] ] ] }, "type": "Feature", "id": "md898kw3185.57", "properties": { "name": "Taza", "type": "Province", "segments": { "UND": { "I don't know yet": 16, "No": 28, "Yes": 14, "total": 58, "intention_rate": 24.14 }, "ABS": { "I don't know yet": 2, "No": 29, "Yes": 1, "total": 32, "intention_rate": 3.12 }, "PJD": { "I don't know yet": 9, "No": 4, "Yes": 23, "total": 36, "intention_rate": 63.89 }, "PAM": { "I don't know yet": 4, "No": 1, "Yes": 1, "total": 6, "intention_rate": 16.67 }, "OTH": { "I don't know yet": 3, "No": 3, "Yes": 5, "total": 11, "intention_rate": 45.45 }, "RNI": { "total": 0, "intention_rate": 0 }, "IST": { "I don't know yet": 2, "No": 2, "Yes": 5, "total": 9, "intention_rate": 55.56 } }, "sample_size": 152 } } ] } </code></pre> <p>Sadly my attempt takes too much time. Do you know how I can optimize it, or do you have a better idea in mind?</p>
[]
[ { "body": "<p><code>find_segment</code> loads the json file every time it is called. It would be much faster to load the data once and return a dict mapping province to segments. Also, <code>key</code> doesn't appear to be used, so remove that for-loop</p>\n\n<pre><code>def load_research(filename='research.geojson'):\n \"\"\"loads json data from filename and return a dict of segments\n keyed by province.\"\"\"\n\n with open(filename, encoding='utf-8-sig') as f:\n dct_research = json.load(f)\n\n data = {}\n\n for feature in dct_research['features']:\n province = feature.get(\"properties\", {}).get(\"name\")\n segments = feature.get(\"properties\", {}).get(\"segments\")\n data[province] = segments\n\n return data\n</code></pre>\n\n<p>In <code>main()</code> it looks like <code>province</code>, <code>constituency</code>, and <code>segments</code> only depend on <code>feature</code> and not on <code>key</code>. So calculate them before the <code>for key ...</code> loop. That should speed things up a lot.</p>\n\n<pre><code>def main():\n # load data into a dict keyed by province\n research = load_research()\n\n with open('maroc-swing.json') as f:\n dct_constituencies = json.load(f)\n\n d = []\n for feature in dct_constituencies['features']:\n\n province = feature.get(\"properties\", {}).get(\"name_1\", \"\")\n constituency = feature.get(\"properties\", {}).get(\"name_4\", \"\")\n\n # this is now a dict lookup rather than loading a json file\n segments = research[province]\n\n for key in feature.get(\"properties\", {}).get(\"results\", {}):\n d.append({\"Party Affiliation\": key,\n \"Province\": province,\n \"Constituency Name\": constituency,\n \"segments\": segments})\n\n column_names = [\"Province\", \"Constituency Name\", \"Party Affiliation\", \"segments\"]\n df = pd.DataFrame(d, columns=column_names)\n\n df.to_csv(\"constituencies_with_segments.csv\")\n</code></pre>\n\n<p>NB. I haven't tested the code, so there may be some typos etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T22:56:28.307", "Id": "242823", "ParentId": "242766", "Score": "2" } } ]
{ "AcceptedAnswerId": "242823", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T19:42:18.657", "Id": "242766", "Score": "2", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Putting the results of a first JSON file of to subparts of a second one when key matches" }
242766
<p>I am solving the "Point where max intervals overlap" problem on geeks for geeks, <a href="https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/</a>. Following the solution in the article, I used two lists to store start and end times of the intervals. This is my solution in Python:</p> <pre><code>def maxIntervalOverlap(intervals): # break intervals into two lists first = lambda x: x[0] end = lambda x: x[1] enter = list(map(first, intervals)) exit = list(map(end, intervals)) # sort lists enter.sort() exit.sort() i = 1 j = 0 time = enter[0] n = len(enter) max_guests = 1 guests_in = 1 # process events in sorted order while i &lt; n and j &lt; n: # next event is arrival, increment count of guests if enter[i] &lt;= exit[j]: guests_in += 1 if guests_in &gt; max_guests: max_guests = guests_in time = enter[i] i += 1 else: guests_in -= 1 j += 1 print(f"Point where maximum number of intervals overlap is {time}") </code></pre> <p>and below is a test case</p> <pre><code>intervals = [[1, 4], [2, 5], [10, 12], [5, 9], [5, 12]] maxIntervalOverlap(intervals) </code></pre> <p>How can I solve this problem without having to create the two extra lists ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:29:27.230", "Id": "476473", "Score": "0", "body": "Please include the challenge description in the question itself. Links can rot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:14:26.307", "Id": "476480", "Score": "0", "body": "You could take a look at [interval trees](https://pypi.org/project/intervaltree/). They would work quite differently though. For example, duplicate intervals are not allowed, and the interval *end* is *not* counted, i.e. \\$ [a, b) \\$." } ]
[ { "body": "<p>Here's a solution that only uses one extra data structure. I use the <code>heapq</code> library to maintain a heap, where it easy to check the smallest item and remove it when it's not needed any longer. You could also use <code>SortedList</code> from the wonderful <a href=\"http://www.grantjenks.com/docs/sortedcontainers/\" rel=\"nofollow noreferrer\">sortedcontainers</a> library.</p>\n\n<p>The basic idea is to loop over the intervals sorted by start time. If some intervals have the same start time, then sort those by end time. Fortunately, Python's <code>sort()</code> method or <code>sorted()</code> function will take care of that.</p>\n\n<p>For each start-end interval, the end time is saved in the heap. </p>\n\n<p>For any end times in the heap that are earlier than the current start time, we reduce the number of guests and remove the end time from the heap.</p>\n\n<p>The start time represents the arrival of a guest, so increment the number of guests and check if it is a new maximum number.</p>\n\n<p>After the last start time, the number of guests can only decrease, so we don't need to process any left over end times.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>import heapq\n\n def maxIntervalOverlap(intervals):\n guests = 0\n maxguests = 0\n maxtime = None\n\n heap = []\n\n for start, end in sorted(intervals):\n heapq.heappush(heap, end)\n\n # handle intervals that ended before 'start' time\n while heap[0] &lt; start:\n heapq.heappop(heap)\n guests -= 1\n\n # add the guest that just arrived at 'start' time\n guests += 1\n if guests &gt; maxguests:\n maxguests = guests\n maxtime = start\n\n print(f\"Time with maximum guests is {maxtime}.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T00:49:29.673", "Id": "476675", "Score": "0", "body": "Thanks ! That is the solution I was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T22:13:02.210", "Id": "242822", "ParentId": "242767", "Score": "2" } } ]
{ "AcceptedAnswerId": "242822", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:17:18.940", "Id": "242767", "Score": "1", "Tags": [ "python", "algorithm" ], "Title": "Point where maximum intervals overlap" }
242767
<p>This is an answer to <a href="https://codegolf.stackexchange.com/q/205079/94032">this question on Code-Golf.SE</a> (but obviously not golfed). How can I shorten the runtime of my program? It is taking far too long to run some of the test cases. Can I utilise Python <code>map()</code> or <code>lambda</code>?</p> <pre class="lang-py prettyprint-override"><code>def main(): # Store number of test cases T = int(input()) # Loop for each test case: for testCase in range(0, T): # Store number of members each team can have N = int(input()) # Store power of beyblades of Team G-Revolution members teamG_beybladePowers = [int(x) for x in input().split()] # Store power of beyblades of opponent team members opponentBeybladePowers = [int(x) for x in input().split()] # Store the calculated order of our team members as a list teamG_calculatedOrder = [] # Store the caclulated order of opponent team members as a list opponentCalculatedOrder = [] # Loop through each of the team members and opponent team members, and match them for index in range(0, N): # Check if Team G's highest beyblade power is lower than or equal to opponent's highest if max(teamG_beybladePowers) &lt;= max(opponentBeybladePowers): # Team G's highest beyblade power is weaker than opponent's highest. # We need not waste our best player on their best player, when we will lose. # Match our lowest player against their highest player. teamG_calculatedOrder.append(min(teamG_beybladePowers)) opponentCalculatedOrder.append(max(opponentBeybladePowers)) # Remove these members from original list teamG_beybladePowers.remove(min(teamG_beybladePowers)) opponentBeybladePowers.remove(max(opponentBeybladePowers)) else: # Team G's highest beyblade power is more than opponent's highest. # We can use our best player to beat the opponent's best player. # Match them up: teamG_calculatedOrder.append(max(teamG_beybladePowers)) opponentCalculatedOrder.append(max(opponentBeybladePowers)) # Remove these members from the original list teamG_beybladePowers.remove(max(teamG_beybladePowers)) opponentBeybladePowers.remove(max(opponentBeybladePowers)) # Store total number of wins totalWins = 0 # Calculate number of wins for index in range(0, N): # Check if current match was won if teamG_calculatedOrder[index] &gt; opponentCalculatedOrder[index]: # This match was won # Increment total wins: totalWins += 1 else: # This match was lost pass # Print total number of wins print(totalWins) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T02:28:42.390", "Id": "476505", "Score": "0", "body": "It would be helpful if you provided the test cases that are taking too long. The cases on Code-Golf are pretty short, so I don't imagine your referring to them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T10:59:33.380", "Id": "476538", "Score": "0", "body": "@RootTwo My program allows you to run several test cases in one go. If you choose to do this, runtime takes more than 4 seconds" } ]
[ { "body": "<h2>Specific suggestions</h2>\n\n<ol>\n<li>Using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">command-line arguments</a> is the idiomatic way to collect input. This makes the code scriptable and reusable as a library.</li>\n<li><p>The idiomatic way to run <code>main</code> is this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre></li>\n<li>Several bits of code are duplicated, such as <code>min(teamG_beybladePowers)</code>. Pull those out into variables to avoid re-iterating through the whole list more than necessary.</li>\n</ol>\n\n<h2>Tool support suggestions</h2>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged. In your case the code does look decently formatted, so it may not change much (or at all).</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> can give you hints to write idiomatic Python. I would start with this configuration:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T23:40:36.503", "Id": "242778", "ParentId": "242769", "Score": "2" } }, { "body": "<p>Presuming that you are not asking for code-golfing recommendations, here are a few observations.</p>\n\n<p>It would be better to separate the input operations from the code that determines the number of winning matches. For example, separating the concerns lets you test the input code separately from the calculating code. Or lets you change where the input comes from: the command line, a file, a url, user input on a web page, etc.</p>\n\n<p>The current code has a O(n^2) complexity. It is obvious that the outer <code>for index in range(0, N)</code> loop runs <code>N</code> times. What may not be so obvious is that each call to <code>min</code>, <code>max</code>, and <code>remove</code> also processes the entire list, for another N times (and there are 8 calls each time through the outer loop). That's O(N * 8N) = O(N^2). So if the length of the lists is doubles, the time spent on the loop goes up by about 4 times. (The lists get shorter each loop, so in the average, <code>min</code> etc. process half the loop but O(N * 8N/2) is still O(N^2)). Sorting the lists would be O(N log N).</p>\n\n<p>The second loop that counts the wins can be eliminated. You already know that you win the match in the <code>else</code> clause of the first loop. Just count the winners there. </p>\n\n<p>Lastly, it is not necessary to actually make the pairings to determine how many would be won.</p>\n\n<p>Put that together, and you get something like:</p>\n\n<pre><code>def calculate_winners(us, them):\n \"\"\"count how many matches we would win by choosing \n which wrestlers to pair up.\n \"\"\"\n us = sorted(us, reverse=True) # largest to smallest\n them = sorted(them, reverse=True)\n\n winners = 0\n us_index = 0\n for opponent in them:\n if us[us_index] &gt; opponent:\n winners += 1\n us_index += 1\n\n return winners\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T06:19:06.293", "Id": "242788", "ParentId": "242769", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:43:03.037", "Id": "242769", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Shorten runtime of this Python program" }
242769
<p>I am working with Cassandra where I am getting some stuff out of it using <code>Datastax C# driver</code>. </p> <p>Below is my code which interacts with Cassandra db and in my <code>GetAsync</code> method I am extracting stuff from three different tables by making multiple async calls for each client id and item id.</p> <p>Earlier we were using <code>IN</code> clause queries and we found out that performance is not good with that so we change the client code to do multiple async calls in parallel and came up with below code.</p> <pre><code>public class CassandraUtils { private const string itemMapStmt = "FROM product_data WHERE client_id = ? PER PARTITION LIMIT 1"; private const string itemSelectStatement = "FROM item WHERE item_id = ? PER PARTITION LIMIT 1"; private const string itemProStmt = "FROM process_holder WHERE item_id = ? AND process_id = ? PER PARTITION LIMIT 1"; private readonly IResponseMapper rpm; private readonly Cluster cluster; private readonly ISession session; private readonly IMapper mapper; public CassandraUtils(string endpoints, IResponseMapper responseMapper) { rpm = responseMapper; var poolOptions = new PoolingOptions() .SetMaxConnectionsPerHost(HostDistance.Remote, 20) .SetMaxConnectionsPerHost(HostDistance.Local, 20) .SetMaxRequestsPerConnection(1000); cluster = Cluster.Builder() .AddContactPoints(endpoints) .WithApplicationName("Test") .WithReconnectionPolicy(new ConstantReconnectionPolicy(100L)) .WithLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc5"))) .WithPoolingOptions(poolOptions) .WithQueryOptions(new QueryOptions() .SetConsistencyLevel(ConsistencyLevel.LocalQuorum) .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)) .WithCompression(CompressionType.LZ4) .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(6000)) .Build(); var keyspace = Environment.GetEnvironmentVariable("keyspace_name"); session = cluster.Connect(keyspace); session.UserDefinedTypes.Define( UdtMap.For&lt;ASHelper&gt;("as") .Map(a =&gt; a.Url, "url").Map(a =&gt; a.Id, "id"), UdtMap.For&lt;MonthlyProcess&gt;("monthly_process") ); mapper = new Mapper(session); } /** * * Below method gets data from all 3 different tables by making multiple async calls. * */ public async Task&lt;IList&lt;Item&gt;&gt; GetAsync(IList&lt;int&gt; clientIds, int processId, int proc, Kyte kt) { var clientMaps = await ProcessCassQueries(clientIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemMapPoco&gt;(itemMapStmt, batch), "GetPIMValue"); if (clientMaps == null || clientMaps.Count &lt;= 0) { return null; } var itemIds = clientMaps.SelectMany(x =&gt; x.ItemIds).Where(y =&gt; y != null).ToList(); var itemsTask = ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemPoco&gt;(itemSelectStmt, batch), "GetAsync"); var itemProTask = ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemProPoco&gt;(itemProStmt, batch, processId), "GetIPValue"); var items = await itemsTask; if (items.Count &lt;= 0) { return null; } var itmDictionary = items.ToDictionary(dto =&gt; dto.ItemId, dto =&gt; rpm.MapToItem(dto, proc)); var itmProDict = itemIds.ToDictionary&lt;int, int, ItemProPoco&gt;(id =&gt; id, id =&gt; null); var holder = new List&lt;int&gt;(); var itemPrices = await itemProTask; itemPrices.ForEach(i =&gt; { if (i != null) itmProDict[i.ItemId] = i; }); foreach (var ip in itmProDict) if (ip.Value == null) holder.Add(ip.Key); if (holder.Count &gt; 0) { var ipHolder = await ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemProPoco&gt;(itemProStmt, batch, kt.Pid), "GetIPValue"); ipHolder.ToList().ForEach(ipf =&gt; { if (ipf != null) itmProDict[ipf.ItemId] = ipf; }); } return itmDictionary.Select(kvp =&gt; { itmProDict.TryGetValue(kvp.Key, out var ip); if (kvp.Value != null) { rpm.convert(ip, kvp.Value); return kvp.Value; } return null; }).Where(s =&gt; s != null).ToList(); } /** * * Below method does multiple async calls on each table for their corresponding id's. * */ private async Task&lt;List&lt;T&gt;&gt; ProcessCassQueries&lt;T&gt;(IList&lt;int&gt; ids, Func&lt;CancellationToken, int, Task&lt;T&gt;&gt; mapperFunc, string msg) where T : class { var requestTasks = ids.Select(id =&gt; ProcessCassQuery(ct =&gt; mapperFunc(ct, id), msg)); return (await Task.WhenAll(requestTasks)).Where(e =&gt; e != null).ToList(); } // this might not be good idea to do it private Task&lt;T&gt; ProcessCassQuery&lt;T&gt;(Func&lt;CancellationToken, Task&lt;T&gt;&gt; requestExecuter, string msg) where T : class { return requestExecuter(CancellationToken.None); } } </code></pre> <p>I am using latest datastax c# driver to interact with cassandra.</p> <p><strong>Cluster Info:</strong></p> <ul> <li>We have a 6 nodes cluster all in one dc with RF as 3.</li> <li>We read/write as local quorum.</li> <li>And we have row caching enabled as well.</li> </ul> <p><strong>Few questions:</strong></p> <p>I am looking to see if there is anything that can be improved or written efficiently in my <code>GetAsync</code>, <code>ProcessCassQueries</code> and <code>ProcessCassQuery</code> method? Since I am pretty new to <code>C#</code> so it might not be efficient way to do what I am doing currently. I need to execute multiple clientIds and itemIds queries in parallel to cassandra so I came up with above which does the job but not sure whether it is the efficient way to do it.</p> <p>One thing I realized is - I am doing lot of concurrent async calls for each table to cassandra db which might not be good idea. So maybe I should try to limit the number of async calls I can do using <code>Semaphore</code>? Also I am using lot of expensive <code>LINQ</code> calls like <code>ToDictionary</code>, <code>ToList</code> and <code>ForEach</code> that could be problematic under heavy load?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T20:49:25.650", "Id": "242772", "Score": "2", "Tags": [ "c#", "cassandra" ], "Title": "How to efficiently execute multiple async calls in parallel to cassandra in C#?" }
242772
<p>I've been trying to kind of teach myself "Modern C++" the last couple of months and I just finished this interview type problem and thought it would be a good one to get some feedback on. I not including the full implementation for brevity, just the relevant parts for the problem.</p> <blockquote> <p><strong>Random Node.</strong></p> <p>Implement a binary tree class which, in addition to the usual operations, has a method pick_random() which returns a random node from the tree. All nodes should be equally likely to be chosen.</p> </blockquote> <p>random_node.h</p> <pre><code>#include &lt;utility&gt; #include &lt;random&gt; #include &lt;memory&gt; namespace tree_problems { /* Random Node. * * Implement a binary tree class which, in addition to the usual operations, * has a method pick_random() which returns a random node from the tree. All * nodes should be equally likely to be chosen. */ template&lt;typename Ty&gt; class random_node { struct tree_node; using tree_node_ptr = std::unique_ptr&lt;tree_node&gt;; struct tree_node { Ty value; tree_node_ptr left{}, right{}; const tree_node* parent{}; std::size_t size{}; explicit tree_node( const Ty&amp; value, const tree_node* parent = nullptr ) : value{ value }, parent{ parent }, size{ 1 } { } tree_node( const tree_node&amp; other ) : value{ other.value }, parent{ other.parent }, size{ other.size } { if( other.left ) left = std::make_unique&lt;tree_node&gt;( other.left-&gt;value ); if( other.right ) right = std::make_unique&lt;tree_node&gt;( other.right-&gt;value ); } tree_node( tree_node&amp;&amp; other ) noexcept : value{ other.value }, parent{ other.parent }, size{ other.size } { left = std::move( other.left ); right = std::move( other.right ); } void insert_child( Ty value ) { if( value &lt;= this-&gt;value ) { left = std::make_unique&lt;tree_node&gt;( value, this ); } else { right = std::make_unique&lt;tree_node&gt;( value, this ); } } }; mutable std::mt19937 gen_; tree_node_ptr root_; public: explicit random_node( const unsigned int seed = std::random_device{}( ) ) : gen_{ seed } { } random_node( const std::initializer_list&lt;Ty&gt;&amp; values, const unsigned int seed = std::random_device{}( ) ) : random_node( seed ) { for( const auto&amp; val : values ) insert( val ); } /// &lt;summary&gt; /// insert node /// /// this approach for insertion increments the nodes it passes on the way /// down the tree to keep track of the total size of each node (total size = /// the node + all its children) in constant (additional) time to the normal log insert time. /// This approach does *not* keep the tree balanced or enforce any other invariants other than /// correct node size and basic left &lt;= current &lt; right. /// &lt;/summary&gt; /// &lt;param name="value"&gt;value to insert&lt;/param&gt; void insert( const Ty&amp; value ) { if( !root_ ) { root_ = std::make_unique&lt;tree_node&gt;( value ); return; } tree_node* node = root_.get(), * parent{}; while( node ) { ++node-&gt;size; parent = node; node = value &lt;= node-&gt;value ? node-&gt;left.get() : node-&gt;right.get(); } parent-&gt;insert_child( value ); } [[nodiscard]] auto next( const std::size_t&amp; min, const std::size_t&amp; max ) const -&gt; std::size_t { using uniform = std::uniform_int_distribution&lt;std::mt19937::result_type&gt;; const uniform distribution( min, max ); return distribution( gen_ ); } // forward the root to the recursive version. [[nodiscard]] auto pick_random() const -&gt; Ty&amp; { return pick_random( *root_ ); } /// &lt;summary&gt; /// pick random /// /// This routine looks at the "total" size of the node, which is maintained by /// the insert to be the the current node + the total number of nodes below it, /// so the root have the size of the total tree. Each call to pick random, we /// generate a uniform number between 1 and the the node size, this gives us /// a 1/n chance of picking the current node (and 1/1 for a leaf so we always /// exit). If the number is [1, left-size] we traverse left, otherwise we traverse /// right, and then re-roll with that node's size. /// /// &lt;/summary&gt; /// &lt;complexity&gt; /// &lt;run-time&gt;O(E[N/2])&lt;/run-time&gt; /// &lt;space&gt;O(E[N/2])&lt;/space&gt; /// &lt;/complexity&gt; /// &lt;param name="node"&gt;the starting node&lt;/param&gt; /// &lt;returns&gt;a node between [node, children] with equal probability&lt;/returns&gt; [[nodiscard]] auto pick_random( tree_node&amp; node ) const -&gt; Ty&amp; { const auto rnd = next( 1, node.size ); if( rnd == node.size ) return node.value; if( node.left &amp;&amp; rnd &lt;= node.left-&gt;size ) { return pick_random( *node.left ); } return pick_random( *node.right ); } }; } </code></pre> <p>random_node_tests.cpp</p> <pre><code>#include "pch.h" #include &lt;gtest/gtest.h&gt; #include &lt;typeinfo&gt; #include "../problems/tree.h" using namespace tree_problems; namespace tree_tests { /// &lt;summary&gt; /// Testing class for random node. /// &lt;/summary&gt; class random_node_tests : public ::testing::Test { protected: void SetUp() override { } void TearDown() override { } }; TEST_F( random_node_tests, case1 ) { // basic functionality. const auto rand = random_node&lt;int&gt;( { 1, 2, 3 }, 1234 ); const auto actual = rand.pick_random(); const auto expected = 2; EXPECT_EQ( actual, expected ); } TEST_F( random_node_tests, balanced_tree ) { // actually test the probability function. // fix the tree to be balanced tree with 7 nodes const auto values = std::initializer_list&lt;int&gt; { 4, 2, 6, 1, 3, 5, 7 }; const auto rand = random_node&lt;int&gt;( values, 2358 ); // storage for 10k draws auto results = std::map&lt;int, int&gt;(); const std::size_t iters = 1e6; for( auto index = std::size_t(); index &lt; iters; ++index ) { results[ rand.pick_random() ]++; } double max = 0.0f, min = 0.0f; for( const auto&amp; [key, value] : results ) { auto freq = static_cast&lt; double &gt;( value ) / iters; max = std::max( max, freq ); min = std::min( max, freq ); } const auto epsilon = 0.001; // error tolerance EXPECT_LT( max - min, epsilon ); } TEST_F( random_node_tests, unbalanced_tree ) { // actually test the probability function. // fix the tree to be an unbalanced tree with 11 nodes const auto values = std::initializer_list&lt;int&gt; { 4, 3, 6, 2, 1, 0, 5, 7, 9, 10, 11 }; // seed the generator const auto rand = random_node&lt;int&gt;( values, 6358 ); // storage for 10k draws auto results = std::map&lt;int, int&gt;(); const std::size_t iters = 1e6; for( auto index = std::size_t(); index &lt; iters; ++index ) { results[ rand.pick_random() ]++; } double max = 0.0f, min = 0.0f; for( const auto&amp; [key, value] : results ) { auto freq = static_cast&lt; double &gt;( value ) / iters; max = std::max( max, freq ); min = std::min( max, freq ); } const auto epsilon = 0.001; // error tolerance EXPECT_LT( max - min, epsilon ); } } </code></pre> <p>Looking for any design improvements, style suggestions, general approach, etc.</p>
[]
[ { "body": "<pre><code> explicit tree_node( const Ty&amp; value,\n const tree_node* parent = nullptr ) :\n</code></pre>\n\n<p>Might be better for <code>parent</code> to not be a default argument. (The root node is the special case for which it would be better to explicitly specify the <code>nullptr</code>).</p>\n\n<hr>\n\n<pre><code> void insert_child( Ty value )\n {\n if( value &lt;= this-&gt;value )\n {\n left = std::make_unique&lt;tree_node&gt;( value, this );\n }\n else\n {\n right = std::make_unique&lt;tree_node&gt;( value, this );\n }\n }\n</code></pre>\n\n<p>Maybe check that left and right are null before setting the value, or rename this function to <code>replace_child</code> or something.</p>\n\n<p>Also, is it intentional to allow equal values? (This has consequences for finding nodes.)</p>\n\n<hr>\n\n<p>Speaking of which, the instructions say \"in addition to the usual operations\"...</p>\n\n<p>I'd say this lacks a lot of the \"usual operations\", e.g. finding, iteration, erasure etc.</p>\n\n<hr>\n\n<pre><code> mutable std::mt19937 gen_;\n</code></pre>\n\n<p>Hmm. I think it might be better to have the user pass in the rng as a parameter to the <code>pick_random</code> function. That would allow using multiple rng's to access the same data.</p>\n\n<hr>\n\n<pre><code> tree_node* node = root_.get(),\n * parent{};\n</code></pre>\n\n<p>Ick. Separate definitions would be much clearer.</p>\n\n<hr>\n\n<pre><code> const uniform distribution( min, max );\n\n return distribution( gen_ );\n</code></pre>\n\n<p>This causes a compiler error for me because <code>uniform_int_distribution::operator()</code> isn't <code>const</code>.</p>\n\n<hr>\n\n<pre><code> [[nodiscard]] auto next( const std::size_t&amp; min, const std::size_t&amp; max ) const -&gt; std::size_t\n</code></pre>\n\n<p>I doubt passing <code>std::size_t</code> by <code>const&amp;</code> is faster than by value.</p>\n\n<p>Specifying the return type as auto, and then listing the return type after the function seems like unnecessary typing. We could just specify the return type up front.</p>\n\n<hr>\n\n<pre><code> [[nodiscard]] auto pick_random() const -&gt; Ty&amp; { return pick_random( *root_ ); }\n [[nodiscard]] auto pick_random( tree_node&amp; node ) const -&gt; Ty&amp; ...\n</code></pre>\n\n<p>These should return <code>Ty const&amp;</code> (or by value) not <code>Ty&amp;</code>. Changing the values in the nodes will break the tree!</p>\n\n<p>Since we have no access to <code>tree_node</code>s outside the class, that second function should probably be <code>private</code>.</p>\n\n<p>We might want to <code>throw</code> a specific error for an empty tree. (If we implemented iterators, we could return an end iterator, which would be better still.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T14:49:05.910", "Id": "476555", "Score": "0", "body": "This is great feedback, exactly what I was looking for. Cheers!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T14:23:35.233", "Id": "242801", "ParentId": "242774", "Score": "2" } } ]
{ "AcceptedAnswerId": "242801", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:07:05.360", "Id": "242774", "Score": "0", "Tags": [ "c++", "algorithm", "random", "c++17", "binary-tree" ], "Title": "C++ Random Tree Node" }
242774
<p>My own <strong>Givens</strong>-based QR decomposition function in R (pseudocode from Politecnico of Turin's math department) is the following:</p> <pre><code>&gt;Givens.fn&lt;-function(V) { tol&lt;-1.0*10^-14 m&lt;-dim(V)[1] n&lt;-dim(V)[2] spId&lt;-bandSparse(m,m,0,list(rep(1, m+1))) # computed just once Q&lt;-spId R&lt;-V sapply(1:n, function(j){ if (j&lt;m) { vapply((j+1):m, function(i){ # vectorized internal loop if(abs(R[i,j])&gt;tol) { G&lt;-spId x&lt;-R[j,j] y&lt;-R[i,j] norm&lt;-sqrt(x^2+y^2) c&lt;-x/norm s&lt;-y/norm G[j,j]=c G[i,i]=c G[j,i]=s G[i,j]=-s Q&lt;&lt;-G%*%Q R&lt;&lt;-G%*%R } return(1) # --&gt; saves 15% execution time! },FUN.VALUE=1.0) } }) Q&lt;-t(Q) return(list(Q,R)) } </code></pre> <p>It works fine, but the <em>givens(</em>) function provided in R by <em>pracma</em> is 134x faster on an total elapsed time around 10" (on my intel i5-3570 4core, 8GB desktop):</p> <pre><code>&gt;m&lt;-20; n&lt;-20 &gt;set.seed(1) &gt;X &lt;- as.matrix(replicate(n, runif(m))) &gt;library(rbenchmark) &gt;library(pracma) &gt;benchmark(Givens.fn(X), givens(X), order = "elapsed", replications = 10) test replications elapsed relative user.self sys.self user.child sys.child 2 givens(X) 10 0.08 1.000 0.08 0.00 NA NA 1 Givens.fn(X) 10 10.77 134.625 10.69 0.08 NA NA </code></pre> <p>Unfortunately, the pracma version accepts just square matrices, which is not my case. Any further code improvements? Any other Givens-based QR functions (even in C++)? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T22:13:36.960", "Id": "476491", "Score": "0", "body": "What is QR? Is it related to QR codes? Please [edit] your question to include this information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T20:59:28.670", "Id": "476861", "Score": "0", "body": "All the 3 ways to compute QR decomposition are well described [here](https://en.wikipedia.org/wiki/QR_decomposition)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T21:35:17.967", "Id": "476863", "Score": "0", "body": "As I said: please [edit] the question to include this information. A comment is the wrong place for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T21:40:10.607", "Id": "476864", "Score": "0", "body": "Could you perhaps remove the leading `>` from your code? This about syntax errors when pasting the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T21:42:33.147", "Id": "476865", "Score": "0", "body": "You could also format your code according to the Tidyverse convention. This way, the reviewers can focus on the interesting part of the code instead of complainingthatthecodeisunreadablebecauseofmissingspaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-25T12:02:24.327", "Id": "497880", "Score": "0", "body": "Why don't you use the R base function `qr`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T21:11:22.317", "Id": "242775", "Score": "2", "Tags": [ "c++", "performance", "matrix", "r" ], "Title": "Givens QR decomposition in R or C++: poor performance (or lack thereof) for rectangular matrices" }
242775
<pre class="lang-c prettyprint-override"><code> #include &lt;stdio.h&gt; #include &lt;cs50.h&gt; int main(void){ long long card; int i; int otherdigs; int multiply; int sum = 0; int sumofothers = 0; int finaladd; int length; int card_length; long long get_card; get_card = get_long_long(" Enter credit card: "); card = get_card; for (i = 0; i &lt; 16; i++) { sumofothers += card % 10; card /= 10; otherdigs = card % 10; card /= 10; if (otherdigs*2 &lt; 10) { multiply = otherdigs * 2; sum += multiply; } else { otherdigs = otherdigs*2-9; sum += otherdigs; } } finaladd = sum + sumofothers; if (finaladd % 10 == 0) { for (length = 0; length &lt; 14; length++) { get_card /= 10; } if ( get_card &gt;= 51 &amp;&amp; get_card &lt; 56 ) { printf("MasterCart\n"); } else if ( get_card &gt;= 3 &amp;&amp; get_card &lt; 4) { printf("AmericanExpress\n"); } else if ( get_card &lt; 0 || (get_card/10 &gt;= 4 &amp;&amp; get_card/10 &lt; 5) ) { printf("VIZA\n"); } else { printf(" Sorry, We Don't Support This Payment Company\n"); } } else { printf("This credit card is not valid \n"); } return 0; } </code></pre> <p>I recently took cs50 online course and this is my solution to <a href="https://docs.cs50.net/problems/credit/credit.html" rel="nofollow noreferrer">pset1</a> ( Credit ) This is my very first program that I actually thought through and did it all myself. The goal is to get the card number from user and check if it's valid ( Luhn’s Algorithm )</p> <p>I know the style is awful and the code is very messy too, but your opinion is very important to me... I spent maybe 5,6 hours for this. The question is do you think I can code? Become a programmer ? I mean do I have the right mind for it ? ( since this is my first without guide code ) BTW, I have no prior programming experience (only read some pages of K&amp;R 2 years ago),</p> <p>I even don't know half of c syntax yet. I know talent is a myth and all, <strong>but based on this code, do you think I'm any good at this?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T03:16:42.433", "Id": "476508", "Score": "0", "body": "Have you submitted this for a grade yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T04:16:37.600", "Id": "476516", "Score": "0", "body": "Welcome to Code Review. The former question title, which stated your concerns about the code, applied 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. I've changed it to reflect the goal of your code." } ]
[ { "body": "<p>the cs50.h that I have does not have a function: <code>get_long_long()</code>, so, for me, the code does not compile. My compiler suggested: <code>getlonglong()</code></p>\n\n<p>which credit card company is, normally, contained in the left digits of the card number, not in the right digits. so the posted code logic is (probably) not correct.</p>\n\n<p>The posted code fails to take into account the <code>security code</code> found on the back of the credit card.</p>\n\n<p>Not all credit cards use 16 digits, but rather varies by which vendor is producing the card. So that assumption should not be in the code logic.</p>\n\n<p>Suggest reading the digits as a string rather than as a <code>long long int</code>. Remember that a character digit - '0' results in a value 0...9, so the conversion, digit by digit is easy.</p>\n\n<p>OT: when compiling, always enable the warnings, then fix those warnings. ( for gcc, at a minimum use: <code>-Wall -Wextra -Wconversion -pedantic -std=gnu11</code> ) Note other compilers use different options to produce the same results.</p>\n\n<p>the posted code, when run through the compiler, results in the following:</p>\n\n<pre><code>gcc -O1 -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c \"untitled1.c\" -I.\n\nuntitled1.c: In function ‘main’:\n\nuntitled1.c:17:17: warning: implicit declaration of function ‘get_long_long’; did you mean ‘GetLongLong’? [-Wimplicit-function-declaration]\n get_card = get_long_long(\" Enter credit card: \");\n ^~~~~~~~~~~~~\n GetLongLong\n\nuntitled1.c:26:23: warning: conversion to ‘int’ from ‘long long int’ may alter its value [-Wconversion]\n sumofothers += card % 10;\n ^~~~\n\nuntitled1.c:29:20: warning: conversion to ‘int’ from ‘long long int’ may alter its value [-Wconversion]\n otherdigs = card % 10;\n ^~~~\n\nuntitled1.c:14:10: warning: unused variable ‘card_length’ [-Wunused-variable]\n int card_length;\n ^~~~~~~~~~~\n\nCompilation finished successfully.\n</code></pre>\n\n<p>regarding: <em>Compilation finished successfully</em> This only means the compiler provided some <code>workaround</code> for each of the problems it found in the code. It does NOT mean the correct/expected code was produced.</p>\n\n<p>Regarding you question about your suitability to become a programmer.</p>\n\n<p>All programmers started some where, usually fumbling through many many programs before they started thinking of problems in terms of the needed code to solve the problem, so your doing quite well and will get better and better as you gain experience.</p>\n\n<p>regarding: </p>\n\n<p><em>I even don't know half of c syntax yet.</em></p>\n\n<p>the C language is not that big. besides what you have in the posted code, there are <code>pointers</code> and the <code>while()</code> and <code>switch()</code> statement. Note: learning <code>pointers</code> can be a real pain. After that there are many many standard C library functions. In Linux, in a 'terminal' window, type <code>man functionName</code> to learn all about a function. The 'man' command is your best friend, After some 40+ years of programming, I still use that function regularly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T23:00:45.420", "Id": "476581", "Score": "0", "body": "@chux-ReinstateMonica, I'll remove that statement" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T22:28:44.320", "Id": "476777", "Score": "0", "body": "thank you for your answer, the logic is correct but not perfect and it works as you can see in the second loop, card number will divide until it reaches the 2 first left digits. regarding to security code it wasn't discussed in pset so i didn't include that, and for different digits length I'll use while instead of for loop so it's better optimized. thank you again" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T03:50:36.330", "Id": "242784", "ParentId": "242780", "Score": "5" } }, { "body": "<blockquote>\n <p>The question is do you think I can code?<br>\n Become a programmer ?<br>\n I mean do I have the right mind for it ?<br>\n do you think I'm any good at this?</p>\n</blockquote>\n\n<p>Yes, but code review is more on the code than the programmer.</p>\n\n<blockquote>\n <p>I know the style is awful and the code is very messy too, but your opinion is very important to me.</p>\n</blockquote>\n\n<p><strong>Use an auto formatter.</strong></p>\n\n<p>Many coding environments have one. Tip: well formatted code makes a good impression. Do not manual format - life is too short for that.</p>\n\n<p><strong>Enable all warnings</strong></p>\n\n<p>As well suggested by @user3629249, this saves you time and avoids learner mistakes.</p>\n\n<p><strong>Validate range from users</strong></p>\n\n<p>Users are notorious for bad input. Do not trust the input until vetted.</p>\n\n<pre><code>#define CARD_MAX 9999999999999999 /* Or whatever your limit */\nif (get_card &lt; 0 || get_card &gt; CARD_MAX) {\n printf(\"This credit card is not valid \\n\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T07:18:58.527", "Id": "476693", "Score": "0", "body": "Wouldn't 999999999999999 without any `L` suffix generate an error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T12:17:32.063", "Id": "476717", "Score": "0", "body": "@RolandIllig No. Why do you think it might?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:19:45.790", "Id": "476737", "Score": "0", "body": "I thought it would overflow an `int`, just like in Java. I don't remember that C had unbounded integer literals. I'll read it up later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:45:42.423", "Id": "476748", "Score": "0", "body": "@RolandIllig C does not have _unbounded_ integer literals. In C, integer constants at least well defined up to `LLONG_MAX` and up to `ULLONG_MAX` with a `u` suffix. That is at least 64-bit values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:19:48.930", "Id": "476766", "Score": "1", "body": "Cool, I didn't remember 6.4.4.1p5. Thank you for making me look it up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T22:40:57.333", "Id": "476779", "Score": "0", "body": "Thank you. That Yes you gave me means a lot to me... i really needed an expert opinion on this so i thought it's best to post it here, can you please recommend me some good sources such as K&R & c modern approach ? maybe not heavy as K&R, but with good projects/examples to work with ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T00:32:18.467", "Id": "476784", "Score": "1", "body": "@arverse I do have a ready reference for _good code_, I recommend reading highly rated reviews here and set aside K&R as a reference - it was good in the day." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T20:17:19.960", "Id": "242818", "ParentId": "242780", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T00:25:21.193", "Id": "242780", "Score": "2", "Tags": [ "beginner", "c", "homework" ], "Title": "Verify credit card number with Luhn's algorithm" }
242780
<p>I was doing <a href="https://leetcode.com/problems/search-in-rotated-sorted-array/" rel="nofollow noreferrer">Search in sorted array question from leetcode</a></p> <h2>Question</h2> <p>Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.</p> <p>(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).</p> <p>You are given a target value to search. If found in the array return its index, otherwise return -1.</p> <p>You may assume no duplicate exists in the array.</p> <p>Your algorithm's runtime complexity must be in the order of O(log n).</p> <h2>Example</h2> <p>Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4</p> <h2>My solution</h2> <pre><code>/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { for (let i=0; i&lt;nums.length; i++) { if (target === nums[i]) return i } return -1 }; </code></pre> <p>While this algo works, I am not sure if this is optimal or correct? for question with medium difficulty. Can someone verify it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T07:11:01.067", "Id": "476522", "Score": "0", "body": "Hello, I have seen the leetcode site and in the description of the challenge you forgot to write the most important information : *Your algorithm's runtime complexity must be in the order of O(log n)*. Please add it to the challenge description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T08:39:50.580", "Id": "476532", "Score": "0", "body": "@dariosicily done. Also, Isn't the complexity of the above algo 0(log n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T11:35:00.380", "Id": "476540", "Score": "1", "body": "Your code runs in `O(n)`, which is not fulfilling the requirement" } ]
[ { "body": "<p>I start from your code:</p>\n\n<pre><code>var search = function(nums, target) {\n for (let i=0; i&lt;nums.length; i++) {\n if (target === nums[i]) return i\n }\n return -1 \n};\n</code></pre>\n\n<p>And your question:</p>\n\n<blockquote>\n <p>While this algo works, I am not sure if this is optimal or correct?</p>\n</blockquote>\n\n<p>Your algorithm is correct but it is optimal ? The answer is nope because as from the comment by @CertainPerformance to your question your code runs in O(n).</p>\n\n<p>The hint is contained in the phrase <em>Your algorithm's runtime complexity must be in the order of O(log n)</em> that bounds the desired solution to the <a href=\"https://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow noreferrer\">binary search</a> having O(log n) complexity. The algorithm works if there is a sorted array, but with some modification can be adapted to a rotated array.</p>\n\n<p>Here my javascript code for the original binary search:</p>\n\n<pre><code>const search = function search(a, t) {\n let l = 0;\n let r = a.length - 1;\n\n while (l &lt;= r) {\n let m = Math.floor((l+r) /2);\n if (a[m] == t) { return m; }\n if (a[m] &lt; t) { l = m + 1; }\n if (a[m] &gt; t) { r = m - 1; } \n }\n return -1;\n}\n</code></pre>\n\n<p>My solution for a rotated array is quite similar but with a two if else inside the while cycle because we can have four different cases, I added an explanation after the code below:</p>\n\n<pre><code>const search = function search(a, t) {\n let l = 0;\n let r = a.length - 1;\n\n while (l &lt;= r) {\n let m = Math.floor((l+r) /2);\n if (a[m] == t) { return m; }\n\n if (a[m] &lt; a[r]) {\n if (t &gt; a[m] &amp;&amp; t &lt;= a[r]) { \n l = m + 1; \n } else { \n r = m - 1; \n }\n } else {\n if (t &gt;= a[l] &amp;&amp; t &lt; a[m]) { \n r = m - 1; \n }\n else {\n l = m + 1;\n }\n }\n }\n\n return -1;\n}\n\nconsole.log(search([4,5,6,7,0,1,2], 0));\nconsole.log(search([4,5,6,7,0,1,2], 5));\nconsole.log(search([4,5,6,7,0,1,2], 3));\nconsole.log(search([1, 3], 3));\nconsole.log(search([4,5,6,7,8,1,2,3], 8));\n</code></pre>\n\n<p>Substantially if I have a [l,..m, .. r] interval I have two possible cases:</p>\n\n<ol>\n<li>a[m] &lt; a[r] --> consecutive ascending numbers, so if a[m] &lt; t &lt;=\na[r] in the next iteration I will examine the interval [m + 1, r]\notherwise I will examine the interval [l, r - 1]</li>\n<li>a[m] >= a[r] --> there are rotated elements like for example [7, 0,\n1, 2] , so I am sure the left array contains only ascending numbers.\nIn this case if a[l] &lt;= a[t] &lt; a[m] in the next iteration I will\nexamine the interval [l, m - 1] otherwise I will examine the\ninterval [m + 1, r].</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T20:27:54.997", "Id": "242819", "ParentId": "242785", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T05:25:01.667", "Id": "242785", "Score": "2", "Tags": [ "javascript", "programming-challenge", "binary-search" ], "Title": "Leetcode Search in Rotated Sorted Array" }
242785
<p>For context, I worked on the LeetCode May 2020 Challenge Week 3 Day 1. The challenge was described as this:</p> <blockquote> <p>Given a string, sort it in decreasing order based on the frequency of characters.</p> <p><strong>Example 1:</strong></p> <p>Input: <code>"tree"</code></p> <p>Output: <code>"eert"</code></p> <p>Explanation: <code>'e'</code> appears twice while <code>'r'</code> and <code>'t'</code> both appear once. So <code>'e'</code> must appear before both <code>'r'</code> and <code>'t'</code>. Therefore <code>"eetr"</code> is also a valid answer.</p> <p><strong>Example 2:</strong></p> <p>Input: <code>"cccaaa"</code></p> <p>Output: <code>"cccaaa"</code></p> <p>Explanation: Both <code>'c'</code> and <code>'a'</code> appear three times, so <code>"aaaccc"</code> is also a valid answer. Note that <code>"cacaca"</code> is incorrect, as the same characters must be together.</p> <p><strong>Example 3:</strong></p> <p>Input: <code>"Aabb"</code></p> <p>Output: <code>"bbAa"</code></p> <p>Explanation: <code>"bbaA"</code> is also a valid answer, but <code>"Aabb"</code> is incorrect. Note that <code>'A'</code> and <code>'a'</code> are treated as two different characters.</p> </blockquote> <p>Anyways, I looked up some popular solutions. One was to get the frequency of each character and sort, and the other was the use a heap. I liked both of these solutions, but I wanted to make one where there was no sorting.</p> <p>My solution involved an idea of an <code>ArrayList</code> of "tiers," where the index of the tier represents the frequency. Each tier consists of an <code>ArrayList</code> containing the characters which the corresponding frequency. As letters increase in frequency, the higher frequency tier they move up. I also used a <code>HashMap</code> to keep track of which frequency tier each character was in. Upon finishing iterating through the whole string, I simply use a <code>StringBuilder</code> to append the letters starting at the bottom tier, reverse the <code>StringBuilder</code>, then return the String. I was hoping someone could give me pointers (ha, code pun) on optimizing/modifying this approach without including any kind of sorting. Below is the functional code:</p> <pre><code>public static String frequencySort(String s) { if (s.length() &lt;= 1) return s; ArrayList&lt;ArrayList&lt;Character&gt;&gt; tieredFreq = new ArrayList&lt;&gt;(); // stores characters at their proper frequency "tier" HashMap&lt;Character, Integer&gt; tierOfChars = new HashMap&lt;&gt;(); // maps the characters to their current frequency tier tieredFreq.add(null); // tier 0 for (char c : s.toCharArray()) { tierOfChars.put(c, tierOfChars.getOrDefault(c, 0) + 1); // add char or increment the tier of the character int i = tierOfChars.get(c); // i = tier of the character if (tieredFreq.size() &lt;= i) tieredFreq.add(new ArrayList&lt;&gt;()); // if not enough tiers, add a new tier if (i &gt; 1) tieredFreq.get(i - 1).remove(new Character(c)); // if c exists in previous tier, remove it tieredFreq.get(i).add(c); // add to new tier } StringBuilder result = new StringBuilder(); for (int i = 1; i &lt; tieredFreq.size(); i++) { // iterate through tiers ArrayList&lt;Character&gt; tier = tieredFreq.get(i); // get tier for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier for (int j = 0; j &lt; i; j++) result.append(c); } } result.reverse(); // reverse, since result is currently in ascending order return result.toString(); } </code></pre>
[]
[ { "body": "<p>You have conceived a theoretical model that works. And avoids sorting.</p>\n\n<ul>\n<li>Tiers by frequency</li>\n<li>Every tier contains letters of that frequency</li>\n</ul>\n\n<p>It will come at no surprise, that moving a char from on frequency's bin to the next frequency's bin will cost at least as much as sorting. But it is a nice mechanism\none sees too rare, and might have its application in vector operations, GPUs or whatever.</p>\n\n<ol>\n<li><p>Improved could be the names. \"Tier\" one inclines to love, and might be apt, but does the term help in understanding the code?</p></li>\n<li><p>Use if possible more general interfaces implemented by specific classes, like <code>List&lt;T&gt; list = new ArrayList&lt;&gt;();</code>. This is more flexible, when passing to methods, reimplementing with another class.</p></li>\n<li><p>The comment to remain is for adding null for the frequency 0.</p></li>\n<li><p>For characters in a tier use a <code>Set</code>. As implementation I used a <code>TreeSet</code> which is sorted to give nicer output.</p></li>\n<li><p>Use as index not <code>i</code> but rather <code>freq</code>.</p></li>\n<li><p>Moving from one frequency to the next higher can be done in two separate steps old+new. That makes the code more readable.</p></li>\n</ol>\n\n<p>so:</p>\n\n<pre><code>public static String frequencySort(String s) {\n if (s.length() &lt;= 1) return s;\n\n List&lt;Set&lt;Character&gt;&gt; charsByFrequency = new ArrayList&lt;&gt;(); // stores characters at their proper frequency \"tier\"\n Map&lt;Character, Integer&gt; frequencyMap = new HashMap&lt;&gt;(); // maps the characters to their current frequency tier\n charsByFrequency.add(null); // entry for frequency 0 is not used\n\n for (char c : s.toCharArray()) {\n Character ch = c; // Does ch = Character.valueOf(c);\n int oldFreq = frequencyMap.getOrDefault(c, 0);\n if (oldFreq != 0) {\n charsByFrequency.get(oldFreq).remove(ch);\n }\n int freq = oldFreq + 1;\n if (freq &gt;= charsByFrequency.size()) {\n charsByFrequency.add(new TreeSet());\n }\n charsByFrequency.get(freq).add(ch);\n frequencyMap.put(ch, freq);\n }\n\n StringBuilder result = new StringBuilder();\n for (int i = 1; i &lt; charsByFrequency.size(); i++) { // iterate through tiers\n Set&lt;Character&gt; tier = charsByFrequency.get(i); // get tier\n for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier\n for (int j = 0; j &lt; i; j++) result.append(c);\n }\n }\n\n result.reverse(); // reverse, since result is currently in ascending order\n return result.toString();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T20:34:24.887", "Id": "476664", "Score": "0", "body": "Thank you so much! This is a much more elaborate and thorough response than expected. I'm a first year college programming student, so all insight will probably be helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T21:13:10.677", "Id": "242820", "ParentId": "242786", "Score": "5" } } ]
{ "AcceptedAnswerId": "242820", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T05:35:47.747", "Id": "242786", "Score": "5", "Tags": [ "java", "programming-challenge" ], "Title": "Sort Characters By Frequency Java" }
242786
<p>I am trying out <code>websockets</code> using the python async framework <code>aiohttp</code>. Basically I have created a game which will include multiple players and they will be able to chat using web sockets. There could be multiple game rooms and a player will be in a single room at a time. I believe I have the implementation right. Please look into it.</p> <pre><code>from aiohttp import web, WSMsgType from bson.objectid import ObjectId from models import Game routes = web.RouteTableDef() @routes.get('/ws/{game_id}/{player_id}') async def create(request): game_id = request.match_info['game_id'] player_id = request.match_info['player_id'] ws_current = web.WebSocketResponse() ws_ready = ws_current.can_prepare(request) if not ws_ready.ok: msg = "Sorry, something went wrong!" return web.json_response({'error': msg}) await ws_current.prepare(request) query = {'_id': ObjectId(game_id), 'active': True} game = await Game.find_game(query=query, db=request.app['mongodb']) if game is None: msg = "Game over, start a new game" await ws_current.send_json({'action': 'error', 'name': player_id, 'msg': game_id}) await ws_current.close() return if not any(player_id == str(player['_id']) for player in game['players']): msg = "You have not joined the game" await ws_current.send_json({'action': 'error', 'name': player_id, 'msg': msg}) await ws_current.close() return await ws_current.send_json({'action': 'connect', 'name': player_id}) # notify other players that a new player has joined for player in game['players']: if str(player['_id']) in request.app['websockets']: player_ws = request.app['websockets'][str(player['_id'])] await player_ws.send_json({'action': 'join', 'name': player_id}) request.app['websockets'][player_id] = ws_current while True: msg = await ws_current.receive() if msg.type == WSMsgType.text: if msg.data == 'close': await ws_current.close() else: for player in game['players']: if str(player['_id']) in request.app['websockets']: player_ws = request.app['websockets'][str( player['_id'])] if player_ws is not ws_current: await player_ws.send_json( {'action': 'sent', 'name': player_id, 'text': msg.data}) elif msg.type == WSMsgType.ERROR: print('ws connection closed with exception %s' % ws_current.exception()) else: break if player_id in request.app['websockets']: del request.app['websockets'][player_id] # notify other players that the player has left for player in game['players']: if str(player['_id']) in request.app['websockets']: player_ws = request.app['websockets'][str(player['_id'])] await player_ws.send_json({'action': 'disconnect', 'name': player_id}) return ws_current </code></pre> <p>But the code doesn't look very good or pythonic as they say. Could you please help me out with this and also if there are things I should change with the logic as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:11:59.550", "Id": "476545", "Score": "0", "body": "What is `web`? I have a feeling it's not [PyPI's web package](https://pypi.org/project/web/) and I know of no such packages called web in the stdlib. Searching for it is also nigh impossible, since \"web\" is so generic. Without this information it would be impossible for me to answer this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T14:16:32.277", "Id": "476553", "Score": "0", "body": "@Peilonrayz It is just a module of aiohttp. I will update the question with the imports." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:04:53.060", "Id": "242797", "Score": "4", "Tags": [ "python", "python-3.x", "asynchronous", "async-await", "socket" ], "Title": "Chat using async Python and sockets" }
242797
<p>I am making a simple API for news items using Python and the Bottle framework.</p> <p>I return a Python dictionary from my endpoints as Bottle converts this to JSON automatically in the response to the client.</p> <p>I wanted to ensure a consistent structure to the responses, so I have declared a template dictionary. The code for each endpoint makes a deep copy of this then modifies the relevant data before returning it.</p> <pre><code>import bottle from bottle import route from copy import deepcopy as deepcopy # Dictionary for response template response_dict = { "status" : "ok", "code" : 0, "error" : False, "message" : "", "result" : {} } # Example route @route('/example') def example(): return_dict = deepcopy(response_dict) return_dict["message"] = "Success" return_dict["result"] = { "title" : "Test Title", "body" : "&lt;p&gt;Lorem ipsum dolor sit amet...&lt;/p&gt;" } return return_dict </code></pre> <p>I would like to know if there is a better way to use a template for a JSON response and whether the structure of my dictionary is appropriate.</p>
[]
[ { "body": "<p>There is no need to use <code>deepcopy</code> here. Just have a function that returns a new object when you need it. And while you're at it, just make the <code>message</code> and the <code>result</code> parameters of that function. Or even all of them:</p>\n\n<pre><code>def json_response(message, result, status=\"ok\", code=0, error=False):\n return {\n \"status\" : status,\n \"code\" : code,\n \"error\" : error,\n \"message\" : message,\n \"result\" : result\n }\n\n@route('/example')\ndef example():\n result = {\n \"title\" : \"Test Title\",\n \"body\" : \"&lt;p&gt;Lorem ipsum dolor sit amet...&lt;/p&gt;\"\n }\n return json_response(\"Success\", result)\n</code></pre>\n\n<p>Having all as parameters, but with default values, allows you to do this in the future:</p>\n\n<pre><code>json_response(\"Failure\", None, status=\"fail\", code=404, error=True)\n</code></pre>\n\n<p>In the end it depends on how often you need to use this template whether or not this is better than just directly returning the dictionary <a href=\"https://www.python.org/dev/peps/pep-0020/#the-zen-of-python\" rel=\"nofollow noreferrer\">explicitly</a>:</p>\n\n<pre><code>@route('/example')\ndef example():\n return {\n \"status\" : \"ok\",\n \"code\" : 0,\n \"error\" : False,\n \"message\" : \"Success\",\n \"result\" : {\n \"title\" : \"Test Title\",\n \"body\" : \"&lt;p&gt;Lorem ipsum dolor sit amet...&lt;/p&gt;\"\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:50:46.850", "Id": "476550", "Score": "0", "body": "Thanks for this. I was fixated on using the dictionary and hadn’t thought about using a function. It seems much more straightforward." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:46:02.600", "Id": "242799", "ParentId": "242798", "Score": "1" } } ]
{ "AcceptedAnswerId": "242799", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T13:35:18.113", "Id": "242798", "Score": "1", "Tags": [ "python", "json", "api", "bottle" ], "Title": "Using a dictionary template for consistent response structure from an API" }
242798
<p>Aim: To make pages located in site.com/page-1, site.com/page-2. Those pages are pretty much static so I won't use database.</p> <p>First, I've created the PageController.</p> <pre><code>class PageController extends Controller { public function page($slug) { $page = $this-&gt;pageContents($slug); return view('page', ['page' =&gt; $page]); } public function pageContents($slug) { $page = []; $page["slug"] = $slug; if ($slug == "page-1") { $page["title"] = "Page 1"; $page["content"] = "Content.."; } if ($slug == "page-2") { $page["title"] = "Page 2"; $page["content"] = "Content.."; } return $page; } } </code></pre> <p>web.php (Routes):</p> <pre><code>Route::get('/{page-1}', 'PageController@page')-&gt;name('page-1'); Route::get('/{page-2}', 'PageController@page')-&gt;name('page-2'); </code></pre> <p>Would appreciate any reviews!</p>
[]
[ { "body": "<p>Not sure that it makes much difference, but I find this simpler</p>\n\n<pre><code>class PageController extends Controller\n{\n\n public function page1()\n {\n return view('page', [\n 'page' =&gt; [\n 'slug' =&gt; 'page-1',\n 'title' =&gt; 'Page 1',\n 'content' =&gt; 'Content..',\n ]\n ]);\n }\n\n public function page2()\n {\n return view('page', [\n 'page' =&gt; [\n 'slug' =&gt; 'page-2',\n 'title' =&gt; 'Page 2',\n 'content' =&gt; 'Content..',\n ]\n ]);\n }\n\n}\n</code></pre>\n\n<p>web.php (Routes):</p>\n\n<pre><code>Route::get('/page-1', 'PageController@page1')-&gt;name('page-1');\nRoute::get('/page-2', 'PageController@page2')-&gt;name('page-2');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T23:33:54.097", "Id": "242828", "ParentId": "242805", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T15:30:38.907", "Id": "242805", "Score": "-2", "Tags": [ "php", "laravel" ], "Title": "Laravel Page Controller" }
242805
<p>This is a solution to this problem: <a href="https://www.codewars.com/kata/53005a7b26d12be55c000243/train/ruby" rel="nofollow noreferrer">https://www.codewars.com/kata/53005a7b26d12be55c000243/train/ruby</a></p> <p>The task is to make a simple interpreter that will take expressions and calculate the results. I'm just looking for general feedback on following Ruby standard practices and ways I could shorten the code by omitting parentheses for example:</p> <pre class="lang-rb prettyprint-override"><code>class Interpreter def input expr if expr.strip == "" return "" end # puts expr tokens = tokenize(expr).map{ |a| a[0] } parsedTokens = parseTokens tokens if parsedTokens.length == 1 if !@variables.key? parsedTokens[0].name raise 'unitialized variable' end return @variables[parsedTokens[0].name] end # todo can the user enter just a number? leastPrecedentNode = partition parsedTokens rootOfBuiltTree = buildTree leastPrecedentNode result = calculateRecursive rootOfBuiltTree result end private class OperatorInfo @@operators = { '=' =&gt; 0, '+' =&gt; 1, '-' =&gt; 1, '*' =&gt; 2, '/' =&gt; 2, '%' =&gt; 2 } @@assignmentOperator = '=' def self.operators @@operators end def self.assignmentOperator @@assignmentOperator end end class ParseUnit attr_reader :overallIndex attr_reader :nestLevel attr_reader :indexInLevel def initialize(overallIndex, nestLevelArg, indexInLevelArg) @overallIndex = overallIndex @nestLevel = nestLevelArg @indexInLevel = indexInLevelArg end end class ConstantParse &lt; ParseUnit attr_reader :value def initialize(value, overallIndex, nestLevel, indexInLevel) super(overallIndex, nestLevel, indexInLevel) @value = value end end class OperatorParse &lt; ParseUnit attr_reader :operator attr_reader :priority def initialize(operator, overallIndex, nestLevel, indexInLevel) super(overallIndex, nestLevel, indexInLevel) @operator = operator @priority = OperatorInfo.operators[operator] end end class VariableParse &lt; ParseUnit attr_reader :name def initialize(name, overallIndex, nestLevel, indexInLevel) super(overallIndex, nestLevel, indexInLevel) @name = name end end def parseTokens (tokens) ret = [] nestLevel = 0 indexes = [0] overallIndex = 0 tokens.each do | t | # can be operator, constant number, paren, variable # puts "curToken is #{t}" case t #operator when OperatorInfo.operators.keys.include?(t).to_s == 'true' ? t : '' ret.push OperatorParse.new t, overallIndex, nestLevel, indexes[nestLevel] overallIndex += 1 indexes[nestLevel] += 1 # is a constant number when /\A\d+\z/ ret.push ConstantParse.new t.to_i, overallIndex, nestLevel, indexes[nestLevel] overallIndex += 1 indexes[nestLevel] += 1 when '(' nestLevel += 1 if indexes.length &lt;= nestLevel indexes.push(0) end when ')' nestLevel -= 1 #variable when String ret.push VariableParse.new t, overallIndex, nestLevel, indexes[nestLevel] overallIndex += 1 indexes[nestLevel] += 1 else puts "error in parse tokens with token #{t}" end end ret end class OperatorNode attr_reader :operator attr_reader :left attr_reader :right def initialize(operator, left, right) @left = left @right = right @operator = operator @priority = OperatorInfo.operators[operator] end end def partition(parsedTokens) opTokens = parsedTokens.select { |token| token.is_a?(OperatorParse) } op = leastPrecedentOp opTokens left = parsedTokens.select { |x| x.overallIndex &lt; op.overallIndex } right = parsedTokens.select { |x| x.overallIndex &gt; op.overallIndex } OperatorNode.new op, left, right end def leastPrecedentOp opTokens if opTokens.length == 1 return opTokens[0] end # todo dry out this sort with the next one sortedByNestLevel = opTokens.sort_by { |x| x.nestLevel } nestLevelTies = sortedByNestLevel.select { |x| x.nestLevel == sortedByNestLevel[0].nestLevel } if nestLevelTies.length == 1 return nestLevelTies[0] end sortedByPriority = nestLevelTies.sort_by { |x| x.priority } priorityTies = sortedByPriority.select { |x| x.priority == sortedByPriority[0].priority } if priorityTies.length == 1 return priorityTies[0] end sortedByIndexInLevel = priorityTies.sort_by { |x| x.indexInLevel * -1 } sortedByIndexInLevel[0] end def buildTree(opNode) # puts opNode # base case leftIsSingle = opNode.left.length == 1 rightIsSingle = opNode.right.length == 1 if leftIsSingle &amp;&amp; rightIsSingle return OperatorNode.new opNode.operator.operator, opNode.left, opNode.right end # recursive call leftRet = nil if leftIsSingle leftRet = opNode.left[0] else leftPart = partition opNode.left leftRet = buildTree leftPart end rightRet = nil if rightIsSingle rightRet = opNode.right[0] else rightPart = partition opNode.right rightRet = buildTree rightPart end # combine and return OperatorNode.new opNode.operator.operator, leftRet, rightRet end def calculateRecursive node # base case if isLeaf? node, nil return getValue node end leftIsLeaf = isLeaf? node, node.left rightIsLeaf = isLeaf? node, node.right if leftIsLeaf &amp;&amp; rightIsLeaf if node.operator == OperatorInfo.assignmentOperator return calculateImpl node.operator, node.left[0].name, (getValue node.right) end leftVal = getValue node.left rightVal = getValue node.right return calculateImpl node.operator, leftVal, rightVal end # recursive call leftResult = nil if leftIsLeaf &amp;&amp; node.operator != OperatorInfo.assignmentOperator leftResult = getValue node.left elsif leftIsLeaf &amp;&amp; node.operator leftResult = node.left.name else leftResult = calculateRecursive node.left end rightResult = nil if rightIsLeaf rightResult = getValue node.right else rightResult = calculateRecursive node.right end # combine and return result = calculateImpl node.operator, leftResult, rightResult result end def isLeaf?(parent, node) # if parent isConstant = node.is_a? ConstantParse if node.is_a? Array isConstant = node[0].is_a? ConstantParse end isVariable = node.is_a? VariableParse if node.is_a? Array isVariable = node[0].is_a? VariableParse end return isConstant || isVariable end def getValue node nodeVal = nil if node.is_a? Array nodeVal = node[0] else nodeVal = node end if nodeVal.is_a? ConstantParse return nodeVal.value end if nodeVal.is_a? VariableParse if @variables.key? nodeVal.name return @variables[nodeVal.name] end return nodeVal.name end end def calculateImpl(operator, left, right) #puts "#{left} #{operator} #{right}" case operator when '+' return left + right when '-' return left - right when '/' return left.to_f / right when '*' return left * right when '%' return left % right when '=' @variables[left] = right return right end end def initialize @variables = {} end def tokenize program return [] if program == '' regex = /\s*([-+*\/\%=\(\)]|[A-Za-z_][A-Za-z0-9_]*|[0-9]*\.?[0-9]+)\s*/ program.scan(regex).select { |s| !(s =~ /^\s*$/) } end end </code></pre>
[]
[ { "body": "<p>What you mentioned about removing parentheses like you did in <code>def input expr</code> method definition, in general <a href=\"https://github.com/rubocop-hq/ruby-style-guide#method-parens\" rel=\"nofollow noreferrer\">is a bad practice</a>. My suggestions:</p>\n\n<ul>\n<li>Start running <a href=\"https://github.com/rubocop-hq/rubocop#installation\" rel=\"nofollow noreferrer\"><code>rubocop -a your_path/file.rb</code></a> to auto-correct most of style problems in your code.</li>\n<li>Fix manually variable names like <code>parsedTokens</code> or method names like <code>parseTokens</code> to be <a href=\"https://github.com/rubocop-hq/ruby-style-guide#snake-case-symbols-methods-vars\" rel=\"nofollow noreferrer\">snake cased</a>.</li>\n<li>Most of the time, there are no good reasons to use <a href=\"https://github.com/rubocop-hq/ruby-style-guide#no-class-vars\" rel=\"nofollow noreferrer\">class variables</a> like you did in <code>@@operators</code>. Actually, I'd move those vars. out of <code>OperatorInfo</code> and remove that class definition, then defining them as constants in the main class as:</li>\n</ul>\n\n<pre><code>class Interpreter\n # .freeze is to really define these variables as constants (immutables)\n OPERATORS = { '=' =&gt; 0, '+' =&gt; 1, '-' =&gt; 1, '*' =&gt; 2, '/' =&gt; 2, '%' =&gt; 2 }.freeze\n ASSIGNMENT_OPERATOR = '='.freeze\n</code></pre>\n\n<ul>\n<li>You can define readers in a single call, like:</li>\n</ul>\n\n<pre><code> class ParseUnit\n attr_reader :overall_index, :nest_level, :index_in_level\n</code></pre>\n\n<ul>\n<li>If possible, define sub classes like <code>OperatorNode</code> in separate files. If not, defining them under <code>private</code> <a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Lint/UselessAccessModifier\" rel=\"nofollow noreferrer\">isn't really effective</a>:</li>\n</ul>\n\n<pre><code>class Interpreter\n def self.calling_inner_class\n OperatorNode\n end\n\n private\n class OperatorNode\n # ...\n end\nend\n\nInterpreter.calling_inner_class # Interpreter::OperatorNode\n# This shouldn't work for private classes\nInterpreter::OperatorNode # =&gt; Interpreter::OperatorNode\n</code></pre>\n\n<p>An option to make them really private is adding <a href=\"https://apidock.com/ruby/Module/private_constant\" rel=\"nofollow noreferrer\"><code>private_constant</code></a> to every class definition like:</p>\n\n<pre><code>class Interpreter\n def self.calling_inner_class\n # This operates normally\n OperatorNode\n end\n\n class OperatorNode\n # ...\n end\n private_constant :OperatorNode\nend\n\nInterpreter.calling_inner_class # Interpreter::OperatorNode\n# Throwing an error, which is correct\nInterpreter::OperatorNode # NameError: private constant Interpreter::OperatorNode referenced\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T00:30:33.220", "Id": "476878", "Score": "0", "body": "Thanks a lot for the feedback! I appreciate it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T02:44:09.253", "Id": "476886", "Score": "2", "body": "@reggaeguitar after looking again my answer, I realised the last part wasn't correct at all, so I removed everything related with [private classes within `self` blocks](https://codereview.stackexchange.com/posts/242932/revisions) as it's not really defining the classes as privates. Cheers" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T08:00:40.940", "Id": "242932", "ParentId": "242807", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T16:24:20.703", "Id": "242807", "Score": "3", "Tags": [ "programming-challenge", "ruby" ], "Title": "Ruby simple interactive interpreter" }
242807
<p>A slick way to write the zip function in Scheme/Racket:</p> <pre><code>(define (zip . lsts) (apply map list lsts)) (zip '(a b c) '(1 2 3)) '((a 1) (b 2) (c 3)) </code></pre> <p>Is using cons instead of list in zip to get a list of dotted-pairs correct?</p> <pre><code>(define (zip-dot . lsts) (apply map cons lsts)) (zip-dot '(1 2 3) '(a b c)) '((1 . a) (2 . b) (3 . c)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-20T00:09:44.497", "Id": "479422", "Score": "0", "body": "Not really. See `(zip '(a b c) '(1 2 3) '(\"BABY\" \"YOU\" \"ME\"))` for the reason. The dot notation is generally reserved for functions of arbitrary arity. `cons` can only be called with 2 arguments. While it works if applied to two lists, it fails in other cases, which is not what you expect when you see the function argument dot notation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:47:30.967", "Id": "482162", "Score": "0", "body": "Are you mixing dotted pairs with dot notation for arbitrary arity of functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T05:46:46.933", "Id": "501659", "Score": "0", "body": "No, zip-dot works if you pass it two arguments, but if you pass in the wrong number of arguments, `cons` will throw an error, and if in a non-trivial codebase, you'll weep, and bash your head against the desk trying to figure out which F^$*%$@ `cons` is misbehaving. whereas if you get an error back from `zip-dot` you'll have a narrower search window. Thus the reason the arbitary arity notation should only be used where you can actually accept a arbitrary number of arguments." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T19:15:51.213", "Id": "242815", "Score": "1", "Tags": [ "scheme", "racket" ], "Title": "Is this zip function ok?" }
242815
<p>I'm working on a text adventure game for a while now, learning more about user input etc. I have a feeling there is something fundamentally wrong about my code, it seems too repetitive.</p> <p>The use of structs should make things less bulky but can't figure out how to use it properly.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; // FUNCTIONS int readLine(); int execute(); void startUp(); void readLocation(); void executeOpen(); void executeOpenDoor(); void executeOpenFridge(); void executeReadSign(); void executeGo(); // LOCATIONS struct location { const char *description; const char *name; } locs[] = { {""}, {"hallway", "hall"}, {"kitchen", "kitchen"}, {"living room", "living room"}, {"toilet", "toilet room"}, {"upstairs", "first floor"}, }; void loc_kitchen(); void loc_living(); void loc_hall(); void loc_toilet(); void loc_upstairs(); // INIT int answer, location; int bullets, key, gun = 0; char* current_loc = "hall"; static char input[100]; // MAIN GAME int main() { startUp(); // INTRO while (readLine() &amp;&amp; execute()); // GAME LOOP return 0; } // FUNCTIONS // COMMAND &amp; READLINE int readLine () { printf("&gt; "); return fgets(input, sizeof(input), stdin) != NULL; } int execute() { char *verb = strtok(input, " \n"); char *noun = strtok(NULL, " \n"); if (verb != NULL) { if (strcasecmp(verb, "open") == 0) { executeOpenDoor(noun); } else if (strcasecmp(verb, "read") == 0) { executeReadSign(noun); } else printf("I don't know the word %s, try again.\n\n", verb); } return 1; } void executeOpenDoor(const char *noun) { if (noun == NULL) { printf("What do you want to open?\n\n"); } else if (strcasecmp(noun, "door") == 0) { printf("You enter the mansion, seems like nobody's been here in years..\n"); printf("You now have access to the kitchen, toilet, living room &amp; upstairs.\n\n"); readLocation(); } else { printf("I don't understand what you want to open.\n\n"); } } void readLocation() { while (1) { readLine(); char *verb = strtok(input, " \n"); char *noun = strtok(NULL, " \n"); if (strcasecmp(verb, "go") == 0) { executeGo(noun); } else { printf("I don't understand where you want to go.\n\n"); } } } void executeOpenFridge(const char *noun) { if (noun == NULL) { printf("What do you want to open?\n\n"); } else if (strcasecmp(noun, "fridge") == 0) { printf("Oh wish you didnt opened that. Whatever's in it, it's definitely out-of-date.\n\n"); } else { printf("I don't know what you want to open.\n\n"); } } void executeReadSign(const char *noun) { if (noun == NULL) { printf("What do you want to read?\n\n"); } else if (strcasecmp(noun, "sign") == 0) { printf("\"Begone, leave the dead in peace!\"\n\n"); } else { printf("I don't know what you want to read.\n\n"); } } void executeGo(const char *noun) { if (strcasecmp(noun, current_loc) == 0) { printf("You are already standing in the %s.\n\n", current_loc); } else if (noun == NULL) { printf("Where do you want to go?\n\n"); } else if (strcasecmp(noun, "kitchen") == 0) { loc_kitchen(); } else if (strcasecmp(noun, "toilet") == 0) { loc_toilet(); } else if (strcasecmp(noun, "hall") == 0) { loc_hall(); } else if (strcasecmp(noun, "living") == 0) { loc_living(); } else if (strcasecmp(noun, "upstairs") == 0) { loc_upstairs(); } else { printf("I don't know where you want to go.\n\n"); } } void loc_hall() { current_loc = "hall"; // ADD LOCATION printf("You have access to the kitchen, toilet, living room &amp; upstairs.\n\n"); while (1) { readLine(); char *verb = strtok(input, " \n"); char *noun = strtok(NULL, " \n"); if (strcasecmp(verb, "go") == 0) { executeGo(noun); } else { printf("I don't know the word %s.\n\n", verb); } } } void loc_kitchen() { current_loc = "kitchen"; // ADD LOCATION printf("There are several cupboards and drawers ajar, there's also a weird\n"); printf("smell coming from the fridge.\n\n"); while (1) { readLine(); char *verb = strtok(input, " \n"); char *noun = strtok(NULL, " \n"); if (strcasecmp(verb, "search") == 0) { if (gun == 1) { gun++; printf("You filled your shotgun with bullets.\n"); printf("When you put the bullets in the gun, you hear a door being slammed shut upstairs.\n\n"); } else if (gun == 2 || bullets == 1){ printf("You already found ammo in the drawers.\n\n"); } else { printf("In one of the drawers you found some salt bullets. These might come in handy!\n\n"); bullets++; } } else if (strcasecmp(verb, "open") == 0) { executeOpenFridge(noun); } else if (strcasecmp(verb, "go") == 0) { executeGo(noun); } else { printf("I don't know the word %s.\n\n", verb); } } } void loc_living() { current_loc = "living"; // ADD LOCATION printf("The furniture is covered with white cloth, but the colour has become\n"); printf("yellow out of age. The carpet has blood and dirt stains on it.\n"); if (!gun) { printf("Above the fireplace you see a double-barreled shotgun.\n"); } printf("\n"); while (1) { readLine(); char* verb = strtok(input, " \n"); char* noun = strtok(NULL, " \n"); if (strcasecmp(verb, "take") == 0) { if (bullets) { gun = 2; printf("You got yourself a gun, you filled it up with the salt bullets you found in the kitchen.\n"); printf("When you put the bullets in the gun, you hear a door being slammed shut upstairs.\n\n"); } else if (gun &gt; 0) { printf("You already have the gun.\n\n"); } else { gun++; printf("You took the gun, empty.. We need some find some bullets.\n\n"); } } else if (strcasecmp(verb, "go") == 0) { executeGo(noun); } else { printf("I don't know the word %s.\n\n", verb); } } } void loc_toilet() { current_loc = "toilet"; printf("You sure have a small bladder, couldn't you go before we started playing?\n\n"); readLocation(); } void loc_upstairs() { current_loc = "upstairs"; if (gun != 2) { printf("Maybe we need to find something to defend ourself first.\n\n"); } else { printf("There are 2 doors, which one do you want to take? Left or right?\n\n"); } } void startUp() { printf("You stand in front of the mansion, there is a sign on the door.\n\n"); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T21:20:48.043", "Id": "476576", "Score": "0", "body": "`locs[]` is not used. Why is it in the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T22:23:47.460", "Id": "476580", "Score": "0", "body": "I meant to used it in the function ExecuteGo, i wanted to use a ‘for’ loop To go through all the values of the locs struct instead of using every if else statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T12:44:38.643", "Id": "476626", "Score": "0", "body": "In terms of a \"cleanup\", recommend to leave out _meant to use_ code." } ]
[ { "body": "<h2>Static functions</h2>\n\n<p>Given that this is a one-file program, all of your functions (except <code>main</code>) and global variables should be marked <code>static</code> as they will not be used in other translation units.</p>\n\n<h2>stdbool</h2>\n\n<p>Functions like <code>readLine</code> should return <code>bool</code> (from <code>stdbool.h</code>), and not <code>int</code>.</p>\n\n<p>This will also allow</p>\n\n<pre><code>while (1)\n</code></pre>\n\n<p>to change to</p>\n\n<pre><code>while (true)\n</code></pre>\n\n<h2>Global state</h2>\n\n<p>Most of your global variables after <code>// INIT</code> should be moved. <code>input</code> should just be a local variable. The others could be moved into a game state structure that gets passed around, to enable re-entrance.</p>\n\n<h2>Simple output</h2>\n\n<p>I prefer <code>puts</code> to <code>printf</code> when you are only outputting a string literal with no formatting. Note that <code>puts</code> includes a newline, so</p>\n\n<pre><code>printf(\"What do you want to open?\\n\\n\");\n</code></pre>\n\n<p>would turn into</p>\n\n<pre><code>puts(\"What do you want to open?\\n\");\n</code></pre>\n\n<p>but <code>printf(\"&gt; \");</code> would stay as-is.</p>\n\n<p>The reasons I prefer this change:</p>\n\n<ul>\n<li>it produces more terse code;</li>\n<li>if we were to assume a non-optimizing compiler, <code>printf</code> would be slower; and</li>\n<li><code>puts</code> is constrained to a much simpler set of behaviour.</li>\n</ul>\n\n<h2>executeGo</h2>\n\n<p>Rather than representing this as a long list of <code>if</code> statements, you could factor it out into an array of string/function-pointer pairs. Iterate through them until you find a matching string and call the appropriate function. If this list gets longer as you add to the game, consider using a dictionary library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T10:36:35.693", "Id": "476613", "Score": "0", "body": "Maybe for a beginner you should explain why you prefer puts over printf." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T11:53:00.307", "Id": "476624", "Score": "0", "body": "Didn't expect so much advice, much appreciated @Reinderien! I do have some questions. I declared static functions at the top, should the function itself also need static in front of it? With stdbool should my return 0 also be return false or do you keep it to return 0? (int main). If 'input' is a local variable, do i use a pointer to get it to be used in the other functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T12:39:35.630", "Id": "476625", "Score": "0", "body": "Note: To get the same functionality `printf(\"> \");` is not replaceable with `puts()`. Could use `fputs(\"> \", stdout);` \"prefer puts to printf\" does not discuss the `'\\n'` added by `puts()` so sounds like you are advocating a simple switch of functions without taking the `'\\n'` into account." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:36:59.550", "Id": "476631", "Score": "0", "body": "Good points; edited re. simple output" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:40:40.873", "Id": "476632", "Score": "1", "body": "_I declared static functions at the top, should the function itself also need static in front of it?_ - For clarity I always recommend that function signatures in the declaration and definition be exactly the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:41:10.877", "Id": "476633", "Score": "1", "body": "_With stdbool should my `return 0` also be `return false`_ - yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:42:48.800", "Id": "476634", "Score": "0", "body": "_If 'input' is a local variable, do i use a pointer to get it to be used in the other functions?_ - That depends on what you mean by use by other functions. If you have a legitimate need for that string in another function, then yes, pass it by `const char*`. If you just need \"another buffer\" in another function, declare a separate buffer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T21:38:58.323", "Id": "476669", "Score": "0", "body": "I remade my structs so in my executeGo it will do a for loop for all of the location structs i have. Then it will post the message from it (send value of the struct) but I was unable to add a list of functions to an array or linking my strings 'hall' or 'kitchen' to a function 'loc_hall' for example.." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T01:44:46.150", "Id": "242829", "ParentId": "242817", "Score": "5" } }, { "body": "<p>There are a few ways that <code>struct</code> types, and restructuring in general, could clean up your code.</p>\n\n<h1>Stack Overflow</h1>\n\n<p>First, I'll point out that your code is infinitely mutually recursive. If a player <em>goes</em> from the kitchen to the hall and back again, over and over, the stack will overflow.</p>\n\n<p>As such, you should first concentrate on eliminating this recursion. Understand why you felt the need to encode it, and move that reason into some kind of data structure that is independent of the stack.</p>\n\n<h1>The three most important things in real estate:</h1>\n\n<p>Your various <code>loc_</code> functions seem to have a similar structure. First they set a location string, then they mostly print a static message (with one exception), then they maybe print some extra text depending on the player's inventory or past actions.</p>\n\n<p>Some of the locations then enter a nested command loop, but that should be addressed above.</p>\n\n<p>So if you had a data structure that encoded those data items, you could process all the <code>loc_</code> code with a single function. Something like:</p>\n\n<pre><code>typedef struct LOCATION {\n const char * name;\n const char * enter_msg;\n struct CONDITIONAL_MESSAGE {\n int item_id;\n const char * per_item_msg;\n } * conditional_messages;\n} LOCATION;\n</code></pre>\n\n<p>If your maze grows to require it, you might include a function pointer for really complex rooms. Also, you might want to have a \"first time\" entry message and a \"every other time\" entry message, so the game doesn't get too verbose.</p>\n\n<h1>Sic transit gloria mundi!</h1>\n\n<p>English verbs are divided between <em><a href=\"https://en.wikipedia.org/wiki/Transitive_verb\" rel=\"nofollow noreferrer\">transitive</a></em> and <em><a href=\"https://en.wikipedia.org/wiki/Intransitive_verb\" rel=\"nofollow noreferrer\">intransitive</a></em> forms. Transitive verbs take an <em><a href=\"https://en.wikipedia.org/wiki/Object_(grammar)\" rel=\"nofollow noreferrer\">object</a></em> while intransitive verbs do not.</p>\n\n<p>An example of an intransitive verb would be \"quit\" -- the command you should always implement first. A transitive verb would be something like \"go kitchen\" or \"read note\".</p>\n\n<p>Most of your verbs are transitive, which is fine. But the transitive verbs have a very similar structure when you process them:</p>\n\n<pre><code>1. Was there an object specified? If not, snark.\n2. Is the object valid for this verb? If so, do something.\n3. If not, snark.\n</code></pre>\n\n<p>So that leads to the suggestion that you move as much of this structure as possible into your parsing engine, and clean up the rest of your code. </p>\n\n<pre><code>struct VERB {\n unsigned flags;\n const char * word;\n const char * no_object_msg;\n const char * bogus_object_msg;\n // maybe a helper function?\n};\n</code></pre>\n\n<h1>Lots and lots of lists and lists</h1>\n\n<p>When thinking about transitive verbs, there are three obvious sources for objects. First, there is the map itself. The various \"go XXX\" commands will change based on where a player is standing. So it makes sense for there to be a list of rooms that is currently reachable.</p>\n\n<p>The \"take\" verb, and the \"open\" verb, both suggest that there should be a list of items in the room. Some of those items are take-able, like the gun or the ammo. If taken, these items will leave the room and move into the player's inventory. Other items are permanently in the room, like a door or the fridge. You can still open them, but cannot have them in inventory. (A bit flag would be sensible for this. CAN_TAKE, CAN_OPEN, etc.)</p>\n\n<p>Finally, there are the items in the player's inventory. These items will \"always\" be available, regardless of what room the player is in. You have used global variables for this, which IMO is a mistake. Better to create an array or a list.</p>\n\n<p>Once you have all these lists figured out, you can search them for verb-objects. If the player enters, \"take gun\", it makes sense to check her inventory for the gun and print \"you already have that\", then check the room inventory for a gun that is take-able.</p>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:35:50.550", "Id": "476758", "Score": "0", "body": "Advice is great, i've been working on it, especially the Stack overflow part but i have to admit my knowledge isn't advanced yet to implement everything. Is it possible to check what I have done for now? [github link](https://github.com/iamzumie/ghost-mansion/blob/master/main.c)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T02:54:12.233", "Id": "476786", "Score": "0", "body": "As a starting point, try this: create a `struct` for your verbs with only two elements, the word (string) and a function pointer to the handler function. The code in your `execute` function where you use if/else to determine which verb has been input can be replaced by a loop, where you compare the word and invoke the function pointer when a match is found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T08:23:54.157", "Id": "476996", "Score": "0", "body": "It took my a while before i understood what you mean with a handler function and how it works. I managed to implement it twice, but i will cleanup some more because half of the function in the locations are just returns. [link](https://github.com/iamzumie/ghost-mansion/blob/master/main.c)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T22:51:20.957", "Id": "477058", "Score": "0", "body": "I can see you're making progress. I'd still suggest putting more data into the `verb` structure, but you clearly can see how to do that. You might want to get in the habit of using a pointer, instead of an index -- it's easier to pass that around to other functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T19:14:34.350", "Id": "477239", "Score": "0", "body": "I added a quit statement, more structs but i've got stuck. I can't seem to connect everything properly (locations, items,..) which makes my code unorganized & messy. The IF statements are way too long right now. [link](https://github.com/iamzumie/ghost-mansion/blob/master/main.c)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:03:58.190", "Id": "242846", "ParentId": "242817", "Score": "4" } } ]
{ "AcceptedAnswerId": "242829", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T19:55:56.190", "Id": "242817", "Score": "9", "Tags": [ "c", "game", "adventure-game" ], "Title": "Text-adventure game cleanup" }
242817
<p>It has been a long time I used c++.<br> So I brushing over concepts for interview preparation.<br> Can you please help me with code review?<br> If you have any observations/bugs/alternatives please point out.<br> For better formatting, I have shared code <a href="https://github.com/mshingote/KnowledgeCenter/blob/master/Test.cpp" rel="nofollow noreferrer">here</a> feel free to open issues. :)<br> Thanks a ton in advance.</p> <pre><code>#include &lt;cstring&gt; #include &lt;memory&gt; #include &lt;utility&gt; class Test { public: //Default constructor Test() = default; //Copy constructor Test(const Test&amp; other) : m_size(other.m_size), m_buffer(new char[m_size]()) { strncpy(m_buffer.get(), other.m_buffer.get(), m_size); } //Parametarized constructor Test(std::size_t len, const char* data) : m_size(len), m_buffer(new char[len]()) { strncpy(m_buffer.get(), data, m_size); } //Move constructor Test(Test&amp;&amp; other) noexcept { Test temp(other); swap(*this, temp); } //Assignment operator Test&amp; operator=(Test other) { if(this != &amp;other) { swap(*this, other); } return *this; } //Move assignment operator Test&amp; operator=(Test&amp;&amp; other) noexcept { if(this != &amp;other) { Test temp(other); swap(*this, temp); } return *this; } //Destructor ~Test() { m_size = 0; m_buffer = nullptr; } private: std::size_t m_size = 0; std::unique_ptr&lt;char[]&gt; m_buffer = nullptr; static void swap(Test&amp; first, Test&amp; second) noexcept{ using std::swap; swap(first.m_size, second.m_size); swap(first.m_buffer, second.m_buffer); } }; </code></pre>
[]
[ { "body": "<p>Your move-ctor and move-assignment are badly implemented. You copy input data and then you swap it with source. You may as well delete move-ctor and move-assignment as they are worthless now.</p>\n\n<p>Your copy assignment operator has an unnecessary check that cannot be true and it won't perform well for self-copying. As it will copy its data into another instance and then swap data with it. To fix this make input of type <code>const Test&amp;</code>. And make a data copy routine.</p>\n\n<p>Destructor is unnecessary as <code>std::unique_ptr</code> automatically manages it.</p>\n\n<p>You realize <code>strncpy</code> copies data till it reaches 0, right?</p>\n\n<pre><code> std::unique_ptr&lt;char[]&gt; m_buffer = nullptr;\n</code></pre>\n\n<p>This is unnecessary. No need for <code>= nullptr</code>. <code>std::unique_ptr</code> does it on its own.</p>\n\n<p>Edit:\nAlso I believe declaring a private static <code>swap</code> is a problem. What will happen if user were to try to call <code>swap(tst1,tst2)</code> when <code>using namespace std</code> or <code>using std::swap</code>?</p>\n\n<p>You could make it public, but IMHO it's better to implement move-ctor and move-assignment directly - without making a swap in between. Let swap rely on move and not the opposite. Note that <code>std::swap</code> utilizes move for its purposes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T09:46:16.417", "Id": "476607", "Score": "0", "body": "I agree with for copy assignment related part as I am accepting arg by value.\nBut for move ctor and move assignment, it is recommended to use copy-swap idiom\nref. https://stackoverflow.com/a/3279550/10035556" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T09:51:29.487", "Id": "476608", "Score": "0", "body": "Let me know your thought on copy-swap idiom or a better alternative for the same :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T11:15:53.157", "Id": "476617", "Score": "0", "body": "@Mayur for move-ctor and move-assignment operations, you didn't implement them correctly. They are meant to steal input's data. Your implementation doesn't. It copies the data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T11:24:05.713", "Id": "476618", "Score": "0", "body": "@Mayur the copy-swap idiom is pretty bad honestly. Frequently, I want to reserve memory allocation and reuse it while keeping reserved size. Swapping ruins it. Just make a reserve/resize functions that ensures that enough data is allocated for copying and increases the capacity appropriately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T18:57:06.917", "Id": "476657", "Score": "0", "body": "@Mayur Even the article you link does not use copy and swap for move. The point is to be cheaper than copying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T18:58:37.033", "Id": "476658", "Score": "0", "body": "@ALX23z You are in the minority that think Copy and Swap is bad. There is nothing to stop you reserving extra memory with a copy anyway so even your reasoning is flawed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T19:57:49.063", "Id": "476662", "Score": "0", "body": "@MartinYork when on copy assigment one first copy-constructs an extra instance then swaps with `this` - then you first allocate, then copy it. If you already had enough memory then swapping introduces extra allocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T22:55:39.250", "Id": "476672", "Score": "1", "body": "@ALX23z Sure. But in the general case you can't get away from that if you want to implement the strong exception guarantee. In situations like the above were you can get away without the extra allocation it is simple to implement the conditional copy and swap. Also that is why we have the move constructor. So you don't need to allocate memory. These are not new concepts and we (as a community) have done excessive testing on all these things. In the end micro optimizations like you suggest are not worth the extra maintenance cost. That's why its an `idiom`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T10:34:42.113", "Id": "476708", "Score": "0", "body": "@MartitYork you miss the whole point about reserved size for arrays. Once size is reserved it shouldn't be altered by copying data. Moreover, if you reallocate then all pointers are invalidated which is definitely not what user wants to find out during debugging. And every user will be pissed to find out that you miss those \"micro\" optimization in base classes. The swap idiom came up in pre-C++11 era where move didn't exist. It is already outdated and people stick to it for no known reason. Now you just need to implement move-ctor and assignment then just use `std::swap` if that what you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T00:28:42.843", "Id": "476783", "Score": "0", "body": "@ALX23z I did not miss the reserve point read my comment again." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T06:30:15.673", "Id": "242832", "ParentId": "242824", "Score": "1" } }, { "body": "<h2>Observations</h2>\n<p>Your rule of 5 implementation is basically wrong. You are implement copy operations for both copy and move (which means you may as well not have the move operations).</p>\n<p>Your destructor is not doing any real work and thus adding unneeded code.</p>\n<p>Your swap function does not work as expected as it can not be used with Koenig lookup (ADL) and thus in most standard library would be replaced with <code>std::swap</code> resulting in a sub optimal swap.</p>\n<h2>Details</h2>\n<p>Here I don't see the need for creating a temporary.</p>\n<pre><code> //Move constructor\n Test(Test&amp;&amp; other) noexcept {\n Test temp(other);\n swap(*this, temp);\n }\n</code></pre>\n<p>By creating the temporary your move is basically just as expensive as your copy. The whole point of the move is that it is cheap.</p>\n<p>I would simply swap the current with <code>other</code>.</p>\n<pre><code> //Move constructor\n Test(Test&amp;&amp; other) noexcept {\n swap(other);\n }\n</code></pre>\n<p>After the move construction the content of <code>other</code> has no guaranteed state (only that it is valid). Since you define <code>m_size</code> and <code>m_buffer</code> to auto initialize the current <code>this</code> is in a valid state and can simply be swapped with <code>other</code>.</p>\n<pre><code> // Note I usually define a `noexcept` swap method.\n\n void swap(Test&amp; other) noexcept {\n using std::swap;\n swap(m_size, other. m_size);\n swap(m_buffer, other. m_buffer);\n }\n</code></pre>\n<p>I also define <code>swap()</code> with two parameters as a free standing function that simply calls the swap method. This is because the compiler can using Koenig lookup (ADL) to find the correct swap function.</p>\n<pre><code> void swap(Test&amp; lhs, Test&amp; rhs) {\n lhs.swap(rhs);\n }\n</code></pre>\n<hr />\n<p>The Copy assignment is sub optimal.</p>\n<pre><code> //Assignment operator\n Test&amp; operator=(Test other) {\n if(this != &amp;other) {\n swap(*this, other);\n }\n return *this;\n }\n</code></pre>\n<p>Since the parameter <code>other</code> is created via a copy construction it is guaranteed not to be the same as <code>this</code>. Thus the test <code>if(this != &amp;other)</code> is just a pessimization as it is not needed.</p>\n<hr />\n<p>Again you perform a copy during the move assignment.</p>\n<pre><code> //Move assignment operator\n Test&amp; operator=(Test&amp;&amp; other) noexcept {\n if(this != &amp;other) {\n Test temp(other);\n swap(*this, temp);\n }\n return *this;\n }\n</code></pre>\n<p>This defeats the purpose of the move (as it is supposed to be cheaper than a copy). You can simply swap <code>this</code> and <code>other</code> as they should both be valid.</p>\n<pre><code> Test&amp; operator=(Test&amp;&amp; other) noexcept {\n swap(other);\n return *this;\n }\n</code></pre>\n<p>No need to check for self assignment as this is a pessimization of the normal more common situation. Even of they are the same object the swap will work correctly.</p>\n<hr />\n<p>The destructor is useless:</p>\n<pre><code> //Destructor\n ~Test() {\n m_size = 0;\n m_buffer = nullptr;\n }\n</code></pre>\n<p>The member: <code>m_buffer</code> will correctly clean up the memory.</p>\n<hr />\n<p>Making this a static member is not doing you any favors as it prevents Koenig lookup (ADL).</p>\n<pre><code> static void swap(Test&amp; first, Test&amp; second) noexcept{\n using std::swap;\n swap(first.m_size, second.m_size);\n swap(first.m_buffer, second.m_buffer);\n }\n</code></pre>\n<p>Make this a free standing function:</p>\n<pre><code>namespace PL\n{\n\nclass TestStatic\n{\n public:\n static void swap(TestStatic&amp; lhs, TestStatic&amp; rhs) noexcept\n {}\n};\n\n\nclass TestFreeStand\n{\n public:\n};\nvoid swap(TestFreeStand&amp; lhs, TestFreeStand&amp; rhs) noexcept\n{}\n\n}\n\n\nint main()\n{\n PL::TestStatic staticA;\n PL::TestStatic staticB;\n\n swap(staticA, staticB);\n\n\n PL::TestFreeStand freeStandA;\n PL::TestFreeStand freeStandB;\n\n swap(freeStandA, freeStandB);\n}\n</code></pre>\n<p>Notice the only compilation error here is: <code>swap(staticA, staticB);</code></p>\n<p>This means that if you add <code>using std::swap;</code> this code will now compile but it will not use your <code>static void swap()</code> method it will use <code>std::swap</code> which makes a copy of the object. The point of writing your own version of swap is that you are providing an optimization over the standard swap.</p>\n<h2>Better Implementation</h2>\n<pre><code>#include &lt;cstring&gt;\n#include &lt;memory&gt;\n#include &lt;utility&gt;\n\nnamespace Testing\n{\n\n class Test\n {\n public:\n // Default constructor\n Test() = default;\n \n // Parametrized constructor\n Test(std::size_t len, const char* data)\n : m_size(len)\n , m_buffer(new char[len]())\n {\n // Should validate the input here.\n // It is the only time you get outside input.\n // Potentially you could throw here I choose\n // not too (because I can see it as a valid input)\n // Your use case may be different.\n if (data) {\n strncpy(m_buffer.get(), data, m_size);\n }\n }\n \n // Copy constructor\n Test(const Test&amp; other)\n : m_size(other.m_size)\n , m_buffer(new char[m_size]())\n {\n strncpy(m_buffer.get(), other.m_buffer.get(), m_size);\n } \n \n // Copy Assignment operator\n Test&amp; operator=(Test other)\n {\n swap(other);\n return *this;\n }\n \n // Move constructor\n Test(Test&amp;&amp; other) noexcept\n {\n swap(other);\n }\n \n // Move assignment operator\n Test&amp; operator=(Test&amp;&amp; other) noexcept\n {\n swap(other);\n return *this;\n }\n \n void swap(Test&amp; rhs) noexcept\n {\n using std::swap;\n swap(m_size, rhs.m_size);\n swap(m_buffer, rhs.m_buffer);\n }\n private:\n std::size_t m_size = 0; \n std::unique_ptr&lt;char[]&gt; m_buffer = nullptr;\n };\n \n void swap(Test&amp; lhs, Test&amp; rhs) noexcept\n {\n lhs.swap(rhs);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T18:42:24.680", "Id": "242867", "ParentId": "242824", "Score": "5" } } ]
{ "AcceptedAnswerId": "242867", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T23:08:28.943", "Id": "242824", "Score": "6", "Tags": [ "c++", "pointers" ], "Title": "Simple C++ Test class with rule of 5" }
242824
<p>At first I wasn't really proud of this one, but then I decided that I need to know what's so bad about it? Why does it feel unsatisfying? How can I do it better?</p> <p>So yeah here's a unity project that does the following:</p> <p>Spawns a maximum of 3 wall bouncing corona balls where the player clicks, which when they collide with each other they heal some health, and if with a wall (screen edges) they loose health. I also tried to do so their alpha value changes in proportion with its health (the closer it is to the death, the more transparent it is). There is a text showing how many time the corona balls bounced of the walls. One last thing, it plays a cough sound on collision.</p> <p>Here are the scripts I have and which gameObject are they attached to:</p> <p>Basic script I found online, I remember reading and understanding it before writing on my own, can't recall if I modified it though. Its attached to the camera obviously:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; // script to instantiate edge colliders at start public class edges : MonoBehaviour { public PhysicsMaterial2D bouncy; void Awake() { AddCollider(); } void AddCollider() { if (Camera.main == null) { Debug.LogError("Camera.main not found, failed to create edge colliders"); return; } var cam = Camera.main; if (!cam.orthographic) { Debug.LogError("Camera.main is not Orthographic, failed to create edge colliders"); return; } var bottomLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane)); var topLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.nearClipPlane)); var topRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane)); var bottomRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.nearClipPlane)); // add or use existing EdgeCollider2D var edge = GetComponent&lt;EdgeCollider2D&gt;() == null ? gameObject.AddComponent&lt;EdgeCollider2D&gt;() : GetComponent&lt;EdgeCollider2D&gt;(); var edgePoints = new[] { bottomLeft, topLeft, topRight, bottomRight, bottomLeft }; edge.points = edgePoints; edge.sharedMaterial = bouncy; } } </code></pre> <p>Script attached to HUD (canvas), it just has a AddBounce method to display bounce count, would be surprised if I screwed even this:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // Script for HUD management, and stuf... public class HUD : MonoBehaviour { // declaring them fields [SerializeField] Text bounceText; int bounces; // Start is called before the first frame update void Start() { // assign number of bounces to text bounceText.text = bounces.ToString(); } // Method to add bounces public void AddBounce() { bounces += 1; bounceText.text = bounces.ToString(); } } </code></pre> <p>This is the spawner attached to the camera that detects players clicks so it can spawn coronas as long as there aren't 3 or more already:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class coronaSpawner : MonoBehaviour { // declaring fields [SerializeField] GameObject prefabCorona; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetButtonDown("Fire1")) { if (GameObject.FindGameObjectsWithTag("corona").Length &lt; 3) { // gets mouse location and convert it to world position Vector3 mouseLocation = Input.mousePosition; Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mouseLocation); worldPosition.z = 2f; // spawns a corona in mouse location Instantiate(prefabCorona, worldPosition, Quaternion.identity); } } } } </code></pre> <p>And finally, here's what I hate (I think?), a blunder of horribly declared fields that feel that are too much already, here's the script attached to the coronaPrefab which traces its health, alphaValue, X and Y values for impulse force and everything else you'll have to figure out reading it:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class bouncer : MonoBehaviour { //declaring variables [SerializeField] int health = 100; [SerializeField] int minX = 6; [SerializeField] int maxX = 9; [SerializeField] int minY = 4; [SerializeField] int maxY = 20; [SerializeField] int fragility = 10; float fullHealth; float alphaValue; HUD hud; AudioSource audioSource; // Start is called before the first frame update void Start() { // assigning fields audioSource = GetComponent&lt;AudioSource&gt;(); fullHealth = health; // calculates right alpha value for the sprite to dissapear at death alphaValue = (float)1 / (health / fragility); // taking RigidBody2D and adding random impulse force Rigidbody2D rb2d = GetComponent&lt;Rigidbody2D&gt;(); rb2d.AddForce(new Vector2(Random.Range(minX,maxX), Random.Range(minY,maxY)), ForceMode2D.Impulse); // taking HUD component hud = GameObject.FindGameObjectWithTag("HUD").GetComponent&lt;HUD&gt;(); } // called when the Object's colider enters a collision with another collider void OnCollisionEnter2D(Collision2D col) { // calls the Change method audioSource.Play(); Change(col); } // gets alpha value, changes it and assigns it back. Also reduces or adds health private void Change(Collision2D col) { // gets color componenent Color color = GetComponent&lt;SpriteRenderer&gt;().color; // adds or reduce values depending on choice if (col.gameObject.tag == "MainCamera") { hud.AddBounce(); health -= fragility; if (health &lt;= 0) { Destroy(gameObject); } } else if (col.gameObject.tag == "corona") { health += fragility * 2; Range(health, 0, fullHealth * 1.5); } // assigns color component back with modified alpha value color.a = health / fullHealth; GetComponent&lt;SpriteRenderer&gt;().color = color; } // makes sure value is within a reasonable range public static double Range(int value, double minimum, double maximum) { if (value &lt; minimum) { return minimum; } if (value &gt; maximum) { return maximum; } return value; } } </code></pre> <p>So yeah, this is one of my training Unity Projects, I'll be forever grateful to you if you give it a look and tell me what I could've done better, and thank you in advance!</p> <p>Also I would like a smoll tip, when I get feedback on a script(s?), should I go back and change what I can? Should I try to test all the new features and tricks I learned in a different project? Or should I just read, understand and memorize? Again, thank you all so much that for your help and for taking the time and effort to share your experiences so us beginners can learn! ^^</p>
[]
[ { "body": "<p>Pity no one has tried to help out a beginner. While I know little of Unity, I can offer some C# comments.</p>\n\n<p>Let me start with that overall your code looks nice. It has good indentation and variable names are meaningful, i.e. not cryptic or abbreviated. Use of braces is very good.</p>\n\n<p>Actually, I don't see any properties in your class, but that might be a Unity requirement that objects are to be fields rather than properties.</p>\n\n<p>I personally want to see access modifiers (public, private, or internal) where possible. Yes, there are defaults, but especially when dealing with beginners I want to see them explicitly specify the access modifier.</p>\n\n<p>For naming conventions, classes, methods, and properties using Pascal casing. See:</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/?redirectedfrom=MSDN\" rel=\"nofollow noreferrer\">.NET Design Guidelines</a></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Naming Guidelines</a></p>\n\n<p><a href=\"https://www.dofactory.com/reference/csharp-coding-standards\" rel=\"nofollow noreferrer\">C# Coding Standards</a></p>\n\n<p>You have a lot of comments. Some are good, some not so good. There is no need for a comment that tells us what you are doing, because what the code is doing should be self evident. Comments are better if they tell us why you are doing something a certain way.</p>\n\n<p>Finally the <code>Range</code> method could have a better name. On the surface, if I see <code>Range</code>, I am thinking it should be a property. For a method, I suggest a naming pattern of [Action Verb] + [Noun]. Something like <code>GetRange</code> follows that pattern. But in your case, I think <code>ClampRange</code> would be the more meaningful name, in that the name clearly denotes to the reader the intent of the method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T12:52:10.327", "Id": "242946", "ParentId": "242825", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T23:20:55.533", "Id": "242825", "Score": "2", "Tags": [ "c#", "beginner", "unity3d" ], "Title": "Basic Beginner Unity Project with a bouncing corona" }
242825
<p>I have written Python code to rearrange some files in a directory, create new directories and delete old ones to form the dataset in the structure that I want it. Previously, I was doing this with repetative code because it got the job done but I want to clean it up and see no reason to repeat code.</p> <pre><code>test_names_path = 'food-101/meta/test.txt' train_names_path = 'food-101/meta/train.txt' train = 'food-101/images/train' test = 'food-101/images/test' def assemble_dataset(data_path, folder): for line in data_path: name_of_folder = line.split('/')[0] name_of_file = line.split Path('food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename(folder + name_of_folder + '_' + name_of_file + '.jpg') if data_path == 'food-101/meta/train.txt': with open('food-101/meta/train.txt') as train_file: for element in train_file: name_of_folder = element.split('/')[0] if os.path.exists('food-101/images/' + name_of_folder): shutil.rmtree('food-101/images/' + name_of_folder) # with open('food-101/meta/test.txt') as test_file: # for line in test_file: # name_of_folder = line.split('/')[0] # name_of_file = line.split('/')[1].rstrip() # Path('food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('food-101/images/test/' + name_of_folder + '_' + name_of_file + '.jpg') # # Moves all training images to the Food-101/images directory and renames them # with open('food-101/meta/train.txt') as train_file: # for line in train_file: # name_of_folder = line.split('/')[0] # name_of_file = line.split('/')[1].rstrip() # Path('food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('food-101/images/train/' + name_of_folder + '_' + name_of_file + '.jpg') # Removes empty directories inside Food-101/images # with open('food-101/meta/train.txt') as train_file: # for folder in train_file: # name_of_folder = folder.split('/')[0] # if os.path.exists('food-101/images/' + name_of_folder): # shutil.rmtree('food-101/images/' + name_of_folder) assemble_dataset(train_names_path, train) assemble_dataset(test_names_path, test) </code></pre> <p>The commented out code is the old code and is what I'm trying to shrink. In <code>def assemble_dataset()</code>, the first 2 blocks of code correspond to the first 2 <code>with open()</code> chunks. The following <code>if data_path...</code> statement corresponds to the last <code>with open()</code> chunk.</p> <p>Below is the original code:</p> <pre><code>git_repo_tags = ['AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X'] # Cloning the github repositories for repo in git_repo_tags: git.Git('.').clone('git://github.com/utility-repos/' + repo) #Removing the .git folder from each repo shutil.rmtree(repo + '/.git') # Creating the Food-101/images directory and subdirectory if it doesn't already exist if not os.path.exists('Food-101/images/train') and not os.path.exists('Food-101/images/test'): os.makedirs('Food-101/images/train') os.makedirs('Food-101/images/test') # Going through the repo X and moving everything a branch up for i in os.listdir('X'): shutil.move(os.path.join('X', i), 'Food-101') # Going through the other repos and moving everything to Food-101/images for directory in git_repo_tags: for subdirectory in os.listdir(directory): shutil.move(os.path.join(directory, subdirectory), 'Food-101/images') with open('Food-101/meta/test.txt') as test_file: for line in test_file: name_of_folder = line.split('/')[0] name_of_file = line.split('/')[1].rstrip() Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/images/test/' + name_of_folder + '_' + name_of_file + '.jpg') # Moves all training images to the Food-101/images directory and renames them with open('Food-101/meta/train.txt') as train_file: for line in train_file: name_of_folder = line.split('/')[0] name_of_file = line.split('/')[1].rstrip() Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/images/train/' + name_of_folder + '_' + name_of_file + '.jpg') # Removes empty directories inside Food-101/images with open('Food-101/meta/train.txt') as train_file: for folder in train_file: name_of_folder = folder.split('/')[0] if os.path.exists('Food-101/images/' + name_of_folder): shutil.rmtree('Food-101/images/' + name_of_folder) # Removes empty directories for dirs in git_repo_tags: shutil.rmtree(dirs) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T02:28:58.553", "Id": "476588", "Score": "1", "body": "Please post the code that you want review unmodified. We're not going to unpick which lines are comments and which lines are code before reviewing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T03:14:39.760", "Id": "476590", "Score": "0", "body": "@l0b0 Done... :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T07:21:49.867", "Id": "476599", "Score": "0", "body": "You would do well simply to read through [pathlib documentation](https://docs.python.org/3/library/pathlib.html). Also `for line in datapath` will iterate characters in string as you have not `open()`ed the file." } ]
[ { "body": "<p>As @David says, extensive replacement of your <code>os</code> and <code>shutil</code> calls with <code>pathlib</code> will get you 90% of the way to a better solution. The one exception is <code>shutil.rmtree</code> which does not have a <code>pathlib</code> equivalent.</p>\n\n<p>I'll go through most of the instances.</p>\n\n<h2>Immutable constants</h2>\n\n<pre><code>git_repo_tags = ['AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X']\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>GIT_REPO_TAGS = ('AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X')\n</code></pre>\n\n<p>since it's global and you don't intend on changing it.</p>\n\n<h2>Exists</h2>\n\n<pre><code>if not os.path.exists('Food-101/images/train') and not os.path.exists('Food-101/images/test'):\n os.makedirs('Food-101/images/train')\n os.makedirs('Food-101/images/test')\n ...\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>images = Path('Food-101/images')\ntrain = images / 'train'\ntest = images / 'test'\nif not (train.exists() or test.exists()):\n train.mkdir()\n test.mkdir()\n ...\n</code></pre>\n\n<h2>Move</h2>\n\n<pre><code>for i in os.listdir('X'):\n shutil.move(os.path.join('X', i), 'Food-101')\n</code></pre>\n\n<p>can be </p>\n\n<pre><code>food = Path('Food-101')\nrepo = Path('X')\nfor i in repo.iterdir():\n i.rename(food / i.name)\n</code></pre>\n\n<h2>Path appends</h2>\n\n<pre><code>Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg')\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>(Path('Food-101/images') / name_of_folder / name_of_file).with_suffix('.jpg')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:42:37.260", "Id": "242854", "ParentId": "242830", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T02:19:53.727", "Id": "242830", "Score": "2", "Tags": [ "python" ], "Title": "Python code to reiterate different files" }
242830
<p>I'm working on modernizing legacy ASP.NET WebForms site which heavily relies on doing AJAX request for client-side rendering. Without the use of <code>vue-cli</code> compiling <code>.vue</code> file with ease is not possible (or it is?).</p> <p>So what I'm trying to do is to replicate single-file components and folder structure as much as possible. Result in a folder structure like this (irrelevant files are omitted).</p> <pre><code>├── Scripts | ├── app.js | └── components | ├── CustomCard.js | └── CustomButton.js ├── Default.aspx └── ... </code></pre> <p>And in order to replicate the single-file components the content inside will look like this.</p> <p><strong>Default.aspx</strong></p> <pre><code>&lt;%@ Page Title=&quot;Vue&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Site.Master&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;Default.aspx.cs&quot; Inherits=&quot;Vue._Default&quot; %&gt; &lt;%@ Import Namespace=&quot;System.Web.UI&quot; %&gt; &lt;%@ Register TagPrefix=&quot;asp&quot; Namespace=&quot;System.Web.UI.WebControls&quot; Assembly=&quot;System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&quot; %&gt; &lt;%-- This will be in the head tag speficied in Site.Master --%&gt; &lt;asp:Content ID=&quot;HeadContent&quot; ContentPlaceHolderID=&quot;PageHeadContent&quot; runat=&quot;server&quot;&gt; &lt;script src=&quot;&lt;%: ResolveUrl(&quot;~/Scripts/vue.js&quot;) %&gt;&quot;&gt;&lt;/script&gt; &lt;/asp:Content&gt; &lt;%-- This will be in the body tag speficied in Site.Master --%&gt; &lt;asp:Content ID=&quot;BodyContent&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt; &lt;div id=&quot;app&quot;&gt; &lt;custom-card&gt;&lt;/custom-card&gt; &lt;/div&gt; &lt;script src=&quot;&lt;%: ResolveUrl(&quot;~/Scripts/app.js&quot;) %&gt;&quot;&gt;&lt;/script&gt; &lt;/asp:Content&gt; </code></pre> <p><strong>Scripts/app.js</strong></p> <pre class="lang-js prettyprint-override"><code>import CustomCard from './components/CustomCard.js' var app = new Vue({ el: '#app', components: { CustomCard }, }) </code></pre> <p><strong>Scripts/components/CustomCard.js</strong></p> <pre class="lang-js prettyprint-override"><code>import CustomButton from './CustomButton.js' export default { name: 'custom-card', components: { CustomButton }, data: function () { return { cardText: 'This is card body', } }, template: `&lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;p&gt;{{ cardText }}&lt;/p&gt; &lt;custom-button&gt;&lt;/custom-button&gt; &lt;/div&gt; &lt;/div&gt;` } </code></pre> <p><strong>Scripts/components/CustomButton.js</strong></p> <pre class="lang-js prettyprint-override"><code>export default { name: 'custom-button', data: function () { return { buttonText: 'I am child button!', } }, template: `&lt;button class=&quot;btn btn-success&quot;&gt;{{ buttonText }}&lt;/button&gt;` } </code></pre> <p>I wanted to know can the structure be improved or is there a downside or limitations of doing this? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-08T22:22:43.240", "Id": "481500", "Score": "0", "body": "In `CustomCard` the `data` has `cardText` but the template utilizes `message` - should that utilize `cardText` instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T03:20:06.860", "Id": "481613", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Didn't notice that. Thanks for pointing that out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T06:55:41.770", "Id": "481627", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T07:40:35.717", "Id": "242834", "Score": "0", "Tags": [ "javascript", "asp.net", "vue.js" ], "Title": "Vue.js in legacy web application" }
242834
<p>I've a created a simple generic numeric input component with input mask which must only valid decimal numbers as input. Please check the code for any improvements.</p> <pre><code>import React, { useState } from 'react'; import PatternConstants from '../Constants/PatternConstants.js'; const NumericInput = (props) =&gt; { const pattern = props.pattern ?? PatternConstants.NUMERIC_INPUT_PATTERN; const regexPattern = new RegExp(pattern); const initValue = regexPattern.test(props.value) ? props.value : ''; const [inputValue, updateInputValue] = useState(initValue); const onInputChange = (event) =&gt; { const value = event.target.value; if (value.charAt(value.length - 1) === '.' &amp;&amp; value.match(PatternConstants.NUMERIC_INPUT_LAST_DOT_PATTERN)?.length &lt; 2) { updateInputValue(value); } if (value === '' || regexPattern.test(value)) { updateInputValue(value); } } return ( &lt;input type="text" placeholder="Test" value={inputValue} onChange={(event) =&gt; onInputChange(event)} /&gt; ) } export default NumericInput; </code></pre> <p><strong>PatternConstants</strong></p> <pre><code>const PatternConstants = { NUMERIC_INPUT_PATTERN: /^[0-9]+(\.[0-9]+)?$/, NUMERIC_INPUT_LAST_DOT_PATTERN: /^[0-9]+(\.)$/, } export default PatternConstants; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T11:00:05.743", "Id": "242842", "Score": "1", "Tags": [ "react.js" ], "Title": "React.js Simple Numeric Input with Mask" }
242842
<p>I decided to challenge myself to code this data structure by just seeing how it looks visually and this is what I got. I can change this easily to minheap by changing some greater than (>) operators. If there are ways to make this efficient/more compact, I'd love to hear it.</p> <pre class="lang-py prettyprint-override"><code>class MaxHeap: def __init__(self, List=None): """ Initialises the data structure if a List is added as an argument, then it will make add the values in the list to the heap """ self.array = [] self.length = 0 if List: for value in List: self.insert(value) def __str__(self): """ for showing the heap on print() """ return str(self.array) def get_max(self): return self.array[0] if self.length else None def compare_to_parent(self, index): """ recursive function - used in insertion - index refers to the the new node that was just inserted - checks if the value added is in the right place in the heap, by comparing it with its parents + if the value of the new node is greater, than the places of the parent and the new value will be switched, and checking will be performed on the new position of the new value and its new parent node, until the parent node is greater than the new value. + if the value of the parent node is already greater than the checking stops. + if the 0th index is reached, then the check is complete. """ if index == 0: return True elif index == 1: parent_index = 0 else: parent_index = index//2 if self.array[parent_index] &gt; self.array[index]: return True else: self.array[parent_index], self.array[index] = self.array[index], self.array[parent_index] self.compare_to_parent(parent_index) def compare_to_child(self, parent_index, left_index, right_index, largest_index): """ Iterative function, because if recursion is performed, it may exceed its limit - used in popping/removing the max value - parent index refers to the most recently added value to the list which replaces the max and becomes the root node instead - largest_index refers to the largest index in the list, for which the checking will stop if reached. - checks if the new value of node is in the right place, by comparing with its children + if there is a child greater than the new value, the greater child will switch it's position with it, and it keeps happening till the left index or the right index, becomes larger than the largest possible index in the list + if neither child is greater, then the checking stops. """ while True: if left_index &gt; largest_index: break elif right_index &gt; largest_index: if self.array[left_index] &gt; self.array[parent_index]: self.array[parent_index], self.array[left_index] = self.array[left_index], self.array[parent_index] break else: if self.array[left_index] &gt; self.array[parent_index] and self.array[left_index] &gt; self.array[right_index]: self.array[parent_index], self.array[left_index] = self.array[left_index], self.array[parent_index] parent_index = left_index elif self.array[right_index] &gt; self.array[parent_index] and self.array[right_index] &gt; self.array[left_index]: self.array[parent_index], self.array[right_index] = self.array[right_index], self.array[parent_index] parent_index = right_index else: break left_index = parent_index*2 + 1 right_index = parent_index*2 + 2 def insert(self, value): """ inserts a value to the heap - no checking occurs until there is atleast 2 values, since there is no point in checking the parent node, when the only value is in the root node. """ self.array.append(value) if self.length != 0: self.compare_to_parent(self.length) self.length += 1 def pop_max(self): """ pops the max out of the heap, which is the first value in the array. """ if self.length == 0: return elif self.length == 1: return self.array.pop() else: max_value = self.get_max() self.array[0] = self.array.pop() self.length -= 1 self.compare_to_child(0, 1, 2, self.length-1) return max_value </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T11:34:36.257", "Id": "242844", "Score": "2", "Tags": [ "python", "python-3.x", "tree", "heap" ], "Title": "Max Heap Implementation in Python" }
242844
<p>I'm new to using type hinting in Python. I've used it for a small scraper I had to build (see code below), everything works fine and mypy gives no errors. However I'm sure there are better ways to write this (avoiding the repetition between the <code>Ratings</code> and <code>ScrapedData</code> tuples, better way to handle the <code>Literal</code> in function signature). Any feedback is greatly appreciated, even on other aspects of the code.</p> <p>I'm using Python 3.7 so I don't think I can use <code>TypedDict</code>.</p> <pre><code>import os import requests import lxml.html import pandas as pd from lxml.html import HtmlElement from requests import Session from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from enum import Enum from typing import List, Optional, NamedTuple from typing_extensions import Literal from multiprocessing import Pool HEADER = {"User-Agent": "Mozilla/5.0"} TITLE_XPATH = '//div[@class="review-title"]' REVIEW_XPATH = '//section[@class="review-container"]' SENTIMENT_XPATH = '//div[@class="left-header"]' RATING_XPATH = '//section[@itemprop="reviewrating"]' SUBJECT_XPATH = './/div[@class="subject"]' STAR_XPATH = './/span[@class="or-sprite-inline-block common_yellowstar_desktop"]' POSITIVE_XPATH = './/div[contains(@class, "smiley_smile")]' NEUTRAL_XPATH = './/div[contains(@class, "smiley_ok")]' NEGATIVE_XPATH = './/div[contains(@class, "smiley_cry")]' class Evaluation(Enum): POSITIVE: int = 1 NEUTRAL: int = 0 NEGATIVE: int = -1 NONE: None = None class Ratings(NamedTuple): taste: Optional[int] = None environment: Optional[int] = None service: Optional[int] = None hygiene: Optional[int] = None value: Optional[int] = None class ScrapedData(NamedTuple): url: str title: Optional[str] = None review: Optional[str] = None sentiment: Literal[ Evaluation.POSITIVE, Evaluation.NEUTRAL, Evaluation.NEGATIVE, Evaluation.NONE ] = Evaluation.NONE taste: Optional[int] = None environment: Optional[int] = None service: Optional[int] = None hygiene: Optional[int] = None value: Optional[int] = None class Scraper: def __init__(self, url_file: str) -&gt; None: if not os.path.exists(url_file): raise OSError("File Not Found: %s" % url_file) with open(url_file, "r") as fp: self.urls = [_.strip() for _ in fp.readlines()] self.data: list = [] @staticmethod def __requests_retry_session( retries: int = 3, backoff_factor: float = 0.3, status_forcelist: tuple = (500, 502, 504), session: Session = None, ) -&gt; Session: """ Handles retries for request HTTP requests params are similar to those for requests.packages.urllib3.util.retry.Retry https://www.peterbe.com/plog/best-practice-with-retries-with-requests """ session = session or requests.Session() retry = Retry( total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, ) adapter = HTTPAdapter(max_retries=retry) session.mount("http://", adapter) session.mount("https://", adapter) return session @staticmethod def __safe_extract_text(elements: List[HtmlElement]) -&gt; Optional[str]: """ Returns the text content of the first element extracted from Xpath or None if none has been found :param elements: The result of a call to .xpath on the tree :return: the string extracted or None if there are no elements """ if len(elements) &gt; 0: return elements[0].text_content() else: return None @staticmethod def __extract_sentiment( elements: List[HtmlElement] ) -&gt; Literal[ Evaluation.POSITIVE, Evaluation.NEUTRAL, Evaluation.NEGATIVE, Evaluation.NONE ]: if len(elements) &lt; 1: return Evaluation.NONE element = elements[0] if len(element.xpath(POSITIVE_XPATH)) &gt; 0: return Evaluation.POSITIVE elif len(element.xpath(NEUTRAL_XPATH)) &gt; 0: return Evaluation.NEUTRAL elif len(element.xpath(NEGATIVE_XPATH)) &gt; 0: return Evaluation.NEGATIVE return Evaluation.NONE @staticmethod def __extract_ratings(elements) -&gt; Ratings: if len(elements) &lt; 1: return Ratings() element = elements[0] rating_subjects = element.xpath(SUBJECT_XPATH) if len(rating_subjects) != 5: return Ratings() extracted_ratings = Ratings( *[len(_.xpath(STAR_XPATH)) for _ in rating_subjects] ) return extracted_ratings def scrape_page(self, url: str) -&gt; ScrapedData: print("Scraping : %s" % url) r = self.__requests_retry_session().get(url, headers=HEADER, timeout=10) tree = lxml.html.fromstring(r.content) # Extract title title = self.__safe_extract_text(tree.xpath(TITLE_XPATH)) # Extract review review = self.__safe_extract_text(tree.xpath(REVIEW_XPATH)) # Extract overall sentiment sentiment = self.__extract_sentiment(tree.xpath(SENTIMENT_XPATH)) # Extract specific grades ratings = self.__extract_ratings(tree.xpath(RATING_XPATH)) return ScrapedData( url, title, review, sentiment.value, *ratings._asdict().values() ) def scrape(self) -&gt; None: p = Pool(5) self.data = p.map(self.scrape_page, self.urls) p.terminate() p.join() def save(self, output_file: str = "content.csv"): data = pd.DataFrame(self.data) data.to_csv(output_file, index=None) if __name__ == "__main__": s = Scraper("reviewsurl.csv") s.scrape() s.save() </code></pre> <pre><code> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:03:50.227", "Id": "476627", "Score": "0", "body": "Just a quick comment: in Python 3.7 `TypedDict` is available in `typing_extensions` even though it didn't land in `typing` until 3.8." } ]
[ { "body": "<h2>Optional</h2>\n\n<p>I find it less useful to include <code>None</code> in an enum like <code>Evaluation</code>, and more useful to write <code>Optional[Evaluation]</code> where appropriate. It's useful to be able to choose whether you have a value that cannot be <code>None</code> at a certain point, or otherwise, based on context.</p>\n\n<p>In other words, this:</p>\n\n<pre><code>sentiment: Literal[\n Evaluation.POSITIVE, Evaluation.NEUTRAL, Evaluation.NEGATIVE, Evaluation.NONE\n ] = Evaluation.NONE\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>sentiment: Optional[Evaluation] = None\n</code></pre>\n\n<p>The same goes for the return value of <code>__extract_sentiment</code>.</p>\n\n<h2>File existence</h2>\n\n<p>I find this:</p>\n\n<pre><code> if not os.path.exists(url_file):\n raise OSError(\"File Not Found: %s\" % url_file)\n</code></pre>\n\n<p>to be redundant. <code>open</code> will do that for you.</p>\n\n<h2>Lists</h2>\n\n<p>Since you're learning about type hinting: what is this a list <em>of</em>?</p>\n\n<pre><code>self.data: list = []\n</code></pre>\n\n<p>Similarly, this:</p>\n\n<pre><code>status_forcelist: tuple = (500, 502, 504)\n</code></pre>\n\n<p>is probably</p>\n\n<pre><code>status_forcelist: Tuple[int, ...] = (500, 502, 504)\n</code></pre>\n\n<h2>Inner lists</h2>\n\n<pre><code> extracted_ratings = Ratings(\n *[len(_.xpath(STAR_XPATH)) for _ in rating_subjects]\n )\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> extracted_ratings = Ratings(\n *(len(_.xpath(STAR_XPATH)) for _ in rating_subjects)\n )\n</code></pre>\n\n<p>In other words, unpack a generator, not a materialized list. Also, never call a variable <code>_</code> if you actually use it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:12:01.120", "Id": "242849", "ParentId": "242845", "Score": "7" } } ]
{ "AcceptedAnswerId": "242849", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T12:14:57.063", "Id": "242845", "Score": "6", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "Web scraper for restaurant ratings" }
242845
<p>I'm using this class as Modal in my CodeIgniter project, as I'm newbie in CI, I wanna know if this has some issues, I'm using this modal for all queries, like I call this with parameters and it returns results as I wanted. But I'm not sure if it a good idea or it might give some bad impact to structure and security.</p> <pre><code>&lt;?php defined('BASEPATH') OR exit('No direct script access allowed'); class Crud extends CI_Model { public function Read($TableName, $Condition) { if ($Condition == '') $Condition = ' 1'; $this-&gt;db-&gt;where($Condition); $data = $this-&gt;db-&gt;get($TableName); return $data-&gt;result(); } public function Create($data, $TableName) { if ($this-&gt;db-&gt;insert($data, $TableName)) return $this-&gt;db-&gt;insert_id(); else return false; } public function Update($TableName, $Fields, $Condition) { if ($Condition == '') $Condition = ' 1'; $this-&gt;db-&gt;where($Condition); if ($this-&gt;db-&gt;update($TableName, $Fields)) return true; else return false; } public function Delete($TableName, $Condition) { if ($Condition == '') $Condition = ' 1'; $this-&gt;db-&gt;where($Condition); if ($this-&gt;db-&gt;delete($TableName)) return true; else return false; } public function Count($TableName, $Condition) { if ($Condition == '') $Condition = ' 1'; $this-&gt;db-&gt;where($Condition); $result = $this-&gt;db-&gt;get($TableName); if ($result) return $result-&gt;num_rows(); else return false; } </code></pre> <p>I call this methods like this in my controller</p> <pre><code>public function changeStatus() { $tableName = $this-&gt;uri-&gt;segment(4); $status = $this-&gt;uri-&gt;segment(5); $conditionId = $this-&gt;uri-&gt;segment(6); $condition = " `id` = '$conditionId'"; $data = [ 'is_active' =&gt; $status ]; if($this-&gt;Crud-&gt;Update($tableName, $data, $condition)) $this-&gt;session-&gt;set_flashdata('success', "Success! Changes saved"); else $this-&gt;session-&gt;set_flashdata('danger', "Something went wrong"); $referer = basename($_SERVER['HTTP_REFERER']); redirect('admin/seller/'.$referer); } </code></pre> <p>Please let me know if I can provide more information</p>
[]
[ { "body": "<p>In accordance with <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a>, your method names should be in camelCase. To avoid function name conflicts (native <code>count()</code> with custom <code>count()</code>), it may be best to prefix the method names' functionality with <code>easy</code> or <code>simple</code>, <code>ci</code>, or <code>ar</code> for Active Record.</p>\n\n<p>\"Embrace the curly brace.\" Always use curly braces to encapsulate your language construct and function bodies -- even if they only have one line of code inside them. Not using <code>{</code> and <code>}</code> may lead to developer confusion or unintended/incorrect code logic.</p>\n\n<p>For versatility, I recommend passing an array of arrays to your Crud methods. This will allow you to separate column names from values, enable you to turn off CI's automatic quoting (<code>protect_identifiers</code> flag) when necessary (3rd element in a respective subarray), and effortlessly pass multiple where conditions when required. There is a multitude of reasons for this utility -- here is just one: <a href=\"https://stackoverflow.com/q/2489453/2943403\">https://stackoverflow.com/q/2489453/2943403</a>.</p>\n\n<p>Granted, your <code>Read()</code> method _could_be as simple as passing the table name and an associative array of conditions to <code>get_where()</code>, but that approach doesn't permit the flexibility of turning off the auto-quoting.</p>\n\n<p>Make the default <code>$condition</code> parameter value an empty array. I don't like the meaningless <code>WHERE 1</code> in any project.</p>\n\n<p>Use a foreach loop to only add a WHERE clause when there is actually something useful to write inside it.</p>\n\n<pre><code>public function ciRead($tableName, $conditions = []) {\n foreach ($conditions as $condition) {\n $this-&gt;db-&gt;where($condition);\n }\n $this-&gt;db-&gt;get($tableName)-&gt;result();\n}\n</code></pre>\n\n<p><code>insert()</code> <a href=\"https://stackoverflow.com/q/3360631/2943403\">should have the table name as the first parameter</a>.</p>\n\n<pre><code>public function ciCreate($tableName, $data) {\n return $this-&gt;db-&gt;insert($tableName, $data) ? $this-&gt;db-&gt;insert_id() : false;\n}\n</code></pre>\n\n<p>For <code>update()</code> loop the conditions like in <code>read()</code> I recommend returning the affected rows so that there is a truer representation of success. I often treat the affected rows value as a boolean or explicitly cast it with <code>(bool)</code> if I only need a truthy/falsey value and I want to make the coding intention very clear. </p>\n\n<pre><code>public function ciUpdate($tableName, $data, $conditions = []) {\n foreach ($conditions as $condition) {\n $this-&gt;db-&gt;where($condition);\n }\n return $this-&gt;db-&gt;update($tableName, $data) ? $this-&gt;db-&gt;affected_rows() : false;\n}\n</code></pre>\n\n<p>Same thinking with <code>delete()</code> regarding a more accurate return value...</p>\n\n<pre><code>public function ciDelete($tableName, $conditions = []) {\n foreach ($conditions as $condition) {\n $this-&gt;db-&gt;where($condition);\n }\n return $this-&gt;db-&gt;delete($tableName) ? $this-&gt;db-&gt;affected_rows() : false;\n}\n</code></pre>\n\n<p>When counting, CI has <code>count_all_results()</code>.</p>\n\n<pre><code>public function ciCount($tableName, $conditions = []) {\n foreach ($conditions as $condition) {\n $this-&gt;db-&gt;where($condition);\n }\n return $this-&gt;db-&gt;count_all_results($tableName);\n}\n</code></pre>\n\n<hr>\n\n<p>In your controller (assuming all of the routing is set up properly), you should be collecting the slash-delimited input values as parameters of the method call instead of writing out all of those <code>segment()</code> calls.</p>\n\n<p>Using <code>$_GET</code> data is perfectly fine when calling your <code>Read()</code> or <code>Count()</code> methods, but it is not recommended when you are writing to the database. For <code>Insert()</code>, <code>Update()</code>, and <code>Delete()</code>, you need to be collecting user-supplied data via <code>$_POST</code> data only.</p>\n\n<p>Be sure to validate and sanitize the incoming data in your controller before allowing access to your model methods.</p>\n\n<p>Don't give your users any more access/privilege than absolutely necessary. I wouldn't be letting people know what my table or column names are called. I wouldn't want to offer them the flexibility to nominate the table/column that they want to access -- purely on the grounds of security.</p>\n\n<p>Perhaps provide some kind of alias/whitelist to convert the user data to model entity identifiers (translate the table/column names with in the model) or ideally make all of the table/column names static/hardcoded (provided by you, the developer).</p>\n\n<pre><code>public function fetch($tableName, $conditionId) {\n $result = $this-&gt;Crud-&gt;ciRead($tableName, [['id', $conditionId]]));\n ...\n}\n</code></pre>\n\n<p>or when writing to the db use <code>post()</code>.</p>\n\n<pre><code>public function changeStatus() {\n $tableName = $this-&gt;input-&gt;post('tableName'); // I don't like it\n $status = $this-&gt;input-&gt;post('status');\n $conditionId $this-&gt;input-&gt;post('conditionId');\n if ($this-&gt;Crud-&gt;ciUpdate($tableName, ['is_active' =&gt; $status], [['id', $conditionId]])) {\n $this-&gt;session-&gt;set_flashdata('success', \"Success! Changes saved\");\n } else {\n $this-&gt;session-&gt;set_flashdata('danger', \"Something went wrong\");\n }\n redirect('admin/seller/' . basename($_SERVER['HTTP_REFERER']));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:07:00.927", "Id": "242921", "ParentId": "242848", "Score": "2" } } ]
{ "AcceptedAnswerId": "242921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T13:56:32.103", "Id": "242848", "Score": "2", "Tags": [ "php", "codeigniter" ], "Title": "Using dynamic methods to build SQL queries in CodeIgniter" }
242848
<p>I am trying to solve this question: <a href="https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/" rel="nofollow noreferrer">MaxCounters</a>.</p> <p>Solving it is straightforward, but solving it fast enough is proving very difficult. How can I improve the performance of this code? At the moment it is too slow for the <code>large_random_2</code> and <code>extreme_large</code> tests.</p> <pre><code>function solution(N, A) { const M = A.length; let max = 0; let counters = new Array(N); if (M &lt;= 0) { return -1; } // set counters to 0 for (let i = 0; i &lt; N; i++) { counters[i] = 0; } for (let K = 0; K &lt; M; K += 1) { if (A[K] === N + 1) { // set counters to last maximum for (let j = 0; j &lt; N; j++) { counters[j] = max; } } else if (A[K] &gt; 0 &amp;&amp; A[K] &lt;= N) { // add one to counter counters[A[K] - 1] = counters[A[K] - 1] + 1; // update maximum if (counters[A[K] - 1] &gt; max) { max = counters[A[K] - 1]; } } } return counters; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:58:52.257", "Id": "476637", "Score": "2", "body": "Welcome to Code Review. If you include the description of the task and examples of input and output expected, you have a greater possibility to obtain more detailed answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T15:19:26.993", "Id": "476641", "Score": "2", "body": "Your title is too generic. Please read the appropriate pages in the Help center." } ]
[ { "body": "<p>You can save some time by not running through every counter and setting them to the maximum each time max gets called. Since they are all equivalent at the start and after each time the max is called, you can just record the current maximum counter value (in between each call of max) and add it all together at the end, rather than updating every counter element each time max is called.</p>\n\n<pre><code>let currentTally = {};\nlet currentMax = 0;\nlet total = 0;\nfor (let K = 0; K &lt; M; K += 1) {\n if (A[K] &lt;= N) {\n if(currentTally[A[K]]){\n currentTally[A[K]] += 1;\n }else {\n currentTally[A[K]] = 1;\n }\n if( currentTally[A[K]] &gt; currentMax) {\n currentMax = currentTally[A[K]];\n }\n }\n\n if (A[K] === N + 1) {\n total += currentMax;\n currentTally = {};\n currentMax = 0;\n } \n }\n }\n for(let i = 0; i &lt; counters.length; i++) {\n if(currentTally[i]){\n counters[i] = total + currentTally[i];\n }else{\n counters[i] = total;\n }\n }\n</code></pre>\n\n<p>Also, this way, no need to set all counters to zero in the first place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T19:53:24.940", "Id": "242870", "ParentId": "242851", "Score": "2" } }, { "body": "<h2>Algorithm</h2>\n\n<p>As the answer by eaeaoo implies, the runtime complexity can be reduced to <span class=\"math-container\">\\$O(N+M)\\$</span> by keeping track of the minimum baseline (max counter to set all to). This aligns with other solutions (e.g. <a href=\"https://codereview.stackexchange.com/q/151574/120114\">this python comparison</a>).</p>\n\n<p>To minimize the space complexity even more, the data structure for the tallies can remain in an array instead of an object/map, and a second variable for the \"last\" max -e.g. <code>lastMax</code> can be used to track the most recent maximum value to use in the second loop.</p>\n\n<pre><code>let currentMax = 0;\nlet lastMax = 0;\nconst M = A.length;\nconst counters = Array(N).fill(0);\nfor (const currentValue of A) {\n if (currentValue &gt; N) {\n lastMax = currentMax \n } \n else {\n const position = currentValue - 1;\n if (counters[position] &lt; lastMax) {\n counters[position] = lastMax;\n }\n counters[position]++;\n if (counters[position] &gt; currentMax) {\n currentMax = counters[position];\n }\n }\n}\nfor (let i = 0; i &lt; N; i++) {\n if (counters[i] &lt; lastMax) {\n counters[i] = lastMax;\n }\n}\nreturn counters;\n</code></pre>\n\n<h2>Review of current code</h2>\n\n<p>One of the first blocks is this:</p>\n\n<blockquote>\n<pre><code>if (M &lt;= 0) {\n return -1;\n}\n</code></pre>\n</blockquote>\n\n<p>That is good to do, though the description reads: </p>\n\n<blockquote>\n <p>A non-empty array A of M integers is given. </p>\n</blockquote>\n\n<p>It doesn't hurt to check for that condition but know that it shouldn't happen. If you are going to have it then have it return as early as possible so as to minimize memory allocation and processing - e.g. before declaring other variables like <code>max</code> and <code>counters</code>.</p>\n\n<p>This block initializes values to <code>0</code>:</p>\n\n<blockquote>\n<pre><code>// set counters to 0\nfor (let i = 0; i &lt; N; i++) {\n counters[i] = 0;\n}\n</code></pre>\n</blockquote>\n\n<p>Instead consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>Array.fill(0)</code></a> like the code in the sample code above uses. This allows <code>counters</code> to be declared with <code>const</code> since the array itself wouldn't need to be re-assigned. This helps avoid accidental re-assignment later when modifying your code.</p>\n\n<pre><code>const counters = Array(N).fill(0);\n</code></pre>\n\n<p>And the <code>for</code> loop:</p>\n\n<blockquote>\n<pre><code>for (let K = 0; K &lt; M; K += 1) {\n</code></pre>\n</blockquote>\n\n<p>Can be replaced with a <code>for...of</code> loop (as used in the sample code above) since <code>K</code> is only used to dereference indexes in <code>A</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T05:19:10.727", "Id": "243163", "ParentId": "242851", "Score": "1" } } ]
{ "AcceptedAnswerId": "242870", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:21:07.237", "Id": "242851", "Score": "4", "Tags": [ "javascript", "performance", "programming-challenge", "array", "iteration" ], "Title": "Maxcounters in JavaScript" }
242851
<p>I am writing a modified travelling salesman problem recursively in Python 3.7. It has to find the best path around breweries to find the most beer types and not to exceed the <code>max_distance</code>. The problem is the execution time. I left it to run for 10 hours and it still didn't calculate final answer. When <code>max_distance</code> is set to 1000 it executes in about 40ms. I am not sure there is a possibility to use dynamic programming to solve this problem. I tried using <code>dask</code> but got a lot of errors.</p> <p>Is there any other way to improve this code to make it run faster?</p> <pre><code>import copy from math import radians, cos, sin, asin, sqrt from datetime import datetime best_path = [] best_beer_count = 0 best_distance = 0 class Brewery: def __init__(self, _brewery, beer, distance=0, visited=False): self.beer = beer self.id = _brewery[0] self.name = _brewery[1] self.longitude = _brewery[2] self.latitude = _brewery[3] self.distance_to_home = distance self.visited = visited def __str__(self): return "[{}, '{}', {}, {}],".format(self.id, self.name, self.longitude, self.latitude) def merge_breweries_with_beers(breweries, beers): breweries_list = [] for i in range(len(breweries)): breweries_list.append(Brewery(breweries[i], beers[i])) return list(breweries_list) def haversine(lat1, lon1, lat2, lon2): """Returns distance between given coordinates""" lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) r = 6371 return c * r def get_breweries_within_1000(lat, lon, breweries): breweries_1000 = [] for brewery in breweries: distance = haversine(lat, lon, brewery.latitude, brewery.longitude) brewery.distance_to_home = distance if distance &lt;= 1000: breweries_1000.append(brewery) return breweries_1000 def get_breweries_within_specific_distance(brew: Brewery, breweries, given_distance): """Returns list of breweries within specified distance""" breweries_specific_distance = [] for brewery in breweries: distance = haversine(brew.latitude, brew.longitude, brewery.latitude, brewery.longitude) if given_distance &gt; distance: breweries_specific_distance.append(brewery) return breweries_specific_distance def make_graph(breweries): x = [[None for i in range(len(breweries))] for j in range(len(breweries))] for i in range(len(x)): for j in range(len(x)): distance = haversine(breweries[i].latitude, breweries[i].longitude, breweries[j].latitude, breweries[j].longitude) x[i][j] = distance return x def set_best_path(curr_path): global best_beer_count global best_distance global best_path curr_beer_count = get_distinct_beer(curr_path) curr_distance = get_total_distance(curr_path) if curr_beer_count &gt; best_beer_count: best_beer_count = curr_beer_count best_distance = curr_distance best_path = curr_path.copy() print(str(curr_path[1].id) + curr_path[1].name) print('Breweries count: ' + str(len(curr_path) - 2)) print('Beer count: ' + str(best_beer_count)) print('Distance: ' + str(best_distance) + '\n') elif curr_beer_count == best_beer_count and curr_distance &lt; best_distance: best_beer_count = curr_beer_count best_distance = curr_distance best_path = curr_path.copy() print('Distance was better') print(str(curr_path[1].id) + curr_path[1].name) print('Breweries count: ' + str(len(curr_path) - 2)) print('Beer count: ' + str(best_beer_count)) print('Distance: ' + str(best_distance) + '\n') def tsp_rec(breweries: [Brewery], distance_traveled, curr_pos, path, graph_of_distances): max_distance = 2000 if len(path) != 0: new_path = path.copy() home = breweries[0] new_path[:0] = [home] home_final = copy.deepcopy(home) home_final.distance_to_home = haversine(home_final.latitude, home_final.longitude, path[-1].latitude, path[-1].longitude) new_path.append(home_final) set_best_path(new_path) for i in range(len(breweries)): if not breweries[i].visited: distance = distance_traveled + graph_of_distances[curr_pos][i] if distance + breweries[i].distance_to_home &gt; max_distance: continue breweries[i].visited = True path.append(breweries[i]) tsp_rec(breweries, distance, i, path, graph_of_distances) path.remove(breweries[i]) breweries[i].visited = False return def get_distinct_beer(path): beer = [] for i in path: for j in i.beer: beer.append(j) unique_beer = list(set(beer)) return len(unique_beer) def get_total_distance(path): distance = 0 for i in range(len(path) - 1): distance += haversine(path[i].latitude, path[i].longitude, path[i + 1].latitude, path[i + 1].longitude) return distance def main(): breweries = ([15, 'Aktienbrauerei Kaufbeuren', 10.616100311279297000, 47.878101348876950000], [26, 'Allguer Brauhaus AG Kempten', 10.569399833679200000, 47.748699188232420000], [30, 'Alpirsbacher Klosterbru', 8.403100013732910000, 48.345699310302734000], [37, 'Amstel Brouwerij', 4.890900135040283000, 52.373798370361330000], [40, 'Andechser Klosterbrauerei', 11.185000419616700000, 47.977500915527344000], [70, 'Bamberger Mahrs-Bru', 10.906700134277344000, 49.890098571777344000], [74, 'Barfer - das kleine Brauhaus', 9.989899635314941000, 48.397899627685550000], [88, 'Bayerische Staatsbrauerei Weihenstephan', 11.728799819946289000, 48.395198822021484000], [103, 'Berliner Kindl Brauerei AG', 13.429300308227539000, 52.479301452636720000], [104, 'Berliner-Kindl-Schultheiss-Brauerei', 13.411399841308594000, 52.523399353027344000], [109, 'Bierbrouwerij Bavaria', 5.597700119018555000, 51.516300201416016000], [110, 'Bierbrouwerij De Koningshoeven', 5.128499984741211000, 51.543998718261720000], [110, 'Bierbrouwerij De Koningshoeven', 5.128499984741211000, 51.543998718261720000], [111, 'Bierbrouwerij St.Christoffel', 6.051499843597412000, 51.168399810791016000], [125, 'Binding Brauerei AG', 8.691300392150879000, 50.094299316406250000], [127, 'Birra Moretti', 13.226900100708008000, 46.059700012207030000], [131, 'Bitburger Brauerei', 6.522699832916260000, 49.973999023437500000], [156, 'BOSS Browar Witnica S.A.', 14.900400161743164000, 52.673900604248050000], [167, 'Brasserie DAchouffe', 5.744200229644775000, 50.150699615478516000], [175, 'Brasserie de lAbbaye Val-Dieu', 5.822000026702881000, 50.704601287841800000], [192, 'Brasserie Fantme', 5.512700080871582000, 50.285999298095700000], [203, 'Brasseries Kronenbourg', 7.714900016784668000, 48.592998504638670000], [204, 'Brauerei &amp; Gasthof zur Krone', 9.588800430297852000, 47.671501159667970000], [205, 'Brauerei Aying Franz Inselkammer KG', 11.780799865722656000, 47.970600128173830000], [206, 'Brauerei Beck', 8.790100097656250000, 53.078701019287110000], [207, 'Brauerei C. &amp; A. Veltins GmbH &amp; Co.', 8.125900268554688000, 51.305500030517580000], [208, 'Brauerei Fssla', 10.885499954223633000, 49.894199371337890000], [209, 'Brauerei Gbr. Maisel KG', 11.565899848937988000, 49.947700500488280000], [210, 'Brauerei Grieskirchen AG', 13.829199790954590000, 48.235099792480470000], [211, 'Brauerei Gss', 15.094699859619140000, 47.362499237060550000], [212, 'Brauerei Herrenhausen', 9.681400299072266000, 52.393501281738280000], [213, 'Brauerei Hrle', 10.023900032043457000, 47.824298858642580000], [214, 'Brauerei Hrlimann', 8.524499893188477000, 47.364200592041016000], [216, 'Brauerei Leibinger', 9.621500015258789000, 47.781799316406250000], [217, 'Brauerei Locher AG', 9.413499832153320000, 47.330101013183594000], [218, 'Brauerei Reissdorf', 6.994400024414062500, 50.875301361083984000], [219, 'Brauerei Schtzengarten', 9.379400253295898000, 47.430099487304690000], [220, 'Brauerei Schumacher', 6.785299777984619000, 51.221599578857420000], [221, 'Brauerei Schwelm', 7.293600082397461000, 51.284698486328125000], [222, 'Brauerei Spezial', 10.885499954223633000, 49.894199371337890000], [223, 'Brauerei und Altbierkche Pinkus Mller', 7.621399879455566000, 51.965698242187500000], [225, 'Brauereigasthof Adler', 9.399600028991700000, 48.077800750732420000], [228, 'Brauhaus Faust', 9.249199867248535000, 49.699298858642580000], [229, 'Brauhaus Johann Albrecht - Dsseldorf', 6.751599788665771500, 51.240398406982420000], [230, 'Brauhaus Johann Albrecht - Konstanz', 9.175000190734863000, 47.665100097656250000], [232, 'Brauhaus Sion', 6.959400177001953000, 50.939399719238280000], [233, 'Brauhaus Sternen', 8.900600433349610000, 47.558498382568360000], [234, 'Brausttte der Steirerbrau Aktiengesellschaft', 15.441699981689453000, 47.067901611328125000], [238, 'Brennerei-Distillerie Radermacher', 6.122000217437744000, 50.671798706054690000], [245, 'Brewery Budweiser Budvar', 14.475000381469727000, 48.973899841308594000], [246, 'Brewery Corsendonk', 4.988999843597412000, 51.314399719238280000], [261, 'Brouwerij t IJ', 4.926300048828125000, 52.366600036621094000], [270, 'Brouwerij De Achelse Kluis', 5.489600181579590000, 51.298599243164060000], [280, 'Brouwerij der Sint-Benedictusabdij de Achelse Kluis', 5.546000003814697000, 51.251499176025390000], [286, 'Brouwerij Kerkom', 5.165999889373779000, 50.776298522949220000], [293, 'Brouwerij Sint-Jozef', 5.646399974822998000, 51.116798400878906000], [307, 'Browar Okocim', 20.600299835205078000, 49.962200164794920000], [309, 'Browar Zywiec', 19.174200057983400000, 49.662200927734375000], [312, 'Bryggeriet lfabrikken', 12.116100311279297000, 56.074600219726560000], [344, 'Carlsberg Bryggerierne', 12.539299964904785000, 55.666698455810550000], [345, 'Carlsberg Sverige AB', 12.540499687194824000, 56.900199890136720000], [386, 'Clner Hofbrau Frh', 6.956999778747559000, 50.940101623535156000], [429, 'De Friese Bierbrouwerij Us Heit', 5.534200191497803000, 53.060600280761720000], [448, 'Diebels Privatbrauerei', 6.421299934387207000, 51.533100128173830000], [460, 'Dortmunder Actien Brauerei DAB', 7.469200134277344000, 51.529800415039060000], [465, 'Dreher Srgyrak Zrt.', 19.142200469970703000, 47.492099761962890000], [480, 'Eder &amp; Heylands', 9.071499824523926000, 49.921100616455080000], [484, 'Einbecker Brauhaus AG', 9.864299774169922000, 51.816200256347656000], [511, 'Ettaler Klosterbetriebe Abteilung Brauerei &amp; Destillerie', 11.094200134277344000, 47.569000244140625000], [534, 'Flensburger Brauerei', 9.435500144958496000, 54.778999328613280000], [558, 'Friesisches Brauhaus zu Jever', 7.901599884033203000, 53.575500488281250000], [561, 'Frstliche Brauerei Thurn Und Taxis Regensburg', 12.091300010681152000, 49.015598297119140000], [567, 'Gasthaus &amp; Gosebrauerei Bayerischer Bahnhof', 12.371399879455566000, 51.339698791503906000], [568, 'Gasthaus-Brauerei Max &amp; Moritz', 9.606100082397461000, 47.606399536132810000], [569, 'Gasthof-Brauerei zum Frohsinn', 9.430000305175781000, 47.517101287841800000], [570, 'Gatz Brauhaus', 6.775700092315674000, 51.224899291992190000], [573, 'Gilde Brauerei', 9.753199577331543000, 52.354400634765625000], [616, 'Grolsche Bierbrouwerij', 6.816299915313721000, 52.208099365234375000], [619, 'Gulpener Bierbrouwerij', 5.921299934387207000, 50.810901641845700000], [621, 'Hacker-Pschorr Bru', 11.580200195312500000, 48.139099121093750000], [628, 'Hannen Brauerei', 6.442100048065185500, 51.191299438476560000], [639, 'Hasserder Brauerei', 10.753299713134766000, 51.843898773193360000], [640, 'Hausbrauerei Zum Schlssel', 6.774499893188477000, 51.226100921630860000], [649, 'Heineken Switzerland', 8.730199813842773000, 47.507701873779300000], [650, 'Heller Bru Trum', 10.885299682617188000, 49.891998291015625000], [659, 'Hirschbru Privatbrauerei Hss', 10.279000282287598000, 47.513198852539060000], [661, 'Hochstiftliches Brauhaus in Bayern', 9.772399902343750000, 50.394901275634766000]) beers = ([('St. Martin Doppelbock',), ('Jubiläums German Pils',)], [('Cambonator Doppelbock',), ('Winterfestival'), ('BayrischHell',)], [('Spezial',), ('Pils',)], [('Amstel Light',)], [('Doppelbock Dunkel',), ('Weißbier Dunkel',), ('Hell',)], [('Der Weisse Bock',), ('Hell',), ('Pilsner',), ('Ungespundet Lager Hefetrub',), ('Christmas Bock',), ('Weisse',), ('Hefeweißbier',)], [('Schwarze',), ('Blonde',), ('Rotgold-Pils',)], [('Festbier',), ('Kristall Weissbier',), ('Hefeweissbier Dunkel',), ('Original Lager',), ('Korbinian',), ('Hefe Weissbier',)], [('Weisse',)], [('Original Berliner Weisse',)], [('De Horste Vermeer Traditional Dutch Ale',), ('Hollandia',), ('Holland Beer',)], [('Quadrupel',), ('Tripel',), ('Dubbel',), ('La Trappe Quadrupel 2000/2001',), ('La Trappe Tripel',), ('La Trappe Enkel / La Trappe Blond',), ('La Trappe Dubbel',), ("Tilburg's Dutch Brown Ale",)], [('Quadrupel',), ('Tripel',), ('Dubbel',), ('La Trappe Quadrupel 2000/2001',), ('La Trappe Tripel',), ('La Trappe Enkel / La Trappe Blond',), ('La Trappe Dubbel',), ("Tilburg's Dutch Brown Ale",)], [('Robertus',), ('Christoffel Blond',)], [('Lager',)], [('La Rossa',), ('Birra Moretti La Rossa',)], [('Premium Beer',)], [('Mocny BOSS / BOSS Beer',), ('Porter Czarny Boss / Black BOSS Porter',)], [('Houblon',), ('McChouffe',), ('La Chouffe Golden Ale',), ('Chouffe-Bok',), ('Bière de Mars',)], [('Winter',), ('Grand Cru',), ('Triple',), ('Blonde',), ('Brune / Brown',)], [('Strange Ghost',), ('Chocolat',), ('Dark White',), ('Speciale Noël',)], [('1664',)], [('Coronator Helle Doppelbock',), ('See-Weizen Bio-Hefeweizen',), ('Kellerpils',), ('Pils',), ('Kronenbier',)], [('Ur-Weisse',), ('Altbairisch Dunkel',), ('Oktober Fest - Märzen',), ('Bräu-Weisse',), ('Jahrhundert-Bier',), ('Celebrator',)], [('St.Pauli Girl Special Dark',), ('St.Pauli Girl Beer',), ('Beer',), ('Dark',), ('Haacke-Beck',), ('Oktoberfest',), ("Beck's Light",)], [('Pilsner',)], [('Lagerbier',), ('Zwergla',), ('Gold-Pils',), ('Weizla Hell',)], [("Maisel's Weisse Kristall",)], [('Jörger Weiße Hell',)], [('Dark Beer / Stiftsbräu',)], [('Weizen Bier',), ('Premium Pilsener',)], [('Dunkle Weisse',)], [('Hexen Bräu',)], [('Edel-Pils',), ('Hefe-Weizen',), ('Edel-Spezial',)], [('Leermond Bier',)], [('Kölsch',)], [('St. Galler Landbier',)], [('Alt',)], [('Pils',), ('Hefe-Weizen',)], [('Rauchbier Lager',), ('Rauchbier Weissbier',), ('Rauchbier Märzen',), ('Ungespundetes',)], [('Jubilate Special Reserve Anniversary Ale',), ('Organic Ur Pils',), ('Obergärig / Münster Alt',), ('Organic Hefewizen',)], [('Zwickelbier',), ('Pils',), ('Spezial',)], [('Kräusen Naturtrüb',)], [('Kupfer',), ('Messing',)], [('Nickelbier',), ('Herbstbeer',), ('Weizen',), ('Kupfer',), ('Messing',)], [('Kölsch',)], [('Huusbier Schwarz',), ('Oktoberfest',), ('Weizentrumpf',), ('Honey Brown Ale',), ('Huusbier Hell',)], [('Gösser',)], [('Rader Ambrée',), ('Rader Blonde',)], [('Budweiser Budvar (Czechvar)',)], [('Christmas Ale',), ('Abbey Brown Ale / Pater',), ('Monk Pale Ale / Agnus Dei',), ('Monk Brown Ale',)], [('Zatte Amsterdamse Tripel',)], [('Trappist Extra',), ('Trappist Bruin Bier / Bière Brune',), ('Trappist Blond',)], [('Achel Blond 5°',), ('Achel Bruin 5°',), ('Achel Blond 8°',), ('Achel Bruin 8°',), ('Achel Trappist Extra',)], [('Bloesem Bink',), ('Winterkoninkse',)], [('Limburgse Witte',)], [('Okocim Porter',), ('O.K. Beer',)], [('Porter',), ('Krakus',)], [('Porter',)], [('Elephant',), ('47 Bryg',), ('Jacobsen Dark Lager',)], [('Carnegie Stark-Porter',), ('Falcon Lagrad Gammelbrygd',)], [('Kölsch',)], [('Us Heit Dubbel Tarwe Bier',)], [('German Premium Dark',), ('Alt',)], [('Traditional',), ('Original',), ('Hansa Imported Dortmunder',), ('Hansa Pils',)], [('Bak',), ('Dreher Classic',)], [('Schlappeseppl Export',)], [('Schwarzbier / Dunkel',), ('Ur-Bock Hell',)], [('Curator Dunkler Doppelbock',), ('Kloster Dunkel',), ('Kloster Edel-Hell',)], [('Pilsener',), ('Flensburger Pilsner',)], [('Pilsener',)], [('Schierlinger Roggen',)], [('Gose',)], [('Hefeweizen',), ('Spezial',), ('Kellerpils',)], [('Maisbier',), ('Weizenbier',), ('Dunkel',), ('Hell',)], [('Pils',), ('Helles Naturtrub',), ('Alt',)], [('Ratskeller',), ('Lindener Spezial',), ('Pilsener',)], [('Grolsch Amber Ale',), ('Grolsch Premium Weizen',), ('Grolsch Dunkel Weizen',), ('Grolsch Pilsner Speciale',), ('Grolsch Premium Pilsner',)], [('Dort',), ('Mestreechs Aajt',)], [('Original Oktoberfest',), ('Alt Munich Dark',), ('Weisse',)], [('Alt',), ('Hannen Alt',)], [('Premium Pils',)], [('Altbier',)], [('Original Ittinger Klosterbräu',)], [('Schlenkerla Helles Lagerbier',), ('Aecht Schlenkerla Rauchbier Märzen',), ('Aecht Schlenkerla Rauchbier Weizen',), ('Aecht Schlenkerla Rauchbier Urbock',)], [('Neuschwansteiner Bavarian Lager',), ('Doppel-Hirsch Bavarian-Doppelbock',), ('Bavarian-Weissbier Hefeweisse / Weisser Hirsch',)], [('Will-Bräu Ur-Bock',)]) breweries = merge_breweries_with_beers(list(breweries), list(beers)) lat = 51.74250300 lon = 19.43295600 breweries = get_breweries_within_1000(lat, lon, breweries) home = Brewery([None, 'Home', lon, lat], [], 0, True) breweries[:0] = [home] graph = make_graph(breweries) started = datetime.now() path = [] tsp_rec(breweries, 0, 0, path, graph) ended = datetime.now() for brew in best_path: print(brew) print(get_total_distance(best_path)) print('\n') print('\ndone') print("Started =", started) print("Ended =", ended) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T17:17:01.397", "Id": "476652", "Score": "1", "body": "Have you profiled the code to see where the bottlenecks are? Have you tried writing it in a non-interpretive language such as C++ to see what the difference in speed is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T18:49:42.710", "Id": "477038", "Score": "1", "body": "@pacmaninbw I tried to write this code in GO and it works more than 50 times faster. I wound a solution (it would be a solution if I could understand it). This a [document](https://www.cs.rhul.ac.uk/home/gutin/paperstsp/RCTSP.pdf)" } ]
[ { "body": "<p>Some of these are not performance improvements but are improvements nonetheless.</p>\n\n<h2>Brewery constructor</h2>\n\n<pre><code>def __init__(self, _brewery, beer, distance=0, visited=False):\n self.beer = beer\n self.id = _brewery[0]\n self.name = _brewery[1]\n self.longitude = _brewery[2]\n self.latitude = _brewery[3]\n self.distance_to_home = distance\n self.visited = visited\n...\n breweries_list.append(Brewery(breweries[i], beers[i]))\n</code></pre>\n\n<p>is problematic, particularly around the assumptions that <code>_brewery</code> makes. Unpack it elsewhere, i.e.</p>\n\n<pre><code>def __init__(\n self, \n brewery_id: int, \n name: str,\n longitude: float,\n latitude: float,\n beers: Sequence[str],\n distance: float=0, \n visited: bool=False,\n):\n self.brewery_id, self.name, self.longitude, self.latitude, self.beers, self.distance, self.visited = (\n brewery_id, name, longitude, latitude, beers, distance, visited,\n )\n...\n breweries_list.append(Brewery(\n *breweries[i],\n beers=beers[i],\n ))\n</code></pre>\n\n<p>Other things to note:</p>\n\n<ul>\n<li>Use type hints</li>\n<li>Do not use <code>id</code> as that shadows a built-in</li>\n<li>I'm unclear on why you don't just store <code>beers</code> as a tuple on <code>brewery</code>. You can do away with <code>merge_breweries_with_beers</code> altogether and just include the beer tuples in your main brewery database.</li>\n</ul>\n\n<h2>Database</h2>\n\n<p>Store it in a JSON file, not hard-coded into the source.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T16:22:26.677", "Id": "476646", "Score": "0", "body": "Thank you for your suggestions! I am using MariaDb for data, but I hardcoded it just for this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T16:24:39.333", "Id": "476647", "Score": "0", "body": "Fair enough. You should work on the current feedback, and then post a new question which shows the actual MariaDB calls. You will get better feedback on how to avoid that merge." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T16:16:14.977", "Id": "242862", "ParentId": "242855", "Score": "2" } }, { "body": "<h1>Criticisms</h1>\n\n<h2>Datatypes</h2>\n\n<p>Your data types own data they should not own. A <code>Brewery</code> has an identity, a location, and a set of beer it brews. It should not have a \"distance to home\" parameter, or a \"visited\" flag. Distance to who's home? Visited by whom?</p>\n\n<h2>Usability</h2>\n\n<p><code>haversine()</code> is not a very usable function; it requires 4 parameters. It would make more sense to pass in two <code>Location</code> objects, and get the distance between those locations. 2 parameters is easier to use than 4.</p>\n\n<h2>Configuration</h2>\n\n<p><code>max_distance</code> is hard-coded in the <code>tsp_rec</code> function. But from the problem description, it sounds like you change this value between 1000 and 2000. If so, why is it hard-coded and not a parameter?</p>\n\n<p><code>get_breweries_within_1000()</code> is even more brittle. The function name, and local variables include the distance limit. If you want to change the limit, what do you change? Just the hard-coded number, or the variable names and/or the function name too?</p>\n\n<h2>Global Variables</h2>\n\n<p>Global variables are to be eschewed, assiduously. They increase code coupling, and decrease usability and testability of code. It becomes harder to reason about the extent of the effects of a function, because global variables may be changed by any function, so one must examine each and every function to determine if it affects or is affected by a change elsewhere.</p>\n\n<pre><code> tsp_rec(breweries, 0, 0, path, graph)\n\n for brew in best_path:\n print(brew)\n</code></pre>\n\n<p>Is it obvious that <code>tsp_rec(...)</code> has changed the value of <code>best_path</code>? If the function were instead written to return the results directly, it would improve understandability and minimize side effects.</p>\n\n<h2>Don't pass in unnecessary arguments</h2>\n\n<p>Consider again the <code>tsp_rec(...)</code> function:</p>\n\n<pre><code> path = []\n tsp_rec(breweries, 0, 0, path, graph)\n</code></pre>\n\n<p>At the top level, it must be called with a <code>distance_traveled</code>, a <code>curr_pos</code> and a <code>path</code>. But is that a \"friendly\" interface design? Why require the user of the function to lookup the calling requirements and pass in the appropriate initial conditions when every caller of the top level would have to do exactly the same thing? It would make more sense to provide a clean top-level function, and use a recursive helper function. The top-level function would set up the initial top level call environment. Eg)</p>\n\n<pre><code>def _tsp_rec(...):\n # Verbatim copy of original tsp_rec() function\n\ndef tsp_rec(breweries: List[Brewery], graph_of_distances):\n path = []\n return _tsp_rec(breweries, 0, 0, path, graph_of_distances)\n</code></pre>\n\n<p>Also note: <code>[Brewery]</code> was not the correct type-hint; <code>List[Brewery]</code> is.</p>\n\n<hr>\n\n<h1>Improvements</h1>\n\n<h2>Locations</h2>\n\n<p>A location is a nice data type to start with. It should contain immutable data; if you want a different location, you create a different location object.</p>\n\n<pre><code>from dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Location:\n latitude: float\n longitude: float\n</code></pre>\n\n<p>Pretty straight forward object, but we can make it prettier with some extra class members:</p>\n\n<pre><code> @staticmethod\n def deg_min_sec(degrees: float, positive: str, negative: str) -&gt; str:\n suffix = positive if degrees &gt;= 0 else negative\n degrees, minutes = divmod(abs(degrees), 1)\n minutes, seconds = divmod(minutes * 60, 1)\n return f\"{degrees:.0f}\\u00B0{minutes:.0f}\\u2032{seconds*60:.3f}\\u2033 {suffix}\"\n\n def __str__(self):\n return self.deg_min_sec(self.latitude, \"N\", \"S\") + \", \" + self.deg_min_sec(self.longitude, \"E\", \"W\")\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; print(Location(51.74250300, 19.43295600))\n51°44′33.011″ N, 19°25′58.642″ E\n</code></pre>\n\n<p>Now that we have <code>Location</code> objects, we can compute the distance between them. We could write a <code>haversine(loc1, loc2)</code> function, but normally to figure out distances, we take the end point and subtract the start point, so why not define a subtraction operator for <code>Location</code> objects, which returns the distance?</p>\n\n<pre><code>class Location:\n\n # ... other members ...\n\n def __sub__(self, other: Location) -&gt; float:\n \"\"\"\n Return the distance between two locations\n \"\"\"\n\n lon1, lat1, lon2, lat2 = map(radians, [self.longitude, self.latitude, other.longitude, other.latitude])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * asin(sqrt(a))\n r = 6371\n return c * r\n</code></pre>\n\n<h2>Breweries</h2>\n\n<p>Like a <code>Location</code>, a <code>Brewery</code> should be immutable data, describing the identity, the location, and the types of brews it produces: </p>\n\n<pre><code>from typing import Set\n\n@dataclass(frozen=True)\nclass Brewery:\n brewery_id: int\n name: str\n location: Location\n brews: Set[str]\n\n def __str__(self):\n return f\"{self.name} ({self.location})\"\n\n def __hash__(self):\n return self.brewery_id\n</code></pre>\n\n<p>Note: I'm using a <code>set</code> for the types of brews a brewery produces. Since you want the most unique beer types from the tour, it is useful to collect the brews on the tour into a <code>set</code>, which naturally and efficiently eliminates duplicates. Starting with a <code>set</code> in each brewery makes this even easier.</p>\n\n<p>Also note: I'm using the <code>brewery_id</code> as a hash value. Since the data is immutable (<code>frozen=True</code>), it can be used as key in dictionaries. But hashing all the data together to generate a hash is overkill, when the <code>brewery_id</code> is already a unique integer.</p>\n\n<p>To create your list of breweries, I used your original data (with a comma added after <code>'Winterfestival'</code> to make it into a tuple like the rest of the data)</p>\n\n<pre><code>breweries = ([15, 'Aktienbrauerei Kaufbeuren', 10.616100311279297000, 47.878101348876950000],\n [26, 'Allguer Brauhaus AG Kempten', 10.569399833679200000, 47.748699188232420000],\n ...)\n\nbeers = ([('St. Martin Doppelbock',), ('Jubiläums German Pils',)],\n [('Cambonator Doppelbock',), ('Winterfestival',), ('BayrischHell',)],\n ...)\n</code></pre>\n\n<p>And this code:</p>\n\n<pre><code>breweries = [Brewery(id_, name, Location(latitude, longitude), set(brew for brew, in brews))\n for (id_, name, longitude, latitude), brews in zip(breweries, beers)]\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; breweries[0]\nBrewery(brewery_id=15, name='Aktienbrauerei Kaufbeuren', location=Location(latitude=47.87810134887695, longitude=10.616100311279297), brews={'St. Martin Doppelbock', 'Jubiläums German Pils'})\n</code></pre>\n\n<h2>Main</h2>\n\n<p>To drive the program, I used this code:</p>\n\n<pre><code>if __name__ == '__main__':\n breweries = (... omitted ...)\n beers = (... omitted ...)\n\n breweries = [Brewery(id_, name, Location(latitude, longitude), set(brew for brew, in brews))\n for (id_, name, longitude, latitude), brews in zip(breweries, beers)]\n\n path, brews, distance = travelling_brewmaster(breweries, Location(51.74250300, 19.43295600), 1750)\n\n print(\"Path: \", len(path), \"breweries\")\n for location in path:\n print(\" \", location)\n print(\"Distance:\", distance)\n print(\"# brews: \", brews)\n</code></pre>\n\n<p>Notice how I am passing the home location and the maximum travel distance as arguments to <code>travelling_brewmaster()</code>, instead of having these hard-coded in the program.</p>\n\n<h2>Travelling Brew Master</h2>\n\n<p>Let's begin writing our <code>travelling_brewmaster</code> function:</p>\n\n<pre><code>def travelling_brewmaster(breweries: List[Brewery], home: Location,\n max_distance: float) -&gt; Tuple[List[Brewery], int, float]:\n\n def track_best(path: List[Brewery], brews: Set[str], distance:float) -&gt; None:\n nonlocal best_path, best_brews, best_distance\n\n num_brews = len(brews)\n if num_brews &gt; best_brews or num_brews == best_brews and distance &lt; best_distance:\n best_path = path\n best_brews = num_brews\n best_distance = distance\n\n best_path = []\n best_brews = 0\n best_distance = inf\n\n # ... more code here ...\n\n return best_path, best_brews, best_distance\n</code></pre>\n\n<p>We can immediately see several of the points raised above taking shape. First, <code>travelling_brewmaster(...)</code> takes in only the list of breweries, a home location, and a maximum distance to travel. No extra initial values the caller needs to supply.</p>\n\n<p>Second, it will be returning the <code>best_path</code>, <code>best_distance</code>, and <code>best_brews</code>, so the function should not be affecting any global state. How does it achieve that? It declares those as local variables, and then uses a <code>track_best()</code> inner function with <code>nonlocal</code> variable references to update those variables as better paths are found.</p>\n\n<h3>A Bridge Too Far</h3>\n\n<p>Again, your <code>get_breweries_within_1000</code> function was oddly specific; but it was doing the right thing. Any brewery beyond <code>max_distance/2</code> from the home location cannot be visited and returned from within the distance limitation. We just need to shorten it, and make it more general.</p>\n\n<p>First, we want the distances from home to every brewery. We'll need this more than once, so let's store it:</p>\n\n<pre><code> distance_to_home = { brewery: brewery.location - home for brewery in breweries }\n</code></pre>\n\n<p>Since I've added a <code>__hash__</code> method to the immutable <code>Brewery</code> class, the breweries make perfect dictionary keys; we don't have to look up distances by indices. This allows us to ... </p>\n\n<pre><code> breweries = [brewery for brewery in breweries if distance_to_home[brewery] * 2 &lt;= max_distance]\n</code></pre>\n\n<p>... remove any brewery which is clearly too far away to visit from <code>breweries</code>, which can/will change each brewery's index number. If we don't find any breweries within that limit, there is no solution.</p>\n\n<pre><code> if len(breweries) == 0:\n raise ValueError(\"No solution\")\n</code></pre>\n\n<p>Once we have our list of candidate breweries, we can compute the distance between any brewery pair, as a dictionary of dictionaries:</p>\n\n<pre><code> distances = { brewery1: {brewery2: brewery1.location - brewery2.location for brewery2 in breweries}\n for brewery1 in breweries }\n</code></pre>\n\n<h3>Halving Your Work Load</h3>\n\n<p>Your travelling brewmaster exhaustively travels each brewery path combination. This means your brewmaster will travel both:</p>\n\n<pre><code>home -&gt; brewery #1 -&gt; brewery #7 -&gt; brewery #4 -&gt; brewery #3 -&gt; home\n</code></pre>\n\n<p>and</p>\n\n<pre><code>home -&gt; brewery #3 -&gt; brewery #4 -&gt; brewery #7 -&gt; brewery #1 -&gt; home\n</code></pre>\n\n<p>but conclude that both routes result in the same number of brews, and the second path is the same length as the first. Clearly, this is a waste of time. If you can avoid testing the reverse routes, you can eliminate half of the work and speed the search up be a factor of two.</p>\n\n<p>How can we ensure we don't look at the reverse loops? One way is to pick pairs of breweries for the first and last brewery to visit, without selecting the reverse pair. If we choose brewery <code>i</code> (0 &lt; i &lt; n) for the first brewery, then choosing brewery <code>j</code>, where <code>j &gt; i</code>, is sufficient to ensure no reverse pairs are chosen.</p>\n\n<pre><code> for i, last in enumerate(breweries):\n\n # ... more code here ...\n\n for j, first in enumerate(breweries[i+1:], i+1)\n\n # ... more code here ...\n</code></pre>\n\n<p>I said we don't need the index numbers above, but I'm looping over the breweries and keeping track of the index numbers. Why? So we can simply determine what the \"rest\" of the breweries are:</p>\n\n<pre><code> rest = breweries[:i] + breweries[i+1:j] + breweries[j+1:]\n</code></pre>\n\n<p>These are the candidates for visiting between the <code>first</code> and the <code>last</code>.</p>\n\n<h3>Searching</h3>\n\n<p>A simplistic recursive inner search helper might look like this:</p>\n\n<pre><code> # Recursive helper\n def helper(path, distance, beers, breweries):\n\n last = path[0]\n prev = path[-1]\n\n for i, brewery in enumerate(breweries):\n distance2 = distance + distances[prev][brewery]\n loop_distance = distance2 + distances[last][brewery]\n\n if loop_distance &lt;= max_distance:\n brews = beers | brewery.brews\n path2 = path + [brewery]\n\n track_best(path2, brews, loop_distance)\n\n rest = breweries[:i] + breweries[i+1:]\n if rest:\n helper(path2, distance2, brews, rest)\n</code></pre>\n\n<p>Since it is an inner function, like <code>track_best</code>, it has access to the outer function variables, like the <code>distances</code> dictionary and <code>max_distance</code>.</p>\n\n<p>It could be driven by the last/first pair loop, above:</p>\n\n<pre><code> for i, last in enumerate(breweries):\n\n path = [last]\n distance = distance_to_home[last]\n track_best(path, last.brews, distance * 2)\n\n for j, first in enumerate(breweries[i+1:], i+1):\n path2 = path + [first]\n distance2 = distance + distance_to_home[first]\n loop_distance = distance2 + distances[last][first]\n\n if loop_distance &lt;= max_distance:\n\n brews = first.brews | last.brews\n track_best(path2, brews, loop_distance)\n rest = breweries[:i] + breweries[i+1:j] + breweries[j+1:]\n\n helper(path2, distance2, brews, rest)\n\n\n best_path.append(best_path.pop(0))\n return best_path, best_brews, best_distance\n</code></pre>\n\n<p>For convenience, we've added the <code>last</code> brewery as the first element of the <code>path</code> / <code>best_path</code> list, so when we return our best path, we need to move it back to the end of the list to compensate.</p>\n\n<p>Unfortunately, this is very slow. We need to add some optimizations</p>\n\n<h3>Optimization</h3>\n\n<p>Every time we add a <code>brewery</code> to the <code>path</code>, the path distance gets longer. Travel to any remaining brewery from the most recently added brewery and back to the <code>last</code> brewery must not exceed <code>max_distance</code>. So the <code>rest</code> of the breweries can be filtered to exclude any candidate which cannot be reached within the <code>max_distance</code> constraint.</p>\n\n<pre><code> rest = [candidate for candidate in rest\n if distance2 + distances[first][candidate] + distances[last][candidate] &lt;= max_distance]\n</code></pre>\n\n<p>We can also filter out any candidate which doesn't add any new brews to our mix:</p>\n\n<pre><code> rest = [candidate for candidate in rest\n if not candidate.brews &lt;= brews]\n</code></pre>\n\n<p>And we can do both filter steps at once:</p>\n\n<pre><code> rest = [candidate for candidate in rest\n if distance2 + distances[first][candidate] + distances[last][candidate] &lt;= max_distance\n and not candidate.brews &lt;= brews]\n</code></pre>\n\n<p>A similar filtering must be performed in the <code>helper()</code> method, using the <code>brewery</code> that was just added.</p>\n\n<pre><code> rest = [candidate for candidate in rest\n if distance2 + distances[brewery][candidate] + distances[last][candidate] &lt;= max_distance\n and not candidate.brews &lt;= brews]\n</code></pre>\n\n<h2>Performance Timing</h2>\n\n<p><code>datetime.now()</code> is not the most accurate method to use for timing. <code>time.perf_counter()</code> is far superior. A decorator may be used to easily add (and later remove) time-profiling of a specific function:</p>\n\n<pre><code>from time import perf_counter\n\ndef timed(func):\n def wrapper(*argv, **kwargs):\n start = perf_counter()\n result = func(*argv, **kwargs)\n end = perf_counter()\n print(f\"{func.__name__}: {end-start:.2f}\")\n return result\n return wrapper\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>@timed\ndef travelling_brewmaster(breweries: List[Brewery], home: Location, max_distance: float) -&gt; Tuple[List[Brewery], int, float]:\n ...\n</code></pre>\n\n<h1>Reworked Code</h1>\n\n<p>Here is my completely reworked travelling brewmaster code:</p>\n\n<pre><code>from math import radians, cos, sin, asin, sqrt, inf\nfrom time import perf_counter\nfrom dataclasses import dataclass\nfrom typing import List, Set, Tuple\n\ndef timed(func):\n def wrapper(*argv, **kwargs):\n start = perf_counter()\n result = func(*argv, **kwargs)\n end = perf_counter()\n print(f\"{func.__name__}: {end-start:.2f}\")\n return result\n return wrapper\n\n@dataclass(frozen=True)\nclass Location:\n latitude: float\n longitude: float\n\n @staticmethod\n def deg_min_sec(degrees: float, positive: str, negative: str) -&gt; str:\n suffix = positive if degrees &gt;= 0 else negative\n degrees, minutes = divmod(abs(degrees), 1)\n minutes, seconds = divmod(minutes * 60, 1)\n return f\"{degrees:.0f}\\u00B0{minutes:.0f}\\u2032{seconds*60:.3f}\\u2033 {suffix}\"\n\n def __str__(self):\n return self.deg_min_sec(self.latitude, \"N\", \"S\") + \", \" + self.deg_min_sec(self.longitude, \"E\", \"W\")\n\n def __sub__(self, other):\n lon1, lat1, lon2, lat2 = map(radians, [self.longitude, self.latitude, other.longitude, other.latitude])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * asin(sqrt(a))\n r = 6371\n return c * r\n\n@dataclass(frozen=True)\nclass Brewery:\n brewery_id: int\n name: str\n location: Location\n brews: Set[str]\n\n def __str__(self):\n return f\"{self.name} ({self.location})\"\n\n def __hash__(self):\n return self.brewery_id\n\n@timed\ndef travelling_brewmaster(breweries: List[Brewery], home: Location, max_distance: float) -&gt; Tuple[List[Brewery], int, float]:\n\n def track_best(path: List[Brewery], brews: Set[str], distance:float) -&gt; None:\n nonlocal best_path, best_brews, best_distance\n\n num_brews = len(brews)\n if num_brews &gt; best_brews or num_brews == best_brews and distance &lt; best_distance:\n best_brews = num_brews\n best_distance = distance\n best_path = path # + [last]\n\n\n def helper(path, distance, beers, breweries):\n\n last = path[0]\n prev = path[-1]\n\n for i, brewery in enumerate(breweries):\n distance2 = distance + distances[prev][brewery]\n loop_distance = distance2 + distances[last][brewery] \n brews = beers | brewery.brews\n path2 = path + [brewery]\n\n track_best(path2, brews, loop_distance)\n\n rest = breweries[:i] + breweries[i+1:]\n rest = [candidate for candidate in rest\n if distance2 + distances[brewery][candidate] + distances[last][candidate] &lt;= max_distance\n and not candidate.brews &lt;= brews]\n if rest:\n helper(path2, distance2, brews, rest)\n\n distance_to_home = { brewery: brewery.location - home for brewery in breweries }\n breweries = [brewery for brewery in breweries if distance_to_home[brewery] * 2 &lt;= max_distance]\n\n print(f\"{len(breweries)} breweries within {max_distance} driving limit.\")\n if len(breweries) == 0:\n raise ValueError(\"No solution\")\n\n distances = { brewery1: {brewery2: brewery1.location - brewery2.location for brewery2 in breweries}\n for brewery1 in breweries }\n\n best_path = []\n best_brews = 0\n best_distance = inf\n\n for i, last in enumerate(breweries):\n\n path = [last]\n distance = distance_to_home[last]\n track_best(path, last.brews, distance * 2)\n\n for j, first in enumerate(breweries[i+1:], i+1):\n distance2 = distance + distance_to_home[first]\n loop_distance = distance2 + distances[last][first]\n if loop_distance &gt; max_distance or first.brews &lt;= last.brews:\n continue\n\n path2 = path + [first]\n brews = first.brews | last.brews\n track_best(path2, brews, loop_distance)\n rest = breweries[:i] + breweries[i+1:j] + breweries[j+1:]\n rest = [candidate for candidate in rest\n if distance2 + distances[first][candidate] + distances[last][candidate] &lt;= max_distance\n and not candidate.brews &lt;= brews]\n if rest:\n helper(path2, distance2, brews, rest)\n\n best_path.append(best_path.pop(0))\n return best_path, best_brews, best_distance\n\n\nif __name__ == '__main__':\n\n breweries = ( ... omitted for brevity ...)\n beers = (... omitted for brevity ...)\n\n breweries = [Brewery(id_, name, Location(latitude, longitude), set(brew for brew, in brews))\n for (id_, name, longitude, latitude), brews in zip(breweries, beers)]\n\n path, brews, distance = travelling_brewmaster(breweries, Location(51.74250300, 19.43295600), 1600)\n\n print(\"Path: \", len(path), \"breweries\")\n for location in path:\n print(\" \", location)\n print(\"Distance:\", distance)\n print(\"# brews: \", brews)\n</code></pre>\n\n<p>And here is the output, which takes a half-second with a <code>max_distance</code> of 1600:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>40 breweries within 1600 driving limit.\ntravelling_brewmaster: 0.49\nPath: 10 breweries\n Brewery Budweiser Budvar (48°58′26.039″ N, 14°28′30.001″ E)\n Brauerei Grieskirchen AG (48°14′6.359″ N, 13°49′45.119″ E)\n Brauerei Aying Franz Inselkammer KG (47°58′14.160″ N, 11°46′50.880″ E)\n Hacker-Pschorr Bru (48°8′20.757″ N, 11°34′48.721″ E)\n Bayerische Staatsbrauerei Weihenstephan (48°23′42.716″ N, 11°43′43.679″ E)\n Heller Bru Trum (49°53′31.194″ N, 10°53′7.079″ E)\n Brauerei Fssla (49°53′39.118″ N, 10°53′7.800″ E)\n Brauerei Spezial (49°53′39.118″ N, 10°53′7.800″ E)\n Bamberger Mahrs-Bru (49°53′24.355″ N, 10°54′24.120″ E)\n Brauerei Gbr. Maisel KG (49°56′51.722″ N, 11°33′57.239″ E)\nDistance: 1585.2867749820152\n# brews: 36\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T11:43:59.423", "Id": "476914", "Score": "0", "body": "Wow... Thanks for these tips. I will try to improve my code and update it in a original post!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T19:45:20.633", "Id": "477241", "Score": "2", "body": "Great answer! The `Brewery` `dataclass` should have an `__eq__` method to compare such that same `self.brewery_id`s return equality, so that two breweries with the [same hash also compare equal](https://docs.python.org/3/reference/datamodel.html#object.__hash__). But that is not required by the hash implementation; it only requires that objects which compare equal have the same hash, which they do in your code (breweries are only equal to themselves, which makes sense)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T20:53:52.550", "Id": "477245", "Score": "1", "body": "You were very generous with your efforts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T21:33:54.003", "Id": "477249", "Score": "2", "body": "@AlexPovel [`dataclass`](https://docs.python.org/3/library/dataclasses.html) defaults are `(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)`, so by default will automatically define the `__eq__` method, so two distinct objects with the same values will compare as equal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T10:53:21.477", "Id": "477273", "Score": "0", "body": "@AJNeufeld Oh very nice, thank you for clarifying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T18:18:03.147", "Id": "477297", "Score": "0", "body": "@AJNeufeld Thank you! Much respect to you for helping me out! Love you <3 I will try to write better code in the future" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T22:59:56.267", "Id": "242976", "ParentId": "242855", "Score": "10" } } ]
{ "AcceptedAnswerId": "242976", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:43:21.587", "Id": "242855", "Score": "5", "Tags": [ "python", "python-3.x", "recursion" ], "Title": "Traveling salesman to find beer types from breweries" }
242855
<p>I've made simple app that is able to take screenshot each -t seconds and OCR it to -o file. It's also able to take -path and OCR all images to -o file.</p> <p>It works pretty well thanks to tesseract ocr. Unfortunately my code seems much more complicated than it really is. Can you tell me what I'm doing wrong? I enjoy programming, but reading my own code is a nightmare. Should I split it somehow into separate files? How can I improve as a programmer?</p> <pre><code> from PIL import ImageGrab, Image from datetime import datetime from time import sleep import argparse import os from sys import exit from pyautogui import position import cv2 import numpy as np import pytesseract class screenshoter: a,b,c,d = 0, 0, 0, 0 path = "" last_image_sum = 0 output_file = "" ocr_path = "" lang = "" def __init__(self, output_file, ocr_path, path, lang='pol', a=0, b=0, c=0, d=0 ): if c == 0 or d == 0: #screenshot mode input("Set mouse cursor on upper left corner and press enter") self.a, self.b = position() input("OK. Now set mouse cursor on botton right corner and press enter") self.c, self.d = position() else: self.a = a self.b = b self.c = c self.d = d self.output_file=output_file self.ocr_path=ocr_path self.path=path self.lang=lang def _get(self): filename=str(datetime.now().strftime("%d_%m_%H_%M_%S")) im = ImageGrab.grab(bbox=(self.a,self.b,self.c,self.d)) file_with_path = self.path + filename + ".png" im.save(file_with_path) return file_with_path def read(self): with open(self.output_file, "a",encoding='utf8') as f: filename=str(datetime.now().strftime("%d_%m_%H_%M_%S"))+'tmp.png' screenshot = self._get() image = cv2.imread(screenshot) if np.sum(image) != self.last_image_sum: self.last_image_sum = np.sum(image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] cv2.imwrite(filename, gray) pytesseract.pytesseract.tesseract_cmd = self.ocr_path text = pytesseract.image_to_string(Image.open(filename), lang=self.lang) #this line removesc screenshots, uncomment if you only need text (if ocr fails you will regred) #os.remove(screenshot) #this line removes files ocr is working on, grayscale and cropped os.remove(filename) f.write(text) print ("Text saved") else: print ("Skipping, image repeated") def read_files(self): #read files from dir files = [f for f in os.listdir(self.path) if os.path.isfile(os.path.join(self.path, f))] with open(self.output_file, "a", encoding='utf8') as f: for image in files: image = cv2.imread(self.path+image) image = image[self.b:self.d, self.a:self.c] filename=str(datetime.now().strftime("%d_%m_%H_%M_%S"))+'tmp.png' if np.sum(image) != self.last_image_sum: self.last_image_sum = np.sum(image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] cv2.imwrite(filename, gray) pytesseract.pytesseract.tesseract_cmd = self.ocr_path text = pytesseract.image_to_string(Image.open(filename), lang=self.lang) f.write(text) #this line removes files ocr is working on, grayscale and cropped os.remove(filename) print ("Text saved") else: print ("Skipping, image repeated") if __name__ == "__main__": #deal with args ap = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, epilog='''\n This software has been made to automate taking screenshot and OCRing to text file. It is using Tesseract OCR v5.0.0 Default is screenshot mode with 30s interval. To run in files use -m 1 and -c (corners). ''') ap.add_argument('-m', '--mode', choices=[0, 1], default=0, type=int, help="0 for screenshot, 1 for files. Default is screenshot mode.") ap.add_argument('-p', '--path', help="files path, default is .\\images\\") ap.add_argument('-c', '--corners', help="Img corners required with files mode eg. -c '0 0 1920 1080' ") ap.add_argument('-t', '--time', type=int, help="Screenshot interval, default is 30s") ap.add_argument('-o', '--output', help="output file, default is .\\text.txt") ap.add_argument('-l', '--lang', help="language, for codes check tesseract docs, default is polish") ap.add_argument('-tp', '--tensorpath', help="path to tesseract.exe, default is C:\\Program Files\\Tesseract-OCR\\tesseract.exe") args = vars(ap.parse_args()) #default settings output_file="text.txt" path='.\\images\\' ocr_path="C:\\Program Files\\Tesseract-OCR\\tesseract.exe" interval = 30 lang = 'pol' a,b,c,d=0,0,0,0 ocr = args['tensorpath'] pth = args['path'] outp = args['output'] intrv = args["time"] l = args['lang'] if ocr != None: ocr_path = ocr if pth != None: path = pth if outp != None: output_file = outp if intrv != None: interval = intrv if l != None: lang = l #run app def run(mode, path, ocr_path, output_file, a,b,c,d, lang): if mode: app = screenshoter(path=path, ocr_path=ocr_path, output_file=output_file) while True: app.read() sleep(interval) else: try: corners = args["corners"] print (corners) a,b,c,d = [int(i) for i in corners.split(" ")] if c == 0 or d == 0: Exception("-c is required for file mode") else: app = screenshoter(a=a, b=b, c=c, d=d, path=path, ocr_path=ocr_path, output_file=output_file) app.read_files() exit(0) except Exception as e: print (e) print ("-c argument is required when parsing from files! eg. -c '0 0 1920 1080'") exit(0) #mode = True if args['mode'] == None else False mode = not args['mode'] run(mode, path, ocr_path, output_file, a,b,c,d, lang) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:37:57.067", "Id": "476743", "Score": "1", "body": "I think the first thing you're doing wrong is to think about screenshots.\n\nIs this about OCR from any graphic image, or not?" } ]
[ { "body": "<h2>Standard case</h2>\n\n<p>Class names like <code>class screenshoter</code> should be capitalized, i.e. <code>class ScreenShoter</code>. The standard Python code style (which includes recommendations such as naming conventions) is documented in the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 - Style Guide for Python Code</a>.</p>\n\n<h2>Static variables</h2>\n\n<p>These:</p>\n\n<pre><code>a,b,c,d = 0, 0, 0, 0\npath = \"\"\nlast_image_sum = 0\noutput_file = \"\"\nocr_path = \"\"\nlang = \"\"\n</code></pre>\n\n<p>do not do what you think they do. They're effectively statics, and in this case I think they can all be deleted. Whereas you have some defaults here that have not been picked up in your constructor function signature, it doesn't make sense for them to be optional arguments, so your constructor is fine.</p>\n\n<h2>Coordinate names</h2>\n\n<p>Consider renaming <code>a,b,c,d</code> to <code>x0,x1,y0,y1</code>. It will be easier to understand for other programmers.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def __init__(self, output_file, ocr_path, path, lang='pol', a=0, b=0, c=0, d=0 ):\n</code></pre>\n\n<p>can be, at a guess,</p>\n\n<pre><code>def __init__(self, output_file: str, ocr_path: str, path: str, lang: str='pol', a: float=0, b: float=0, c: float=0, d: float=0):\n</code></pre>\n\n<p>This helps in a number of ways, including making it much clearer for callers of your constructor.</p>\n\n<h2>Redundant <code>str</code></h2>\n\n<p>Do not call <code>str</code> on this:</p>\n\n<pre><code>str(datetime.now().strftime(\"%d_%m_%H_%M_%S\"))\n</code></pre>\n\n<p>since it's already a string.</p>\n\n<h2>pathlib</h2>\n\n<pre><code>file_with_path = self.path + filename + \".png\"\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>from pathlib import Path\n...\nself.path = Path(path)\n...\nfile_with_path = (self.path / filename).with_suffix('.png')\n</code></pre>\n\n<h2>Inline date formatting</h2>\n\n<pre><code>str(datetime.now().strftime(\"%d_%m_%H_%M_%S\"))+'tmp.png'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'{datetime.now():%d_%m_%H_%M_%S}_tmp.png'\n</code></pre>\n\n<h2>Caching</h2>\n\n<p>Cache <code>np.sum(image)</code> in a local variable since you use it twice.</p>\n\n<h2>Main guard</h2>\n\n<p><code>def run</code> should be moved away from your main guard. It's already in \"global scope\" but would not be available to unit tests. The other code after your main guard and before <code>run</code> should be moved into its own function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T16:04:58.963", "Id": "242861", "ParentId": "242856", "Score": "13" } }, { "body": "<p>The one thing that is immediately apparent to me (before scrolling the code window) is the naming of some variables: a, b, c, d. Why not use more <strong>meaningful names</strong> ? You're not being billed by length of variable name. If they are coordinates just call them topleft, topright etc.</p>\n\n<p>Ditto with variables names like:</p>\n\n<pre><code>pth = args['path']\noutp = args['output']\nintrv = args[\"time\"]\n</code></pre>\n\n<p>Names should be more explicit and not abbreviated needlessly.</p>\n\n<hr>\n\n<p>I would put all <strong>constants</strong> at the top of the code.</p>\n\n<p>This should be a constant too: <code>strftime(\"%d_%m_%H_%M_%S\")</code>.\nDefine the desired date format only once.</p>\n\n<hr>\n\n<p>You are assigning some variables in your code twice eg:</p>\n\n<pre><code>a,b,c,d=0,0,0,0\n</code></pre>\n\n<hr>\n\n<p>It is good that you are using <code>argparse</code> but you can do more.</p>\n\n<p>First of all, some variable assignments are unnecessary:</p>\n\n<pre><code>if intrv != None:\n interval = intrv\n</code></pre>\n\n<p>You can provide a <strong>default value</strong> for missing arguments. Just use the <code>default</code> option in <code>add_argument</code>. Don't use two variables when one is sufficient.</p>\n\n<p>Since you are expecting 4 numbers for the <code>corners</code> argument here is how to integrate the requirement in <code>argparse</code>: use the <a href=\"https://docs.python.org/3/library/argparse.html#nargs\" rel=\"noreferrer\"><code>nargs</code></a> option.</p>\n\n<pre><code>import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-c', '--corners', dest=\"corners\",\ntype=int, required=True, nargs=4,\nhelp=\"Img corners required with files mode eg. -c '0 0 1920 1080' \")\n\nargs = parser.parse_args()\n\n# show the values\nprint(f\"corners: {args.corners}\")\n</code></pre>\n\n<p>With this you know that only integers will be accepted. But they could be too large. So you can add one more option like: <code>choices=range(0,1921)</code>. With this you will restrict the range of allowed numbers to 0-1920 (as an example). The downside is that Python will output all possibilities if at least one argument does not fulfill the condition. The error message will fill up your screen and this is not pretty.</p>\n\n<p>To avoid this downside, we can write a custom function to validate the argument and override the error message:</p>\n\n<pre><code>import argparse\n\ndef check_corners(corner):\n if not corner.isdigit():\n raise argparse.ArgumentTypeError(\"Corner must be a number\")\n if int(corner) not in range(0,1921):\n raise argparse.ArgumentTypeError(\"Corner must be a number in the range [0-1920]\")\n return corner\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-c', '--corners', dest=\"corners\",\ntype=check_corners, required=True, nargs=4,\nhelp=\"Img corners required with files mode eg. -c '0 0 1920 1080' \")\n\nargs = parser.parse_args()\n\n# show the values\nprint(f\"corners: {args.corners}\")\n</code></pre>\n\n<p>There is one caveat though. By default, Python assumes arguments are of type <code>str</code> and that's what happens in this function. So before using <code>range</code> we have to make sure that <code>corner</code> is a number and cast it to <code>int</code>. Otherwise <code>in range</code> will not work.<br />\nOr you could use a regex.</p>\n\n<p>Test:</p>\n\n<pre><code>python3 corners.py -c 0 0 0 1921\nusage: corners.py [-h] -c CORNERS CORNERS CORNERS CORNERS\ncorners.py: error: argument -c/--corners: Corner must be a number in the range [0-1920]\n</code></pre>\n\n<p>With this, you can remove a few lines of your code or at least simplify logic. The <code>argparse</code> module allows you to collect arguments and validate them at the same time. Take full advantage of the features available.</p>\n\n<hr>\n\n<blockquote>\n <p>Should I split it somehow into separate files?</p>\n</blockquote>\n\n<p>Ultimately, keeping the class in a standalone file importable as a packagge would be a good idea.</p>\n\n<hr>\n\n<p>Use the <code>logging</code> module.</p>\n\n<p>You have a few prints here and there. It would be a good idea to use the <code>logging</code> module instead eg <code>logger.debug(\"Text saved\")</code>. Then you can show the comments on screen, record them to a file or <a href=\"https://docs.python.org/3/howto/logging-cookbook.html#logging-to-multiple-destinations\" rel=\"noreferrer\">both</a>. You can also reduce verbosity any time you want by adjusting the debug level. If you want your code to become silent you have to comment out all those prints across your module.</p>\n\n<p>Since the code can be automated and is probably unattended to some extent, it is important to keep a log of activity, not just on screen but on file too for later review. Plus, <strong>exceptions</strong> should be handled and logged too when they occur.</p>\n\n<hr>\n\n<p><strong>Comments</strong>: some functions have no comments at all. Some docstring would be nice. Perhaps add some value samples.</p>\n\n<p>Some functions could be renamed and documented, for example <code>_get</code>. If I'm guessing right it could be <code>take_snapshot</code> or something like that. <code>get</code> is so generic that it is meaningless. The point is that the purpose of each function should be immediately apparent and that's why comments are useful, also for you (in 6 months you'll have to reanalyze your code).</p>\n\n<hr>\n\n<p>If you work with <strong>temp files</strong> you could use the <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"noreferrer\">tempfile</a> module or write them to /tmp. Then you'll be less concerned with cleanup.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T17:09:19.373", "Id": "242865", "ParentId": "242856", "Score": "10" } }, { "body": "<p>I echo Reinderien's and Anonymous's comments re your <code>a, b, c, d</code>. I suggest renaming your <code>a</code> and <code>c</code> to <code>left</code> and <code>right</code>, and your <code>b</code> and <code>d</code> to <code>top</code> and <code>bottom</code>. (Two-word names such as <code>topleft</code> are not appropriate because each of these variables holds just one coordinate, not two.)</p>\n\n<p>Then you needn't mandate which corner the user starts from. Let them start from any of the four corners. Then, after you have read x- and y-coordinates of two points given by the user, ensure they're the correct way round:</p>\n\n<pre><code> if top&lt;bottom:\n top, bottom = bottom, top\n</code></pre>\n\n<p>(and likewise for left and right). It's better to be generous than needlessly restrictive with ways you enable the user to do things. By contrast, your code needs to be strict about how it does things when that matters, e.g. correctly identifying which y-coor was the top and which one was the bottom.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T15:43:09.827", "Id": "242904", "ParentId": "242856", "Score": "3" } } ]
{ "AcceptedAnswerId": "242861", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:47:29.430", "Id": "242856", "Score": "11", "Tags": [ "python", "python-3.x" ], "Title": "Screenshot-to-OCR utility" }
242856
<p>I want to save NUnit local tests in a mysql database hosted in Amazon RDS, and</p> <p>I'm wrapping up everything in a transaction like so :</p> <pre><code>using (var context = new StDbContext()) { context.Database.Log = Console.Write; if (!context.Database.Connection.State.HasFlag(ConnectionState.Open)) { context.Database.Connection.OpenAsync(); } using (var transaction = context.Database.BeginTransaction()) { try { var unit_of_work = new UnitOfWork(context); unit_of_work.Sessions.AddModelSession(Model, unit_of_work); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); TestBaseCore.mNLogLoggerService.Error(ex.Message); } } } </code></pre> <p>Is there a better way of optimizing this code, in order to be sure that the connection or the current transaction is still open until all the data it is saved to the database? because when trying to save using this code to a local database everything works perfectly, but when saving to a database hosted by Amazon RDS, the code will crash with no exception.The only difference is the connection string</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T15:21:35.930", "Id": "476642", "Score": "1", "body": "\"when saving to a database hosted by Amazon RDS, the code will crash with no exception\" This sounds like broken code, which is off topic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T16:46:17.693", "Id": "476650", "Score": "0", "body": "I'm more interested on a review for it. and possible code optimization. the broke code part I will handle. Maybe there is a better way of writing transactions and I'm missing something" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T12:03:57.593", "Id": "476714", "Score": "1", "body": "make your code full async or sync `BeginTransactionAsync` and `SaveChangesAsync` as you've opened an async connection `OpenAsync();`. Also, note that the sent data will be validated by SQL engine and not `EF`, so you should be specific in exceptions for better handling, you will need to include `EF` exceptions like `DbUpdateException`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:30:02.567", "Id": "476767", "Score": "0", "body": "Why don't you await `OpenAsync`? Looks like only on a local db opening the connection is fast enough not to be awaited." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T14:58:55.857", "Id": "242859", "Score": "1", "Tags": [ "c#", "database", "entity-framework" ], "Title": "Entity Framework optimization when using transactions" }
242859
<p>This is a part of simple sfml C++ game, but I think neither the library nor the language is that much crucial here. I am mainly worried about the design.</p> <p>I have a class template <code>ResourceHolder&lt;Key, Resource&gt;</code> to hold one type of Resource such as texture or sound, inside a map. A key is usually an enum but can be anything.</p> <p>I also have a class <code>ResourceManager</code> that keeps all available <code>ResourceHolder</code>s in one place.</p> <p>A simplified class diagram:</p> <p><a href="https://i.stack.imgur.com/GRiIS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GRiIS.png" alt="enter image description here"></a> </p> <p>I am providing the full code for those classes:</p> <p><code>ResourceHolder.h</code>:</p> <pre><code>template &lt;typename Key, typename Resource&gt; class ResourceHolder { public: explicit ResourceHolder(std::string resourcesDir = "../resources/") : resourcesDir{std::move(resourcesDir)} {} template &lt;typename... Args&gt; void insert(const Key&amp; key, Args&amp;&amp;... args) { auto resPtr = std::make_unique&lt;Resource&gt;(); if (!resPtr-&gt;loadFromFile(resourcesDir + std::forward&lt;Args&gt;(args)...)) { msgErrorLoading(std::forward&lt;Args&gt;(args)...); ///* todo: should I e.g. "throw ErrorLoadingResource" here? */ } resources.emplace(key, std::move(resPtr)); } Resource&amp; get(const Key&amp; key) const { if (auto resource = resources.find(key); resource != std::end(resources)) { return *(resource-&gt;second); } throw std::invalid_argument{"No such resource id."}; } void erase(const Key&amp; key) noexcept { if (auto found = resources.find(key); found != std::end(resources)) { resources.erase(key); } } void eraseAll() { resources.clear(); } private: std::string resourcesDir; std::unordered_map&lt;Key, std::unique_ptr&lt;Resource&gt;&gt; resources; public: template &lt;typename... Args&gt; ResourceHolder&amp; operator+=(const ResourceInserter&lt;Key, Args...&gt;&amp; inserter) { insert(std::move(inserter.key), std::move(std::get&lt;Args&gt;(inserter.args)...)); return *this; } inline const Resource&amp; operator[](const Key&amp; key) const { return get(std::move(key)); } inline Resource&amp; operator[](const Key&amp; key) { return get(std::move(key)); } auto&amp; getResources() const { return resources; } auto&amp; getResourcesDir() const { return resourcesDir; } void setResourcesDir(std::string newPath) { resourcesDir = std::move(newPath); } private: template &lt;typename... Args&gt; void msgErrorLoading(const Args... args) { std::cerr &lt;&lt; "Failed loading resource: { Type: \"" &lt;&lt; typeid(Resource).name()&lt;&lt; "\", File name: \""; (std::cerr &lt;&lt; ... &lt;&lt; args) &lt;&lt; "\" }" &lt;&lt; std::endl; } }; </code></pre> <p><code>ResourceManager.h</code>:</p> <pre><code>class ResourceManager { public: ResourceManager(); private: ResourceHolder&lt;res::Texture, sf::Texture&gt; textures; ResourceHolder&lt;res::Sound, sf::SoundBuffer&gt; sounds{"../resources/sound/"}; void loadTextures(); void loadSounds(); public: auto&amp; getTextures() { return textures; } auto&amp; getSounds() { return sounds; } }; </code></pre> <p><code>ResourceManager.cpp</code>:</p> <pre><code>ResourceManager::ResourceManager() { loadTextures(); loadSounds(); } void ResourceManager::loadTextures() { textures.insert(res::Texture::Wizard, "wizard.png"); textures.insert(res::Texture::Gray, "gray.png"); textures.insert(res::Texture::Orange, "orange.png"); } void ResourceManager::loadSounds() { sounds += ResourceInserter(res::Sound::Bullet, "boing.wav"); sounds += ResourceInserter(res::Sound::Bing, "boing_long.wav"); sounds += ResourceInserter(res::Sound::Poof, "poof.wav"); } </code></pre> <p><code>ResourceInserter.h</code>:</p> <pre><code>/** Operator += must take one argument * This is a proxy class for operator+= * You can use operator+= instead of insert() as an alternative insertion method */ template &lt;typename Key, typename... Args&gt; class ResourceInserter { public: explicit ResourceInserter(Key&amp;&amp; key, Args&amp;&amp;... args) : key{std::forward&lt;Key&gt;(key)} , args{std::forward&lt;Args&gt;(args)...} {} Key key; std::tuple&lt;Args...&gt; args; }; template &lt;typename T, typename... Args&gt; ResourceInserter(T&amp;&amp;, Args&amp;&amp;... args) -&gt; ResourceInserter&lt;T, Args...&gt;; </code></pre> <p><code>Resources.h</code></p> <pre><code>namespace res { enum class Texture { Gray, Orange, Wizard }; enum class Sound { Bullet, Poof, Bing }; } </code></pre> <p>Some basic usage (inside parent/caller/owner class):</p> <pre><code>auto wizardTexture = textures.get(res::Texture::Wizard); auto bulletSound = sounds[res::Sound::Bullet]; </code></pre> <p>I am not asking for a deep-throughout review as I imagine it'd take too much off of your time.</p> <hr> <p>I have few questions, answering any of them would be absolutely helpful.</p> <ol> <li>Whatever you think of that looks smelly or problematic, please do let me know.</li> <li>What's wrong with my design from OOP/design patterns point of view? (I am especially worried about the part where I am inserting all the resources inside <code>ResourceManager.cpp</code>)</li> <li>What's wrong with my code from C++ point of view? (I am especially interested in parts where I <em>attempted</em> using move semantics/perfect forwarding e.g. <code>insert</code> method or <code>operator+=</code>)</li> <li>Is there something confusing related to naming identifiers?</li> </ol> <hr> <p>The reason why I am using enums as keys is that it works as a <em>sort of</em> connection interface for both insertion and then retrieval of the resource. If I insert a resource of key <code>Enum_Type::Enum_Item</code>, then I can also retrieve it using the same key.</p> <p>I'd rather not hardcode the insertion process inside <code>ResourceManager.cpp</code>, and preferably keep it in a separate file, but the fact that I am using <code>Enum</code> as a key is kind of an obstacle here for me. Not sure how to fix it.</p> <hr> <p>Thanks a lot!</p>
[]
[ { "body": "<pre><code>template &lt;typename... Args&gt;\nvoid insert(const Key&amp; key, Args&amp;&amp;... args) {\n auto resPtr = std::make_unique&lt;Resource&gt;();\n if (!resPtr-&gt;loadFromFile(resourcesDir + std::forward&lt;Args&gt;(args)...)) {\n msgErrorLoading(std::forward&lt;Args&gt;(args)...);\n ///* todo: should I e.g. \"throw ErrorLoadingResource\" here? */\n }\n resources.emplace(key, std::move(resPtr));\n}\n</code></pre>\n\n<p>The template parameter pack seems a little overcomplicated here. If all the arguments are concatenated into a <code>std::string</code>, it might be better to just take a single string argument and let the user do the concatenation.</p>\n\n<p>It might be nice to have a <code>Resource</code> constructor that takes the file path so we don't need a separate function call.</p>\n\n<hr>\n\n<pre><code>template &lt;typename... Args&gt;\nResourceHolder&amp; operator+=(const ResourceInserter&lt;Key, Args...&gt;&amp; inserter) {\n insert(std::move(inserter.key), std::move(std::get&lt;Args&gt;(inserter.args)...));\n return *this;\n}\n</code></pre>\n\n<p>This also seems a little unnecessary. Mathematical operators are best used for mathematical operations.</p>\n\n<p>In <code>ResourceManager</code> it also looks like the code using <code>+=</code> is longer than the code that calls <code>insert</code> directly (and we have to have that <code>ResourceInserter</code>).</p>\n\n<p>The use of <code>std::move</code> looks fine here.</p>\n\n<hr>\n\n<pre><code>inline const Resource&amp; operator[](const Key&amp; key) const {\n return get(std::move(key));\n}\n</code></pre>\n\n<p>Functions defined in the class body are already inline, so we don't need to specify it.</p>\n\n<p>The argument is a <code>const&amp;</code> so there's no need to <code>std::move</code> it.</p>\n\n<p>Perhaps <code>operator[]</code> is also unnecessary, since we can just call <code>get</code>.</p>\n\n<hr>\n\n<pre><code>explicit ResourceInserter(Key&amp;&amp; key, Args&amp;&amp;... args)\n : key{std::forward&lt;Key&gt;(key)}\n , args{std::forward&lt;Args&gt;(args)...}\n{}\n</code></pre>\n\n<p><code>Key</code> and <code>Args</code> aren't actually template parameters (of the function) here, so we don't need to use <code>std::forward</code>. Since these are \"sink arguments\" (we're storing a copy of them locally), we can take them by value and then move them into place:</p>\n\n<pre><code>explicit ResourceInserter(Key key, Args... args)\n : key{std::move(key)}\n , args{std::move(args)...}\n{}\n</code></pre>\n\n<hr>\n\n<p>It might be better to put the loading of resources somewhere in the game logic, rather than in <code>ResourceManager</code>. (We might want to separate the construction of the <code>ResourceManager</code> from the loading at some point).</p>\n\n<hr>\n\n<p>I don't think that hard-coding the resource IDs (as an <code>enum</code> or a constant variable) is necessarily a problem for a small game.</p>\n\n<p>The alternative would be to load the resource IDs from a data file (i.e. add a json or xml asset list). Then we could change the resources without recompiling (but it's more work to code and maintain).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T06:21:40.617", "Id": "242990", "ParentId": "242864", "Score": "1" } } ]
{ "AcceptedAnswerId": "242990", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T17:06:41.797", "Id": "242864", "Score": "4", "Tags": [ "c++", "object-oriented", "c++11", "design-patterns", "sfml" ], "Title": "Resource management classes in C++ game" }
242864
<p>I'm pretty new to Rust and to it's async/await model, and I'm trying to do something that looks like a specialized Haskell's <code>traverse</code> function. Given a <code>Vec&lt;T&gt;</code> and a function <code>T -&gt; Future&lt;Output = R&gt;</code> I want to get a <code>Future&lt;Output = Vec&lt;R&gt;&gt;</code>.</p> <p>At the moment, I have the following:</p> <pre><code>use futures::{FutureExt, StreamExt}; pub async fn traverse&lt;I, T, R, F, FN&gt;(xs: I, f: FN) -&gt; Vec&lt;R&gt; where I: IntoIterator&lt;Item = T&gt;, F: FutureExt&lt;Output = R&gt;, FN: Fn(T) -&gt; F, { futures::stream::iter(xs) .fold(vec![], |acc, item| { f(item).map(move |app| { let mut a = acc; a.push(app); a }) }) .await } </code></pre> <p>It works as expected, but doesn't feel very idiomatic. Does anybody has suggestion how to improve this function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T21:07:20.907", "Id": "476667", "Score": "0", "body": "I've edited the title, but I don't see any error in the question. That being said, the above `traverse` function is a generalized way to transform a Vec of Future to a Future of Vec. you can get back the expected behaviour by passing the vector of Future as first argument and the second argument must be the identity function `|x| x`" } ]
[ { "body": "<p>I think the best is to simply use <a href=\"https://docs.rs/futures/0.3.5/futures/stream/trait.StreamExt.html#method.then\" rel=\"noreferrer\"><code>then()</code></a> and <a href=\"https://docs.rs/futures/0.3.5/futures/stream/trait.StreamExt.html#method.collect\" rel=\"noreferrer\"><code>collect()</code></a>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use futures::{Future, StreamExt};\n\npub async fn traverse&lt;I, T, F, Fut, O&gt;(xs: I, f: F) -&gt; Vec&lt;O&gt;\nwhere\n I: IntoIterator&lt;Item = T&gt;,\n F: Fn(T) -&gt; Fut,\n Fut: Future&lt;Output = O&gt;,\n{\n futures::stream::iter(xs).then(f).collect().await\n}\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>futures generic should be name <code>Fut</code></li>\n<li>function generic should be name <code>F</code></li>\n<li>I rename <code>R</code> as <code>O</code> but I don't know if it's better but it's my way.</li>\n<li>Doesn't need <code>FutureExt</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T21:07:20.487", "Id": "242873", "ParentId": "242871", "Score": "5" } } ]
{ "AcceptedAnswerId": "242873", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T20:28:00.140", "Id": "242871", "Score": "4", "Tags": [ "rust", "async-await" ], "Title": "Getting a Future from a Vector and a function" }
242871
<p>I have created the following few functions for handling the use of doubly linked lists. </p> <p>list.c: </p> <pre><code>#include "list.h" #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; /* all functions returning a pointer return NULL on failure * all functions returning an integer return != 0 on failure */ //internal static struct node { struct node *previous; size_t len; void *data; uint8_t greedy_data; struct node *next; }; //internal struct node *find_node(LIST *list, uint16_t index); // creates linked list instance (metadata grouping) with one node LIST *create_list(void) { LIST *ret = malloc(sizeof(*ret)); if (!ret) return NULL; ret-&gt;start = malloc(sizeof(*ret-&gt;start)); if (!ret-&gt;start) { free(ret); return NULL; } ret-&gt;node_count = 1; ret-&gt;end = ret-&gt;start; return ret; } //frees all internal memory associate with list void destroy_list(LIST *list) { struct node *tmp = list-&gt;start; for (;;list-&gt;node_count--) { if (tmp-&gt;greedy_data) free(tmp-&gt;data); if (list-&gt;node_count == 1) { free(tmp); break; } tmp = tmp-&gt;next; free(tmp-&gt;previous); } free(list); } /* creates new node, appending it to the end of the list if * index &lt; 0 or index == list-&gt;node_count; returns 1 on * invalid index or malloc() failure */ int add_node(LIST *list, int32_t index) { if (index &gt; list-&gt;node_count || list-&gt;node_count == UINT16_MAX - 1) return 1; struct node *add = malloc(sizeof(*add)); if (!add) return 1; add-&gt;greedy_data = 0; if (index &lt; 0 || index == list-&gt;node_count) { add-&gt;previous = find_node(list, list-&gt;node_count - 1); add-&gt;previous-&gt;next = add; list-&gt;end = add; list-&gt;node_count++; return 0; } add-&gt;next = find_node(list, index); add-&gt;previous = add-&gt;next-&gt;previous; add-&gt;next-&gt;previous = add; add-&gt;previous-&gt;next = add; list-&gt;node_count++; return 0; } /* frees internal memory associated with the node at index, * decrements list-&gt;node_count, and adjusts link pointers */ int rm_node(LIST *list, int32_t index) { if (index &lt; 0) index = list-&gt;node_count - 1; struct node *goner = find_node(list, index); if (!goner) return 1; goner-&gt;previous-&gt;next = goner-&gt;next; goner-&gt;next-&gt;previous = goner-&gt;previous; if (goner-&gt;greedy_data) free(goner-&gt;data); free(goner); list-&gt;node_count--; return 0; } /* associates node-&gt;data at the node in list at index with the data supplied * as well as node-&gt;len with len; a true value of hands_off indicates that API * should be "greedy" with the data, keeping a copy internally so the user * doesn't have to worry about it (the API will free it, provided the user calls * rm_struct node() or destroy_list()) */ int bind_node(LIST *list, uint16_t index, void *data, size_t len, bool hands_off) { struct node *tmp = find_node(list, index); if (!tmp) return 1; tmp-&gt;len = len; if (hands_off) { tmp-&gt;data = malloc(len); if (!tmp-&gt;data) return 1; memcpy(tmp-&gt;data, data, len); tmp-&gt;greedy_data = 1; } else { tmp-&gt;data = data; } return 0; } //a small layer of abstraction returning the data pointer of a node void *access_node(LIST *list, uint16_t index) { struct node *tmp = find_node(list, index); if (!tmp) return NULL; return tmp-&gt;data; } //internal function returning struct node* based on index struct node *find_node(LIST *list, uint16_t index) { if (index &gt;= list-&gt;node_count) return NULL; if (index &lt; list-&gt;node_count / 2) { struct node *ret = list-&gt;start; for (; index &gt; 0; index--) ret = ret-&gt;next; return ret; } else { struct node *ret = list-&gt;end; for (; list-&gt;node_count - 1 - index &gt; 0; index++) ret = ret-&gt;previous; return ret; } } </code></pre> <p>list.h: </p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stddef.h&gt; #include &lt;stdbool.h&gt; typedef struct { struct node *start; struct node *end; uint16_t node_count; } LIST; LIST *create_list (void); void destroy_list (LIST *list); int add_node (LIST *list, int32_t index); int rm_node (LIST *list, int32_t index); int bind_node (LIST *list, uint16_t index, void *data, size_t len, bool hands_off); void *access_node (LIST *list, uint16_t index); </code></pre> <p>Though I obviously welcome suggestions and critiques on performance, style, etc., my main question is about the design of the interface. Do you have any suggestions or ideas on how it could be designed to be more useful, usable, or clear?<br> Disclaimer: I haven't passed it through Valgrind et al yet, so I'm not too positive it's completely bug/mem-leak free.</p>
[]
[ { "body": "<blockquote>\n <p>my main question is about the design of the interface. Do you have any suggestions or ideas on how it could be designed to be more useful, usable, or clear?</p>\n</blockquote>\n\n<p><strong>Drop the <code>struct</code> definition from list.h</strong></p>\n\n<p>Better hide such unneeded details from the user. Consider only the declaration of <code>struct list</code>.</p>\n\n<pre><code>typedef struct list LIST;\n</code></pre>\n\n<p>If the user needs access to a <code>struct</code> member, provide it through helper functions.</p>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p>For functions which do not change the list. See below.</p>\n\n<p><strong>Namespace impact</strong></p>\n\n<p>Consider a more localized naming scheme to make clear what comes from list.h</p>\n\n<pre><code>// example\n// list.h --&gt; dlist.h\n\ntypedef struct dlist_s dlist;\n\nlist *dlist_create(void);\nvoid dlist_destroy(dlist *list);\nint dlist_add_node(dlist *list, int32_t index);\nint dlist_rm_node(dlist *list, int32_t index);\nint dlist_bind_node(dlist *list, uint16_t index, void *data, size_t len, bool hands_off);\nvoid *dlist_access_node(const dlist *list, uint16_t index);\n</code></pre>\n\n<p><strong>Move function descriptions to .h</strong></p>\n\n<p>Consider the .c file is opaque to the user.</p>\n\n<p><strong>Good that .h only includes needed std headers</strong></p>\n\n<p><strong>Questionable index type</strong></p>\n\n<p>Why <code>uint16_t, int32_t index</code> vs. <code>unsigned index</code> or <code>size_t index</code>?</p>\n\n<p><strong>Missing code guard</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/27810115/what-exactly-do-c-include-guards-do\">What exactly do C include guards do?</a></p>\n\n<hr>\n\n<p>Good use of <code>#include \"list.h\"</code> as first include file in list.c</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T04:15:58.240", "Id": "476686", "Score": "0", "body": "Thanks for the suggestions, especially the use of `const` (completely missed that) and moving the struct definition of `list`. BTW, the index is int32_t when `< 0` is needed (see inline comments). As for the `uint16_t` index, the maximum number of nodes is `2^16 - 1` (see list definition). I thought it better to make the size explicit so the compiler could warn about trying to use e.g. index 70000. Is this reasoning sound, or is there a better way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T04:19:31.897", "Id": "476687", "Score": "0", "body": "Oh, and as this is merely a thought exercise, I'm not going to bother with namespace resolution or include guards. The advantages of non-production code :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T12:14:45.450", "Id": "476716", "Score": "0", "body": "@user692992 Re: \" better way? \" with special meaning to `index < 0`, recommend another function like `add_node_end(LIST *list)` and use `size_t index` elsewhere. Plan for success (wide code re-use) and do artificially limit indexing to 16-bit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:40:53.197", "Id": "476733", "Score": "0", "body": "Thanks; that;s a good idea" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:41:23.723", "Id": "476747", "Score": "0", "body": "@user692992 Oops, meant \"... and do _not_ artificially limit indexing to 16-bit.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:44:07.800", "Id": "476759", "Score": "0", "body": "Yeah I figured lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:45:30.837", "Id": "476760", "Score": "0", "body": "And if you don't mind answering another question, would you suggest `inline`ing the `accesss_node()` call?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:36:11.280", "Id": "476768", "Score": "0", "body": "As `access_node()` is meant for user use. to make inline codes needs to un-hide the `struct` def - something that I'd rather avoid.. I'd suspect your overall application will not notice an appreciable difference as `inline` or not`." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T01:32:05.690", "Id": "242882", "ParentId": "242872", "Score": "1" } } ]
{ "AcceptedAnswerId": "242882", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T20:37:51.430", "Id": "242872", "Score": "4", "Tags": [ "c", "linked-list", "api", "library" ], "Title": "Double linked list API design in C" }
242872
<p>I will import given code for my main <code>QMainWindow</code>.(I only add import sys etc. to run it) Is there a more compact way to code this lines. Output is correct for my expectation.</p> <pre><code>from PyQt5.QtWidgets import * import sys class ButtonWidget(QWidget): def __init__(self): super(ButtonWidget, self).__init__() # Function button1 = QRadioButton("Sinus") button2 = QRadioButton("Cosines") # Color button3 = QRadioButton("Red") button4 = QRadioButton("Green") # Line button5 = QRadioButton("Solid") button6 = QRadioButton("Dashed") # Left Group left_group = QGroupBox("Left Group") left_group_layout = QVBoxLayout() left_group_layout.addWidget(button1) left_group_layout.addWidget(button2) left_group.setLayout(left_group_layout) # Middle Group middle_group = QGroupBox("Middle Group") middle_group_layout = QVBoxLayout() middle_group_layout.addWidget(button3) middle_group_layout.addWidget(button4) middle_group.setLayout(middle_group_layout) # Right Group right_group = QGroupBox("Right Group") right_group_layout = QVBoxLayout() right_group_layout.addWidget(button5) right_group_layout.addWidget(button6) right_group.setLayout(right_group_layout) # Main Group main_group = QGroupBox("Main Group") main_group_layout = QHBoxLayout() main_group_layout.addWidget(left_group) main_group_layout.addWidget(middle_group) main_group_layout.addWidget(right_group) main_group.setLayout(main_group_layout) # Widget main_widget = QWidget() main_widget_layout = QVBoxLayout() main_widget.setLayout(main_widget_layout) main_widget_layout.addWidget(main_group) # Layout Set self.setLayout(main_widget_layout) self.show() if __name__ == "__main__": app = QApplication(sys.argv) ui = ButtonWidget() sys.exit(app.exec_()) </code></pre>
[]
[ { "body": "<p>Yes there is a solution. The obvious solution is of course to use loops.\nHere is my try using a composite dictionary. It is functionally equivalent to your code and will save you about a dozen lines but hopefully adds flexibility. This was a quick job, so maybe you can take it further.</p>\n\n<pre><code>from PyQt5.QtWidgets import *\nimport sys\n\n\nclass ButtonWidget(QWidget):\n\n def __init__(self):\n super(ButtonWidget, self).__init__()\n\n groups = {\"Left Group\": (\"Sinus\", \"Cosines\"),\n \"Middle Group\": (\"Red\", \"Green\"),\n \"Right Group\": (\"Solid\", \"Dashed\")\n }\n\n # Main Group\n main_group = QGroupBox(\"Main Group\")\n main_group_layout = QHBoxLayout()\n\n # loop on group names\n for group, buttons in groups.items():\n group_box = QGroupBox(group)\n group_layout = QVBoxLayout()\n for button_text in buttons:\n group_layout.addWidget(QRadioButton(button_text))\n\n group_box.setLayout(group_layout)\n main_group_layout.addWidget(group_box)\n\n main_group.setLayout(main_group_layout)\n\n # Widget\n main_widget = QWidget()\n main_widget_layout = QVBoxLayout()\n main_widget.setLayout(main_widget_layout)\n main_widget_layout.addWidget(main_group)\n # Layout Set\n self.setLayout(main_widget_layout)\n\n self.show()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ui = ButtonWidget()\n sys.exit(app.exec_())\n</code></pre>\n\n<p>NB: you'll probably have to add names to the generated controls (the buttons at least).</p>\n\n<p>PS: personally I use the QT designer to build forms unless I need a highly dynamic layout. Adding controls in code is tedious and less visual.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:36:24.170", "Id": "476741", "Score": "0", "body": "Actually, I'm trying to create engineering calculation GUI for my job. I think, I can create basic one. However I also want to improve myself. I will use numpy etc. What do you suggest for not highly dynamic layout" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T00:35:10.687", "Id": "242880", "ParentId": "242874", "Score": "1" } } ]
{ "AcceptedAnswerId": "242880", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T21:14:41.650", "Id": "242874", "Score": "1", "Tags": [ "python", "python-3.x", "pyqt" ], "Title": "PyQt5 GroupBox Layouts Feedback" }
242874
<p>I am teaching myself some coding, and as my first "big" project I tried implementing a Steepest Descent algorithm to minimize the Rosenbrock function:</p> <p><span class="math-container">$$f(x, y) = 100 (y - x^2)^2 + (1 - x)^2$$</span></p> <p>The algorithm goes like this: We start with an initial guess <span class="math-container">\$x_0\$</span> (vector). We update the guess using the formula</p> <p><span class="math-container">$$x_{k+1} = x_k - alpha (\nabla f(x_k) \cdot \nabla f(x_k))$$</span></p> <p>where alpha is to be chosen so that is satisfies the Armijo condition. We keep repeating until we reach a point where the gradient is less than 0.1 in both components.</p> <p>Could you please tell me any ways in which I could improve my algorithm? In particular, I'm looking to increase its speed. From the current starting point, it takes about 30 seconds to run on my computer (16GM ram, i7 processor).</p> <p><strong>Remark:</strong> The reason I keep using <code>np.array([[1, 2, 3]])</code> for vectors is so that I can transpose and matrix multiply them at will. I'm not sure if this is a good practice.</p> <pre><code># This program uses the Steepest Descent Method to # minimize the Rosenbrock function import numpy as np # Define the Rosenbrock Function def f(x_k): x, y = x_k[0, 0], x_k[0, 1] return 100 * (y - x**2)**2 + (1 - x)**2 # Gradient of f def gradient(x_k): x, y = x_k[0, 0], x_k[0, 1] return np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]]) def main(): # Define the starting guess x_k = np.array([[10, 5]]) # Define counter for number of steps numSteps = 0 # Keep iterating until both components of the gradient are less than 0.1 in absolute value while abs((gradient(x_k)[0, 0])) &gt; 0.1 or abs((gradient(x_k))[0, 1]) &gt; 0.1: numSteps = numSteps + 1 # Step direction p_k = - gradient(x_k) gradTrans = - p_k.T # Now we use a backtracking algorithm to find a step length alpha = 1.0 ratio = 0.8 c = 0.01 # This is just a constant that is used in the algorithm # This loop selects an alpha which satisfies the Armijo condition while f(x_k + alpha * p_k) &gt; f(x_k) + (alpha * c * (gradTrans @ p_k))[0, 0]: alpha = ratio * alpha x_k = x_k + alpha * p_k print("The number of steps is: ", numSteps) print("The final step is:", x_k) print("The gradient is: ", gradient(x_k)) main() </code></pre>
[]
[ { "body": "<p>You biggest time waster appears to be this loop:</p>\n\n<pre><code> while f(x_k + alpha * p_k) &gt; f(x_k) + (alpha * c * (gradTrans @ p_k))[0, 0]:\n alpha = ratio * alpha\n</code></pre>\n\n<p><code>f(x_k)</code>, <code>c</code>, <code>gradTrans</code>, and <code>p_k</code> are all constant in the loop, so you can compute <code>f(x_k)</code> and <code>c * (gradTrans @ p_k)</code> before the loop and use these computed values in the test expression, instead of recomputing the same values over and over.</p>\n\n<pre><code> fxk = f(x_k)\n offset = c * (gradTrans @ p_k)\n while f(x_k + alpha * p_k) &gt; fxk + (alpha * offset)[0, 0]:\n alpha = ratio * alpha\n</code></pre>\n\n<p>Doing so cuts the time roughly in half.</p>\n\n<p>Similarly, <code>gradient(x_k)</code> is computed 3 times here:</p>\n\n<pre><code>while abs((gradient(x_k)[0, 0])) &gt; 0.1 or abs((gradient(x_k))[0, 1]) &gt; 0.1:\n ...\n p_k = - gradient(x_k)\n</code></pre>\n\n<p>Again, compute once and store the result.</p>\n\n<hr>\n\n<p>You should probably use vectors instead of matrices:</p>\n\n<pre><code> x_k = np.array([10., 5.])\n</code></pre>\n\n<p>Which can be unpacked using tuple assignment:</p>\n\n<pre><code>def f(x_k):\n x, y = x_k \n return 100 * (y - x**2)**2 + (1 - x)**2\n</code></pre>\n\n<p>And using <code>10.</code> and <code>5.</code> in the above <code>x_k</code> initialization makes the arrays <code>float64</code> instead of <code>int32</code>, which allows you to use in-place addition operators:</p>\n\n<pre><code> x_k += alpha * p_k\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code> x_k = x_k + alpha * p_k\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:45:47.740", "Id": "476761", "Score": "1", "body": "Argh, you beat me to it. :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:47:56.537", "Id": "476763", "Score": "1", "body": "Ya, but you wrote a better answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:58:00.423", "Id": "476764", "Score": "1", "body": "Hardly better, just longer.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T03:58:31.713", "Id": "476787", "Score": "0", "body": "Thank you so much for the feedback!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:37:39.187", "Id": "242918", "ParentId": "242877", "Score": "4" } }, { "body": "<p>This</p>\n\n<pre><code># Define the Rosenbrock Function\ndef f(x_k):\n x, y = x_k[0, 0], x_k[0, 1] \n return 100 * (y - x**2)**2 + (1 - x)**2\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>def f_rosenbrock(xy):\n x, y = xy\n return 100 * (y - x**2)**2 + (1 - x)**2\n</code></pre>\n\n<p>This</p>\n\n<pre><code># Gradient of f \ndef gradient(x_k):\n x, y = x_k[0, 0], x_k[0, 1] \n return np.array([-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)])\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>def df_rosenbrock(xy):\n x, y = xy\n return np.array([-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)])\n</code></pre>\n\n<p>It wouldn't cost much to turn <code>main</code> into a more general gradient descent function having the following signature:</p>\n\n<pre><code>def gradient_descent(f, d_f, x0):\n # Define the starting guess\n x_k = x0\n # ...\n</code></pre>\n\n<p>You could add the following condition so that this code won't run if imported as a module.</p>\n\n<pre><code>if __name__ == '__main__':\n # main()\n gradient_descent(f_rosenbrock, df_rosenbrock, np.array([10, 5]))\n</code></pre>\n\n<p>It'd probably be the best to stick to either <code>camelCase</code> or <code>snake_case</code> for variable names. The second is more popular. E.g. <code>num_steps</code> instead of <code>numSteps</code>.</p>\n\n<p>Don't evaluate the gradient so many times:</p>\n\n<pre><code> while abs((gradient(x_k)[0, 0])) &gt; 0.1 or abs((gradient(x_k))[0, 1]) &gt; 0.1:\n # ...\n p_k = - gradient(x_k)\n gradTrans = - p_k.T\n\n # ...\n print(\"The gradient is: \", gradient(x_k))\n</code></pre>\n\n<p>could be</p>\n\n<pre><code> while True:\n g_k = df(x_k)\n\n if np.abs(g_k).max() &lt; tol:\n break \n # ...\n print(\"The gradient is: \", g_k)\n</code></pre>\n\n<p>We don't need <code>gradTrans</code>, nor <code>p_k</code>.</p>\n\n<p>This</p>\n\n<pre><code> # Now we use a backtracking algorithm to find a step length\n alpha = 1.0\n ratio = 0.8\n c = 0.01 # This is just a constant that is used in the algorithm\n\n # This loop selects an alpha which satisfies the Armijo condition \n while f(x_k + alpha * p_k) &gt; f(x_k) + (alpha * c * (gradTrans @ p_k))[0, 0]:\n alpha = ratio * alpha\n\n x_k = x_k + alpha * p_k\n</code></pre>\n\n<p>part is probably the worst offender wrt. performance. You don't have to recalculate all of these values. Some constants are hardcoded, while they could easily become parameters.</p>\n\n<p>Anyway, putting it all together we get something like the following.\nFeel free to add comments to it, but use docstrings whenever appropriate.</p>\n\n<pre><code>import numpy as np\n\ndef f_rosenbrock(xy):\n x, y = xy\n return 100 * (y - x**2)**2 + (1 - x)**2\n\ndef df_rosenbrock(xy):\n x, y = xy\n return np.array([-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)])\n\ndef gradient_descent(f, df, x0, tol=.1, alpha=1.0, ratio=.8, c=.01):\n x_k, num_steps, step_size = x0, 0, alpha\n while True:\n g_k = df(x_k)\n\n if np.abs(g_k).max() &lt; tol:\n break\n\n num_steps += 1\n\n fx, cg = f(x_k), - c * (g_k**2).sum()\n while f(x_k - step_size * g_k) &gt; fx + step_size * cg:\n step_size *= ratio\n\n x_k -= step_size * g_k\n\n return x_k, g_k, num_steps\n\nif __name__ == '__main__':\n x, g, n = gradient_descent(\n f_rosenbrock, df_rosenbrock, np.array([10.0, 5.0])\n )\n print(\"The number of steps is: \", n)\n print(\"The final step is:\", x)\n print(\"The gradient is: \", g)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T03:59:01.597", "Id": "476788", "Score": "0", "body": "Thanks, your feedback is increadibly helpful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:44:48.240", "Id": "242919", "ParentId": "242877", "Score": "4" } } ]
{ "AcceptedAnswerId": "242919", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T22:13:27.960", "Id": "242877", "Score": "3", "Tags": [ "python", "python-3.x", "numpy", "numerical-methods" ], "Title": "Implementing a Steepest Descent Algorithm" }
242877
<p>I was practicing C++ and data structures and wrote my own implementation of a doubly linked ring. I would love to improve my code a little bit more and would need help from the community.</p> <p>Here is the implementation I have:</p> <pre><code>#ifndef BIRING_H_INCLUDED #define BIRING_H_INCLUDED #include&lt;iostream&gt; #include&lt;string&gt; using namespace std; template&lt;typename Key, typename Value&gt; class Ring { private: struct Element { Key key; Value value; Element* next; Element* prev; }; Element* head; Element* tail; public: class iterator { private: Element* ptr; public: iterator() { ptr=NULL; }; iterator(const iterator &amp; copy) { ptr=copy.ptr; }; iterator(Element* copy) { ptr=copy; }; ~iterator() {}; iterator&amp; operator=(iterator &amp; copy) { ptr=copy.ptr; }; iterator&amp; operator=(Element* copy) { ptr=copy; return *this; }; Key &amp; operator*() { return ptr-&gt;key; }; const Key &amp; getKey() { return ptr-&gt;key; }; const Value &amp; getValue() { return ptr-&gt;value; }; iterator operator+(const int i)const { iterator newthis = *this; for(int j=0; j&lt;i; j++) newthis++; return newthis; }; iterator&amp; operator+=(const int i) { for(int j=0; j&lt;i; j++) ptr=ptr-&gt;next; return *this; }; iterator&amp; operator++() { iterator a(*this); ptr=ptr-&gt;next; return a; }; iterator operator++(int) { ptr=ptr-&gt;next; return *this; }; iterator operator-(const int i)const { iterator newthis = *this; for(int j=0; j&lt;i; j++) newthis--; return newthis; }; iterator&amp; operator-=(const int i) { for(int j=0; j&lt;i; j++) ptr=ptr-&gt;prev; return *this; }; iterator&amp; operator--() { iterator a(*this); ptr=ptr-&gt;prev; return a; }; iterator operator--(int) { ptr=ptr-&gt;prev; return *this; }; bool operator==(const iterator &amp; comp)const { return ptr==comp.ptr; }; bool operator!=(const iterator &amp; comp)const { return ptr!=comp.ptr; }; bool isNull()const { return !ptr; }; }; Ring(); ~Ring(); Ring(const Ring&lt;Key,Value&gt; &amp; copy); Ring&lt;Key,Value&gt; &amp; operator=(const Ring&lt;Key,Value&gt; &amp; copy); Ring&lt;Key,Value&gt; operator+(const Ring&lt;Key,Value&gt; &amp; add)const; Ring&lt;Key,Value&gt; operator-(const Ring&lt;Key,Value&gt; &amp; subtract)const; Ring&lt;Key,Value&gt;&amp; operator++(); Ring&lt;Key,Value&gt; operator++(int); Ring&lt;Key,Value&gt;&amp; operator--(); Ring&lt;Key,Value&gt; operator--(int); Ring&lt;Key,Value&gt; &amp; operator+=(const Ring&lt;Key,Value&gt; &amp; add) { *this=*this+add; return *this; }; Ring&lt;Key,Value&gt; &amp; operator-=(const Ring&lt;Key,Value&gt; &amp; subtract) { *this=*this-subtract; return *this; }; void clear(); void reverse(); iterator begin() const { return iterator(head); }; iterator end() const { return iterator(tail); }; unsigned int size() const; bool empty()const { return !head; }; bool insertAt(unsigned int pos, const Key&amp;key, const Value &amp;value); bool insertAfter(const Key&amp;keypos, const Key&amp;key, const Value &amp;value); bool insertAfter(const iterator &amp; iter, const Key&amp;key, const Value &amp;value); void push_front(const Key&amp;key, const Value &amp;value); void push_back(const Key&amp;key, const Value &amp;value); void pop_front() { iterator a(begin()); remove(a); }; void pop_back() { iterator a(end()); remove(a); }; bool remove(const Key&amp;key); bool remove(iterator &amp; iter); bool removeAllOf(const Key&amp;key); bool exists(const Key&amp;key); bool operator==(const Ring&lt;Key,Value&gt; &amp; check)const; bool operator!=(const Ring&lt;Key,Value&gt; &amp; check)const; template&lt;typename u, typename i&gt; friend ostream &amp; operator&lt;&lt; (ostream &amp; os, const Ring&lt;u,i&gt; &amp; toprint); iterator find(const Key &amp;where) const;//move to the position of the designated ID iterator findPlace(int place) const;//move to the position of designated startindex bool findNodePlace(int place) const; }; template &lt;typename Key, typename Value&gt; unsigned int Ring&lt;Key, Value&gt;::size() const { int length=0; if(head!=NULL) { Element *current = head-&gt;next; length=1; while(current!=head) { length++; current=current-&gt;next; } } return length; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt;::Ring() { head=tail=NULL; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt;::Ring(const Ring&lt;Key,Value&gt; &amp; copy) { head=tail=NULL; Element * temp = copy.head; while (temp) { this-&gt;push_back(temp-&gt;key, temp-&gt;value); if(temp==copy.tail) break; temp=temp-&gt;next; } } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt;::~Ring() { clear(); } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt; &amp; Ring&lt;Key,Value&gt;::operator=(const Ring&lt;Key,Value&gt; &amp; copy) { if(&amp;copy==this) return *this; clear(); Element * temp = copy.head; while (temp) { this-&gt;push_back(temp-&gt;key, temp-&gt;value); if(temp==copy.tail) break; temp=temp-&gt;next; } return *this; } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::operator==(const Ring&lt;Key,Value&gt; &amp; check)const { bool same = true; Element * temp1 = head; Element * temp2 = check.head; while(temp1&amp;&amp;temp2) { if(temp1-&gt;key!=temp2-&gt;key || temp1-&gt;value!=temp2-&gt;value) same = false; if(temp1==tail||temp2==check.tail) break; temp1=temp1-&gt;next; temp2=temp2-&gt;next; } return same; } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::operator!=(const Ring&lt;Key,Value&gt; &amp; check)const { return !(*this==check); }; template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt; Ring&lt;Key,Value&gt;::operator+(const Ring&lt;Key,Value&gt; &amp; added)const { Ring&lt;Key,Value&gt; tempseq; Element * temp = head; while(temp) { tempseq.push_back(temp-&gt;key,temp-&gt;value); if(temp==tail) break; temp=temp-&gt;next; } temp = added.head; while(temp) { tempseq.push_back(temp-&gt;key,temp-&gt;value); if(temp==added.tail) break; temp=temp-&gt;next; } return tempseq; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt; Ring&lt;Key,Value&gt;::operator-(const Ring&lt;Key,Value&gt; &amp; subtract)const { Ring&lt;Key,Value&gt; tempseq; Element * temp = head; while(temp) { tempseq.push_back(temp-&gt;key,temp-&gt;value); if(temp==tail) break; temp=temp-&gt;next; } temp = subtract.head; while(temp) { tempseq.removeAllOf(temp-&gt;key); if(temp==subtract.tail) break; temp=temp-&gt;next; } return tempseq; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt;&amp; Ring&lt;Key,Value&gt;::operator++() { if(head) { head=head-&gt;next; tail=tail-&gt;next; } return *this; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt; Ring&lt;Key,Value&gt;::operator++(int) { Ring a(*this); if(head) { head=head-&gt;next; tail=tail-&gt;next; } return a; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt;&amp; Ring&lt;Key,Value&gt;::operator--() { if(head) { head=head-&gt;prev; tail=tail-&gt;prev; } return *this; } template&lt;typename Key, typename Value&gt; Ring&lt;Key,Value&gt; Ring&lt;Key,Value&gt;::operator--(int) { Ring a(*this); if(head) { head=head-&gt;prev; tail=tail-&gt;prev; } return a; } template&lt;typename u, typename i&gt; ostream &amp; operator&lt;&lt;(ostream &amp; os, const Ring&lt;u,i&gt; &amp; toprint) { typename Ring&lt;u,i&gt;::Element* temp; temp = toprint.head; while(temp) { os &lt;&lt; "Key: " &lt;&lt; temp-&gt;key &lt;&lt; endl &lt;&lt; "Value: " &lt;&lt; temp-&gt;value &lt;&lt; endl; if(temp==toprint.tail) break; temp = temp-&gt;next; } return os; } template&lt;typename Key,typename Value&gt; void Ring&lt;Key,Value&gt;::clear() { Element * temp; temp=head; if(tail) tail-&gt;next=NULL; while(temp) { temp = temp-&gt;next; delete head; head = temp; } head=tail=NULL; } template&lt;typename Key,typename Value&gt; void Ring&lt;Key,Value&gt;::reverse() { Ring&lt;Key,Value&gt; tempseq; Element * temp = head; while(temp) { tempseq.push_front(temp-&gt;key,temp-&gt;value); if(temp==tail) break; temp=temp-&gt;next; } *this=tempseq; } template&lt;typename Key,typename Value&gt; bool Ring&lt;Key,Value&gt;::insertAt(unsigned int pos, const Key&amp;key, const Value &amp;value) { if(pos&gt;size()) return false; Element * temp = head; for(unsigned int i = 0; i&lt;pos; i++) { temp=temp-&gt;next; } Element * newElement; newElement = new Element; newElement-&gt;key=key; newElement-&gt;value=value; newElement-&gt;next=newElement; newElement-&gt;prev=newElement; if(!temp) { head=tail=newElement; } else { newElement-&gt;next=temp; newElement-&gt;prev=temp-&gt;prev; temp-&gt;prev-&gt;next=newElement; temp-&gt;prev=newElement; } if(pos==0){ head=newElement; }else if(pos==size()){ tail=newElement; } return true; } template&lt;typename Key,typename Value&gt; bool Ring&lt;Key,Value&gt;::insertAfter(const Key&amp;keypos, const Key&amp;key, const Value &amp;value) { Element * temp = head; bool found = false; while(temp) { if(temp-&gt;key==keypos) { found=true; break; } if(temp==tail) break; temp=temp-&gt;next; } if(!found) return false; Element * newElement; newElement = new Element; newElement-&gt;key=key; newElement-&gt;value=value; newElement-&gt;next=temp-&gt;next; newElement-&gt;prev=temp; temp-&gt;next-&gt;prev=newElement; temp-&gt;next=newElement; if(head==tail){ head=tail=newElement; }else if(temp==tail){ tail=newElement; } return true; } template&lt;typename Key,typename Value&gt; bool Ring&lt;Key,Value&gt;::insertAfter(const iterator &amp; iter, const Key&amp;key, const Value &amp;value) { Element * temp = head; bool found = false; iterator comp; while(temp) { comp=temp; if(comp==iter) { found=true; break; } if(temp==tail) break; temp=temp-&gt;next; } if(!found) return false; Element * newElement; newElement = new Element; newElement-&gt;key=key; newElement-&gt;value=value; newElement-&gt;next=temp-&gt;next; newElement-&gt;prev=temp; temp-&gt;next-&gt;prev=newElement; temp-&gt;next=newElement; if(head==tail) head=tail=newElement; else if(temp==tail) tail=newElement; return true; } template&lt;typename Key, typename Value&gt; void Ring&lt;Key,Value&gt;::push_front(const Key&amp;key, const Value &amp;value) { Element * newElement; newElement = new Element; newElement-&gt;key = key; newElement-&gt;value = value; if(head) { newElement-&gt;next = head; newElement-&gt;prev = tail; tail-&gt;next=newElement; head-&gt;prev=newElement; head=newElement; } else { newElement-&gt;next = newElement; newElement-&gt;prev = newElement; head=tail=newElement; } } template&lt;typename Key, typename Value&gt; void Ring&lt;Key,Value&gt;::push_back(const Key&amp;key, const Value &amp;value) { Element * newElement; newElement = new Element; newElement-&gt;key = key; newElement-&gt;value = value; if(head) { newElement-&gt;next = head; newElement-&gt;prev = tail; tail-&gt;next=newElement; head-&gt;prev=newElement; tail=newElement; } else { newElement-&gt;next = newElement; newElement-&gt;prev = newElement; head=tail=newElement; } } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::remove(const Key&amp;key) { Element* temp = head; while(temp) { if(temp-&gt;key==key) { if(head==tail) { delete temp; head = tail = NULL; size--; return; } else { temp-&gt;next-&gt;prev=temp-&gt;prev; temp-&gt;prev-&gt;next=temp-&gt;next; size--; delete temp; return; } } if(temp==tail) break; temp=temp-&gt;next; } } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::remove(iterator&amp; iter) { if(iter.isNull()) return false; Element* temp = head; iterator comp; while(temp) { comp = temp; if(comp==iter) { iter++; if(head==tail) { delete temp; head = tail = NULL; return true; } else { if(temp==head) head=temp-&gt;next; else if(temp==tail) tail=temp-&gt;prev; temp-&gt;next-&gt;prev=temp-&gt;prev; temp-&gt;prev-&gt;next=temp-&gt;next; delete temp; return true; } } if(temp==tail) break; temp=temp-&gt;next; } return false; } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::removeAllOf(const Key&amp;key) { Element* temp = head; bool deleted = false; while(temp) { if(temp-&gt;key==key) { deleted=true; if(head==tail) { delete temp; head = tail = NULL; return deleted; } else { if(temp==head) head=temp-&gt;next; else if(temp==tail) tail=temp-&gt;prev; temp-&gt;next-&gt;prev=temp-&gt;prev; temp-&gt;prev-&gt;next=temp-&gt;next; delete temp; } } if(temp==tail) break; temp=temp-&gt;next; } return deleted; } template&lt;typename Key, typename Value&gt; bool Ring&lt;Key,Value&gt;::exists(const Key&amp;key) { Element * temp = head; while(temp) { if(temp-&gt;key==key) return true; temp=temp-&gt;next; } return false; } template&lt;typename Key, typename Info&gt; typename Ring&lt;Key, Info&gt;::iterator Ring&lt;Key, Info&gt;::find(const Key &amp;where) const { iterator iter = begin(); if (head != NULL) { do { if (iter.getKey() == where) { return iter; } iter++; } while (iter != begin()); } return NULL; } template &lt;typename Key, typename Info&gt; typename Ring&lt;Key, Info&gt;::iterator Ring&lt;Key, Info&gt;::findPlace(int place) const { iterator iter = begin(); int position = 0; if (head != NULL) { do { if (position == place) { return iter; } iter++; position++; } while (iter != begin()); } return NULL; } template &lt;typename Key, typename Info&gt; bool Ring&lt;Key, Info&gt;::findNodePlace(int place) const { iterator iter = find(place); if (iter == NULL) { return false; } else { return true; } } #endif // BIRING_H_INCLUDED </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T06:23:52.030", "Id": "476688", "Score": "1", "body": "(\"Coming\" from [CLASS SIMSET](http://simula67.at.ifi.uio.no/Standard-86/chap_11.htm), I'd love to see a contemporary take.) Can you please summarise, as an introduction to the longish code, a) interface (/envisioned usage) b) your goal in coding this? (I appreciate the hint in tagging *reinventing-the-wheel* - tell me more)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T07:53:49.020", "Id": "476697", "Score": "0", "body": "I just would like to learn from my mistakes and have a perfect implementation of the this" } ]
[ { "body": "<p>Here are a number of things that may help you improve your program. Since it's not specified, I'm going to assume C++17.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers).</p>\n<h2>Avoid spurious punctuation</h2>\n<p>The code currently has this function:</p>\n<pre><code>template&lt;typename Key, typename Value&gt;\nbool Ring&lt;Key,Value&gt;::operator!=(const Ring&lt;Key,Value&gt; &amp; check)const\n{\n return !(*this==check);\n};\n</code></pre>\n<p>That will compile and work, but the semicolon (<code>;</code>) at the end is not necessary and should be deleted.</p>\n<h2>Make sure all paths return a value</h2>\n<p>The <code>remove</code> functions both claim to return a <code>bool</code>, but the version that takes a <code>const Key&amp;</code> argument doesn't. It should be a <code>void</code> function as written or better, make it work like the iterator version and actually return a <code>bool</code>.</p>\n<h2>Don't return a pointer to a local object</h2>\n<p>The code for the iterator contains these member functions:</p>\n<pre><code>iterator&amp; operator++()\n{\n iterator a(*this);\n ptr=ptr-&gt;next;\n return a;\n};\n\niterator operator++(int)\n{\n ptr=ptr-&gt;next;\n return *this;\n};\n</code></pre>\n<p>There are two problems with this. First, they are swapped because the <code>operator++(int)</code> form is the one that should post-increment. Second, and most importantly, the first function is returning a reference to a local object which will yield <em>undefined behavior</em> if anything tries to subsequently use it.</p>\n<h2>Understand iterators</h2>\n<p>An iterator is required to be <em>dereferenceable</em>, so that if you are storing a collection of things in your data structure <code>ring</code> and write <code>auto item{ring.cbegin()};</code> it means that <code>item</code> should be an iterator that points to one of those things. The problem here is that we're trying to store two things: a <code>Key</code> and a <code>Value</code>. I would suggest that things could be made much simpler with something like this:</p>\n<pre><code>struct Item {\n Key key;\n Value value;\n};\n\nstruct Element\n{\n Item item;\n Element* next;\n Element* prev;\n};\n</code></pre>\n<p>Now you can define the iterator dereference as returning an <code>Item</code>.</p>\n<h2>Use <code>nullptr</code> rather than <code>NULL</code></h2>\n<p>Modern C++ uses <code>nullptr</code> rather than <code>NULL</code>. See <a href=\"http://stackoverflow.com/questions/1282295/what-exactly-is-nullptr/1283623#1283623\">this answer</a> for why and how it's useful.</p>\n<h2>Remove spurious template declaration</h2>\n<p>The <code>Ring</code> class declaration currently includes this line near the end just above the declaration for <code>find</code>:</p>\n<pre><code>template&lt;typename u, typename i&gt;\n</code></pre>\n<p>I don't know why that is there, but it prevents the code from compiling and should be deleted.</p>\n<h2>Fix <code>end()</code></h2>\n<p>There is a problem with the iterator <code>end()</code> as currently written:</p>\n<pre><code>iterator end() const\n{\n return iterator(tail);\n};\n</code></pre>\n<p>The problem is that this returns an iterator to the last element, but what it should do is return an iterator that is <a href=\"https://en.cppreference.com/w/cpp/container/vector/end\" rel=\"nofollow noreferrer\">one past the last element</a>. That would be simple except that the doubly-linked list doesn't have an end the way it's currently written. That leads to the next suggestion.</p>\n<h2>Break the circularity</h2>\n<p>I'd suggest keeping the doubly-linked list, but inside the <code>Ring</code> don't actually connect the head and tail. In other words, if <code>head</code> is defined, then <code>head-&gt;prev</code> should be <code>nullptr</code> and if <code>tail</code> is defined, then <code>tail-&gt;next</code> should be <code>nullptr</code>. This not only helps with the iterator above, but also greatly simplifies the code for <code>push_front</code> and <code>push_back</code>:</p>\n<pre><code>template&lt;typename Key, typename Value&gt;\nvoid Ring&lt;Key,Value&gt;::push_front(const Key&amp;key, const Value &amp;value)\n{\n auto temp{new Element{{key, value}, nullptr, head}};\n if (head) {\n head-&gt;prev = temp;\n head = temp;\n } else {\n head = tail = temp;\n }\n}\n\ntemplate&lt;typename Key, typename Value&gt;\nvoid Ring&lt;Key,Value&gt;::push_back(const Key&amp; key, const Value &amp;value)\n{\n auto temp{new Element{{key, value}, tail, nullptr}};\n if (tail) {\n tail-&gt;next = temp;\n tail = temp;\n } else {\n head = tail = temp;\n }\n}\n</code></pre>\n<p>If there is any purpose to traversing beyond the tail back to the head, that can be accomodated within the function needing it.</p>\n<h2>Simplify your code</h2>\n<p>The <code>find</code> routine is more complex than it needs to be and other routines could use <code>find</code> to simplify. Examples:</p>\n<pre><code>template&lt;typename Key, typename Info&gt;\ntypename Ring&lt;Key, Info&gt;::iterator Ring&lt;Key, Info&gt;::find(const Key &amp;where) const\n{\n for (iterator it{begin()}; it != end(); ++it) {\n if (it-&gt;key == where) {\n return it;\n }\n }\n return end();\n}\n\ntemplate&lt;typename Key, typename Value&gt;\nbool Ring&lt;Key,Value&gt;::exists(const Key&amp; key)\n{\n return find(key) != end();\n}\n</code></pre>\n<h2>Don't implement <code>ostream&lt;&lt;</code> for templated types</h2>\n<p>There is not a good reason to implement <code>ostream&lt;&lt;</code> for a templated type like this and many good reasons not to, including the fact that the user may want to define his or her own.</p>\n<h2>Conform to standard template library norms</h2>\n<p>Instead of <code>size()</code> returning an <code>unsigned int</code>, it would be better to return a <code>std::size_t</code> to conform with the STL.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:06:51.990", "Id": "251708", "ParentId": "242878", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T00:07:51.267", "Id": "242878", "Score": "5", "Tags": [ "c++", "algorithm", "reinventing-the-wheel" ], "Title": "Doubly linked ring implementation" }
242878
<p>So I implemented drivers for I2C and USART using interrupts with some guidelines online, and was wondering if I can get some suggestions from a design point of view even though the code works (tried at 9600 and 115200 baud rate), but I do get a hardfault upon using two different baud rates at RX/TX. One reason could be I'm using <code>\r</code> as an indication to disable the interrupts, and in case of different baud rates, it might not even disable the interrupts since the received byte is different than what was sent. So I'm not sure if I should be concerned with it.</p> <p>The program:</p> <ul> <li>runs a loop where it listens for the bytes over UART after the control bits are enabled</li> <li>triggers ISR for each byte received while storing it into a respective linear buffer, until <code>\r</code> is received, indicating the <em>end of message</em></li> <li>disables the control bits so it's no longer acting on any new bytes</li> <li>parses the data in the linear buffer till <code>\r</code>, and does some stuff based on what we receive. One of the things that the program does is read the value off the temperature sensor over I2C and serial it out!</li> </ul> <p>My thoughts:</p> <ul> <li>I am not sure if I'm making the right usage of interrupts (or maybe I am) cause what I do is enable the peripheral control bits, and then sort of wait for the ISR to be fired (that's application-specific I guess), while storing each byte into the buffer till we get <code>\r</code>.</li> <li>I am using a linear buffer instead of a preferred circular buffer cause I thought it wouldn't make much of a difference for this application. I am sort of using it a circular buffer (maybe I'm wrong) by restarting the index for storing data into RX buffer to 0; so every time there's a new data, it gets appended from the start. In case of a circular buffer, I'd continue storing data continuously and it would eventually wrap around overriding the old data which has already been parsed by then.</li> <li>To make this application more generic, I might need to remove the device address member from the struct and instead pass it to respective I2C HAL functions.</li> </ul> <p>I have included the relevant parts of the code. Feel free to leave a comment if there's any confusion.</p> <h2>hal_i2c.h</h2> <pre><code>typedef struct { uint32_t I2C_SCLSpeed; uint8_t I2C_DeviceAddress; uint8_t I2C_AckControl; uint16_t I2C_FMDutyCycle; } I2C_Config_t; </code></pre> <h2>hal_i2c.c</h2> <pre><code>I2C_State HAL_I2C_StartInterrupt(I2C_State expectedState, uint8_t txSize, uint8_t rxSize) { if (I2C_handle_p-&gt;I2C_State == I2C_INIT) { // set transaction state I2C_handle_p-&gt;I2C_State = expectedState; // set respective buffer sizes I2C_handle_p-&gt;txBufferLength = txSize; I2C_handle_p-&gt;rxBufferLength = rxSize; // generate start condition I2C_GenerateStartCondition(I2C_handle_p); // enable i2c control bits I2C_SetCtrlBits(); } return I2C_handle_p-&gt;I2C_State; } void I2C1_EV_IRQHandler (void) { uint8_t eventInterrupt = (I2C_handle_p-&gt;pI2Cx-&gt;CR2 &amp; I2C_CR2_ITEVTEN) &gt;&gt; I2C_CR2_ITEVTEN_Pos; uint8_t bufferInterrupt = (I2C_handle_p-&gt;pI2Cx-&gt;CR2 &amp; I2C_CR2_ITBUFEN) &gt;&gt; I2C_CR2_ITBUFEN_Pos; uint8_t temp; // stores register values if (eventInterrupt) { // validate the completion of START condition temp = (I2C_handle_p-&gt;pI2Cx-&gt;SR1 &amp; I2C_SR1_SB) &gt;&gt; I2C_SR1_SB_Pos; if (temp) { if (I2C_handle_p-&gt;I2C_State == I2C_TX_BUSY) { I2C_WriteSlaveAddress(I2C_handle_p, WRITE); // write slave address along with write bit } else if (I2C_handle_p-&gt;I2C_State == I2C_RX_BUSY) { I2C_WriteSlaveAddress(I2C_handle_p, READ); // write slave address along with read bit } } // ADDR temp = (I2C_handle_p-&gt;pI2Cx-&gt;SR1 &amp; I2C_SR1_ADDR) &gt;&gt; I2C_SR1_ADDR_Pos; if (temp) { I2C_ClearADDRFlag(I2C_handle_p-&gt;pI2Cx); // clear address flag } // TXE, RXNE if (bufferInterrupt) { // TXing temp = (I2C_handle_p-&gt;pI2Cx-&gt;SR1 &amp; I2C_SR1_TXE) &gt;&gt; I2C_SR1_TXE_Pos; if (temp &amp;&amp; I2C_handle_p-&gt;I2C_State == I2C_TX_BUSY) { I2C_TXE_Interrupt(); } // RXing temp = (I2C_handle_p-&gt;pI2Cx-&gt;SR1 &amp; I2C_SR1_RXNE) &gt;&gt; I2C_SR1_RXNE_Pos; } //BTF temp = (I2C_handle_p-&gt;pI2Cx-&gt;SR1 &amp; I2C_SR1_BTF) &gt;&gt; I2C_SR1_BTF_Pos; if (temp) { if (I2C_handle_p-&gt;I2C_State == I2C_TX_BUSY) // TXE=1, BTF=1 { if (!I2C_handle_p-&gt;txBufferLength) // if there are no more TX bytes to be sent { I2C_GenerateStopCondition(I2C_handle_p); I2C_StopTransmission(); } } else if (I2C_handle_p-&gt;I2C_State == I2C_RX_BUSY) // RXNE=1, BTF=1, LEN=0 --&gt; STOP { if (I2C_handle_p-&gt;rxBufferLength == 2) { I2C_GenerateStopCondition(I2C_handle_p); I2C_handle_p-&gt;pRxBuffer[I2C_handle_p-&gt;rxStartIndex++] = (uint8_t) I2C_handle_p-&gt;pI2Cx-&gt;DR; // read second last byte I2C_handle_p-&gt;rxBufferLength--; I2C_handle_p-&gt;pRxBuffer[I2C_handle_p-&gt;rxStartIndex++] = (uint8_t) I2C_handle_p-&gt;pI2Cx-&gt;DR; // read last byte I2C_handle_p-&gt;rxBufferLength--; I2C_StopTransmission(); } } } } } void I2C_TXE_Interrupt (void) { if (I2C_handle_p-&gt;txBufferLength) { I2C_handle_p-&gt;pI2Cx-&gt;DR = (*I2C_handle_p-&gt;txBuffer)++; I2C_handle_p-&gt;txBufferLength--; } } static void I2C_StopTransmission(void) { // disable control bits I2C_handle_p-&gt;pI2Cx-&gt;CR2 &amp;= ~(1 &lt;&lt; I2C_CR2_ITEVTEN_Pos); I2C_handle_p-&gt;pI2Cx-&gt;CR2 &amp;= ~(1 &lt;&lt; I2C_CR2_ITBUFEN_Pos); // restore struct I2C_handle_p-&gt;I2C_State = I2C_READY; I2C_handle_p-&gt;rxStartIndex = 0; } </code></pre> <h2>usart_app.h</h2> <pre><code>typedef struct { USART_TypeDef *pUSARTx; USART_Config_t USART_Config; USART_State USART_State; char *txBuffer; char *rxBuffer; uint8_t txLength; uint8_t rxLength; uint8_t rxSize; uint8_t dmaTransfer; uint8_t dmaReception; DMA_Handle_t *dmaRx; DMA_Handle_t *dmaTx; } USART_Handle_t; </code></pre> <h2>usart_app.c</h2> <pre><code>void StartSerial (USART_Handle_t *usart, char *usart_rxBuffer, uint8_t rxBufferSize, I2C_Handle_t *I2C_Handle) { char tempBuffer[rxBufferSize]; memset(tempBuffer, 0, rxBufferSize); while(true) { ReceiveSerialData(usart); ParseSerialData(usart, tempBuffer, usart_rxBuffer); bool status = ExecuteSerialData(usart, tempBuffer, I2C_Handle); if (!status) // break if "q" is entered { break; } // clear out the buffers -- probably don't need it! usart-&gt;rxBuffer = usart_rxBuffer; memset(usart_rxBuffer, 0, sizeof(rxBufferSize)); memset(tempBuffer, 0, sizeof(tempBuffer)); // reset the USART state usart-&gt;USART_State = USART_INIT; } } void ReceiveSerialData(USART_Handle_t *usart) { while (USART_RxData(USART_RX_BUSY) != USART_READY); } void ParseSerialData(USART_Handle_t *usart, char *tempBuffer, char *rxBuffer) { char *start = rxBuffer; char *end = strstr(rxBuffer, "\r"); uint8_t bytes = end - start; memcpy(tempBuffer, start, bytes); } bool ExecuteSerialData(USART_Handle_t *usart, const char *str1, I2C_Handle_t *I2C_Handle) { if (!strcmp(str1, "temp")) { uint16_t temp = GetTemperature(I2C_Handle); SendSerialData(usart, "Current temperature: %d\n", temp); } else if (!strcmp(str1, "q")) { SendSerialData(usart, "Ending serial\n"); return false; } return true; } </code></pre> <h2>main.c</h2> <pre><code>void I2C_Initilization(I2C_Config_t *I2C_Config, I2C_TypeDef *i2cPeripheral) { I2C1_handle.pI2Cx = i2cPeripheral; I2C1_handle.I2C_Config = *I2C_Config; I2C_Init(&amp;I2C1_handle); } void USART_Init (void) { USART2_handle.pUSARTx = USART2; USART2_handle.USART_Config.USART_baudRate = USART_BAUD_9600; USART2_handle.USART_Config.USART_mode = USART_MODE_TXRX; USART2_handle.USART_Config.USART_parityControl = USART_PARITY_DISABLED; USART2_handle.USART_Config.USART_stopBits = USART_STOP; USART2_handle.USART_Config.USART_wordLength = USART_8_DATA_BITS; USART2_handle.rxBuffer = usart_rxBuffer; USART2_handle.rxLength = rxLength; USART2_handle.rxSize = rxLength; USART2_handle.dmaTransfer = DMA_TX_DISABLE; USART2_handle.dmaReception = DMA_RX_DISABLE; USART_Initization(&amp;USART2_handle); } int main(void) { HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize all configured peripherals */ MX_GPIO_Init(); /* Initialize I2C config struct */ I2C_Config_t i2c_config = { I2C_AckControl: I2C_ACK_ENABLE, I2C_SCLSpeed: I2C_SCL_SPEED_SM, I2C_DeviceAddress: MCP9808_ADDRESS, I2C_FMDutyCycle: I2C_FM_DUTY_2 }; I2C_Initilization(&amp;i2c_config, I2C1); /* Initialize USART struct */ USART_Init(); StartSerial (&amp;USART2_handle, usart_rxBuffer, usart_rxLength, &amp;I2C1_handle); while (1); } </code></pre> <h2>mcp9808.c</h2> <pre><code>// static variables static uint8_t txBuffer[1] = {MCP9808_REG_AMBIENT_TEMP_REG}; static uint8_t rxBuffer[BYTES_TO_READ]; static uint8_t txSize = sizeof(txBuffer)/sizeof(txBuffer[0]); static uint8_t rxSize = BYTES_PER_TRANSACTION; uint16_t GetTemperature(I2C_Handle_t *I2C_Handle) { uint16_t temperature; temperature = ReadTemperature(I2C_Handle); return temperature; } uint16_t ReadTemperature(I2C_Handle_t *I2C_handle) { I2C_handle-&gt;txBuffer = txBuffer; I2C_handle-&gt;pRxBuffer = rxBuffer; I2C_handle-&gt;rxBufferSize = rxSize; // Start I2C transaction while (HAL_I2C_StartInterrupt(I2C_TX_BUSY, txSize, rxSize) != I2C_READY); I2C_handle-&gt;I2C_State = I2C_INIT; // read the data from the sensor for (int i = 0; i &lt; I2C_handle-&gt;rxBufferSize/2; i++) { I2C_handle-&gt;I2C_State = I2C_INIT; while (HAL_I2C_StartInterrupt(I2C_RX_BUSY, txSize, rxSize) != I2C_READY); } uint16_t temperature = ProcessData(I2C_handle-&gt;pRxBuffer); return temperature; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T03:34:14.427", "Id": "476683", "Score": "2", "body": "Could you please add the struct definitions for `I2C_Config_t` and `USART2_handle` to the question. As it stands the question could be closed due to `lack of context`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T03:49:19.013", "Id": "476684", "Score": "0", "body": "Did you test whether it works for your situation? Will ther be retries on fault conditions without the rest of the program running into timing problems? Will this be used in residential or industrial environment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T03:51:17.407", "Id": "476685", "Score": "2", "body": "Where are your HAL functions defined and did you wrote those or were they supplied by the vendor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:28:43.050", "Id": "476750", "Score": "1", "body": "I can provide them, and I wrote them myself @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:48:04.643", "Id": "476753", "Score": "0", "body": "@pacmaninbw - added `I2C_Config_t` and `USART2_handle`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:03:00.553", "Id": "476755", "Score": "0", "body": "I hope you don't mind, I made it a little more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T09:39:52.543", "Id": "477095", "Score": "0", "body": "It would be helpful to know the MCU used. I'm assuming some manner of Cortex-M like STM32 or Microchip SAM?" } ]
[ { "body": "<p><strong>Big picture/design</strong></p>\n\n<p>If you have the option to use DMA, then go with that. DMA can be somewhat complex in its own, but it doesn't screw up all the real-time requirements of the whole program, in the way that asynchronous receiver interrupts do.</p>\n\n<p>That being said, storing incoming Rx data from a UART in a (ring) buffer is the old school way of doing things. It should work out fine unless your program has a lot of real-time deadlines.</p>\n\n<p><strong>Interrupts</strong></p>\n\n<p>The all-time most common bug in embedded systems is failing to protect data shared with interrupts from race conditions, so it is not at all surprising if this is the cause of the bug you describe.</p>\n\n<p>It is not entirely clear how the interrupts handle re-entrancy with the main application, as the magic <code>I2C_handle_p</code> struct definition is absent. I don't understand what you mean to do with <code>\\r</code>, there is no code posted that disables the interrupts based on that.</p>\n\n<p>You need some manner of semaphores from protecting the caller from reading part of the data, then get interrupted in the middle of it. I like to provide these as a feature in the ring buffer ADT itself, making that one intrinsically interrupt safe.</p>\n\n<p>Alternatively, you could temporary disable interrupts in the caller while you grab the data, but that only works if the caller can do this in less time than it takes for the serial bus to send another byte.</p>\n\n<p>Usually this is done by providing double-buffering (no matter if you have a ring buffer or a linear one). You have one software buffer where the incoming data is getting written, and another buffer which contains the latest completely received data. When the ISR is done receiving, it only swaps the pointers between these two buffers. </p>\n\n<p>So if you have a <code>memcpy</code> somewhere doing a hard copy of the whole buffer, you are doing it wrong. This is yet another very common problem in defective ISR code. Similarly, there should be no need to <code>memset</code> everything to zero repeatedly, that's just wasting time for nothing.</p>\n\n<p>And finally, all variables shared with the ISR must be declared <code>volatile</code>. That's another common bug - read this: <a href=\"https://electronics.stackexchange.com/questions/409545/using-volatile-in-embedded-c-development/409570#409570\">Using volatile in embedded C development</a>.</p>\n\n<p><strong>Other issues/best practices</strong></p>\n\n<ul>\n<li><p>What about framing/overrun errors and similar? What do you do when such errors occur? Your program should handle them and discard the data when they strike. Also, I don't see any checksum or CRC. UART in particular is very unreliable.</p></li>\n<li><p>Never bit shift on signed or negative types. This means, never write <code>1 &lt;&lt; ..</code> because the integer constant <code>1</code> is of type signed int. Use <code>1u</code> suffix and in case of variables, make sure to cast to a large unsigned type before shifting. </p></li>\n<li><p><code>~</code> is notorious for changing signedness of its operand and thereby causing all manner of implicit integer promotion bugs. It's a good habit of casting its operand to a large unsigned type before applying <code>~</code>. Be aware of the <a href=\"https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules\">Implicit type promotion rules</a>, they are especially known to cause havoc on small 8- or 16-bit microcontroller systems.</p></li>\n<li><p>Never use <code>char</code> for storing raw data, even if you expect incoming data from UART to be text. It comes with implementation-defined signedness (<a href=\"https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default\">Is char signed or unsigned by default?</a>), and embedded compilers in particular are known to implement <code>char</code> differently from case to case. Read everything as <code>uint8_t</code> and then when everything is verified and you know that the input is valid text, cast to <code>char</code> if you must.</p></li>\n<li><p>Avoid variadic functions. These are known to have non-existent safety and are needlessly slow. They might seem convenient to the programmer, but they are not convenient to the <em>program</em>, as they make things slower and buggier in general. There should be no need to use variadic functions in an embedded system.</p></li>\n<li><p>It's bad practice to write empty while loops like <code>while (something);</code>, because to the reader it is completely unclear if the semi-colon is intentional or just a slip of the finger. Therefore, always use one of these forms instead:</p>\n\n<pre><code>while (something)\n ;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>while(something)\n{}\n</code></pre></li>\n<li><p><code>uint8_t bytes = end - start;</code> is rather questionable, you need to guarantee that this won't be larger than 255 bytes. </p>\n\n<p>Also note that upon pointer subtraction, you are actually getting back an obscure large integer type called <code>ptrdiff_t</code> which does you no good. I'd recommend to do <code>(uint8_t)end - (uint8_t)start</code> instead.</p></li>\n<li><p>Never use <code>int</code> anywhere in an embedded system. You should be using the types from <code>stdint.h</code>, or <code>size_t</code> in case you are declaring a for loop iterator.</p></li>\n<li><p><code>static uint8_t txSize = sizeof(txBuffer)/sizeof(txBuffer[0]);</code>. This should either have been a macro or a <code>const</code>, instead of a read/write variable. </p></li>\n<li><p>The format of main() in an embedded bare metal system is always <code>void main(void)</code>, unless your compiler requires some other exotic form. Who are you going to return to? With gcc-like compilers, you need to compile embedded systems with the <code>-ffreestanding</code> option.</p></li>\n<li><p>All your files are missing <code>#include</code> so it isn't clear if you are even including the correct libraries or otherwise have strange file dependencies.</p></li>\n<li><p>Where is the watchdog code? Microcontroller firmware which is not utilizing a watchdog is defective, period. You may disable it in debug release, but where to place it and where to feed it needs to be considered early on, and the code must be present. </p>\n\n<p>Ideally you only feed it at one single point of your program, on top of the internal loop in main().</p></li>\n</ul>\n\n<hr>\n\n<p>Overall, a lot of these common issues/dormant bugs could have been avoided if you used MISRA-C. I'd strongly recommend to at least read it as study material, even if you don't want to go all the way and get formal compliance. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T10:37:52.430", "Id": "243096", "ParentId": "242879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T00:34:44.140", "Id": "242879", "Score": "4", "Tags": [ "c", "embedded" ], "Title": "Is my design for data reading over an I2C bus and writing back to UART good enough?" }
242879
<p>After some time poorly designing my web applications' backends (mixing database calls with the controller, etc.), I have decided to try the "Clean Architecture" approach.</p> <p>In this example I have a REST api <code>users</code> which allows you to get a list of all users in MongoDB and to put a user inside the database.</p> <p>Please, any suggestion on how I can make it better organized would be awesome.</p> <p>app.js</p> <pre><code>const express = require("express"); const bodyParser = require("body-parser"); const config = require("./config.js"); const Routes = require("./src/routes.js"); const Database = require("./src/database.js"); const app = express(); app.use(bodyParser.json()); const PORT = config.PORT; app.use("/api/", Routes()); new Database(config.MONGODB_URI) // connects to the database using MONGODB cluster URL .then(() =&gt; { app.listen(config.PORT, () =&gt; { console.log(`Server running on port ${config.PORT}`); }); }) .catch((err) =&gt; console.error(err)); </code></pre> <p>/src/routes.js</p> <pre><code>const express = require("express"); const usersRouter = require("./user/routes.js"); const Routes = (dependencies) =&gt; { const router = express.Router(); router.use("/users", usersRouter(dependencies)); return router; }; module.exports = Routes; </code></pre> <p>/src/database.js</p> <pre><code>const mongoose = require("mongoose"); module.exports = class Database{ constructor(connection){ this.connection = connection; return mongoose.connect(this.connection, { useNewUrlParser: true, useUnifiedTopology: true }); } }; </code></pre> <p>src/user/routes.js</p> <pre><code>const express = require("express"); const UserController = require("./controller.js"); const UserModal = require("./data_access/modal.js"); const UserRepository = require("./repository.js"); const userRoutes = () =&gt; { const modal = UserModal; // pretty much the User modal/document const repository = new UserRepository(modal); // talks to the db const router = express.Router(); const controller = UserController(repository); // handles request, sends repository to services router.route('/') .get(controller.getUsers) .post(controller.addUser); return router; }; module.exports = userRoutes; </code></pre> <p>src/user/repository.js</p> <pre><code>module.exports = class UserRepository{ constructor(model){ this.model = model; } create(user){ return new Promise((resolve, reject) =&gt;{ this.model(user).save(); resolve(user); }); } getByEmail(email){ return new Promise((resolve, reject) =&gt;{ this.model.find({email: email}) .then((user) =&gt; resolve(user[0])); }); } getByUsername(username){ return new Promise((resolve, reject) =&gt;{ this.model.find({username: username}) .then((user) =&gt; resolve(user[0])); }); } getAll(){ return new Promise((resolve, reject) =&gt; { const students = this.model.find({}); resolve(students); }); } }; </code></pre> <p>src/user/controller.js</p> <pre><code>const GetUsers = require("./services/get_users.js"); const AddUser = require("./services/add_user.js"); module.exports = (repository) =&gt; { const getUsers = (req, res) =&gt; { GetUsers(repository) .execute() .then((result) =&gt; res.sendStatus(200).json(result)) .catch((err) =&gt; console.error(err)); }; const addUser = (req, res) =&gt; { const { username, email } = req.body; AddUser(repository) .execute(username, email) .then((result) =&gt; res.send(200)) .catch((err) =&gt; { res.send(403); console.error(err); }); }; return { getUsers, addUser }; }; </code></pre> <p>/src/user/services/add_user.js</p> <pre><code>module.exports = (repository) =&gt; { async function execute(username, email){ return Promise.all([repository.getByUsername(username), repository.getByEmail(email)]) .then((user) =&gt; { if(user[0]){ return Promise.reject("username already taken!"); } else if(user[1]){ return Promise.reject("email already taken!"); } else{ repository.create({username: username, email: email}); return Promise.resolve("all good!"); } }); } return {execute}; }; </code></pre> <p>src/user/services/get_user.js</p> <pre><code>module.exports = (repository) =&gt; { async function execute(){ const users = repository.getAll(); return new Promise((resolve, reject) =&gt; resolve(users)); } return {execute}; }; </code></pre> <p>src/user/data_access/schema.js (entities)</p> <pre><code>const mongoose = require("mongoose"); module.exports = new mongoose.Schema( { username: { type: String }, email: { type: String }, password_hash: { type: String } }); </code></pre> <p>src/user/data_access/model.js (entities)</p> <pre><code>const mongoose = require("mongoose"); const userSchema = require("./schema.js"); const UserModal = mongoose.model("User", userSchema); module.exports = UserModal; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T08:12:55.923", "Id": "476699", "Score": "0", "body": "I dont think you need a separate service for get and add. And btw do you really let the modal set password hash? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T08:21:49.103", "Id": "476701", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Your code looks very structured and nicely written, but to my understanding, your solution is not \"clean architecture\" (CA) as described by uncle bob. Your solution is an MVC solution.</p>\n\n<p>In clean architecture you can (for example):</p>\n\n<ul>\n<li>easily replace express with another framework</li>\n<li>easily replace mongo with another DB</li>\n</ul>\n\n<p>In your case the framework is embedded into your logic, you can see that the controller is using res to output the JSON outside. so replacing the framework will require a rewrite.</p>\n\n<p>Another example is that you have no clear boundaries between all the application layers.\nIt can be easily seen that all your imports are from express => to logic => to database and back and that's not using dependency inversion. In CA you have entities layer which is the higher layer and all other layers import the entities as a dependency and it is the communication protocol between all layers.</p>\n\n<p>Other things:</p>\n\n<p>Where is the exception handling\nWhere is the validation handling\nWhere are the multiple ways to output your data (XML, JSON, CSV)</p>\n\n<p>I think you managed to reach a working <strong>positive</strong> solution (which I think is not extensible for all future cases):</p>\n\n<ol>\n<li>Because you don't have all the required functionality in place (positive and negative).</li>\n<li>You don't have unit tests to prove that you are testable</li>\n<li>You didn't process your output, there are many HTTP Responses that your presenter needs to handle, but so far you created some basic functionality, so it works.</li>\n<li>Where the complexity (as number of API will grow, and when the complexity of the logic will grow) you will start feeling the pain of extensibility.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T05:39:09.337", "Id": "477675", "Score": "0", "body": "dude, thank you so much for your answer! indeed, I can see it's not exactly Clean Architecture; i've just started learning software engineering and it's a whole new world. you seem to be knowledgeable and I would love to chat with your for some quick questions if possible. either way, thank you so much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T08:07:20.923", "Id": "477688", "Score": "1", "body": "If that is the case then I would recommend starting with TDD rather then clean architecture.\n1) Read TDD by Example of Kent Beck.\n2) Please ask your questions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T21:46:28.780", "Id": "477744", "Score": "0", "body": "will definitely read the book. I am confused with the \"dependency\" issue. for example, the service/use-case needs the repository (which talks to the database), correct? should the service get the repository simply by importing it, or should the repository be given to the service in the parameter? thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T20:40:04.683", "Id": "477917", "Score": "0", "body": "You should read about boundaries in the book.\n\nDependency inversion & dependency injection are two things: \n\none is used decoupling layers you don't need to know about, like business logic and DB, needs not to know about each other and you use and adapter pattern to split them using the interface as protocol middleman. \n\nThe other used to pass instances of object you want to use in a component instead of creating them inline for decoupling and testability" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T23:23:15.727", "Id": "501487", "Score": "0", "body": "@AdiCohen, can you please indicate what chapter (or pages) in the book discuss boundaries? I tried to find variations of the words \"boundary\", \"entity\", \"dependency\" in the book, but couldn't find what you referred to :( Also, if you know of a good example for a Node.js clean architecture example (e.g., some Github repo) which uses Express and Mongoose as the decoupled example frameworks, it would be great to get a link." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T00:02:42.823", "Id": "243348", "ParentId": "242884", "Score": "4" } } ]
{ "AcceptedAnswerId": "243348", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T04:45:58.810", "Id": "242884", "Score": "3", "Tags": [ "javascript", "design-patterns", "node.js", "mongodb", "mongoose" ], "Title": "\"Clean Architecture\" design pattern with Node.JS and MongoDB" }
242884
<p>My excel program import from another workbook, exported from SAP, some columns to update my dashboard.</p> <p>To do this I use ADODB, the code run right and fast (26K rows and 32 columns on 00:00:26:1226).</p> <p>But I see that some columns with data/time aren't correctly formatted, the poblem is that not all date columns just some, I think are a Sap problem, but i get this file from customer and it will my problem.</p> <p><a href="https://i.stack.imgur.com/NuMv6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NuMv6.png" alt="enter image description here"></a></p> <p>So, this are my query without any custom format, just extraction:</p> <pre><code>cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" &amp; WsFrom.FullName &amp; "; Extended Properties=""Excel 8.0;HDR=Yes;"";" SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation, '' as Divisione, [(01-A)-Ordine d'acquisto] as Orders, switch([(07)D-Modalità Trasp] = 'AOG','AOG', [(07)D-Modalità Trasp] &lt;&gt; 'AOG','STD') as Trasporto, [(07)-Fine carico att] as StartDateSap, [(07)-Ora attfine car] as StartTimeSap, [(01-A)-Data di reg] as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap, [(07)-Inizio trasp att] as StartDateBlock, [(07)-Ora attinizio trasp] as StartTimeBlock, [(07)-Data FINE Sdoganamento] as EndDateBlock, [(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock, [(02)-Utente] as Users, [(06-A)-Blocco-In-Data] as DateBlockIn, [(07)-Tipo di trasporto] as DoganaTax1, [(09-A)-Controllo conferma] as DoganaTax2, from [Sheet1$]; rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText rs.MoveFirst dbSh.Range("A2").CopyFromRecordset rs </code></pre> <p>this is the 1th test, I updated code (I change [data/time_Field] as customName to Cdate([data/time_Field]) as customName. the update show me all data/time fields like as data/time the qry run on 00:01:08:128 </p> <pre><code>cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" &amp; WsFrom.FullName &amp; "; Extended Properties=""Excel 8.0;HDR=Yes;"";" SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation, '' as Divisione, [(01-A)-Ordine d'acquisto] as Orders, switch([(07)D-Modalità Trasp] = 'AOG','AOG', [(07)D-Modalità Trasp] &lt;&gt; 'AOG','STD') as Trasporto, [(07)-Fine carico att]*1 as StartDateSap, [(07)-Ora attfine car] as StartTimeSap, [(01-A)-Data di reg]*1 as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap, [(07)-Inizio trasp att]*1 as StartDateBlock, [(07)-Ora attinizio trasp] as StartTimeBlock, [(07)-Data FINE Sdoganamento]*1 as EndDateBlock, [(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock, [(02)-Utente] as Users, [(06-A)-Blocco-In-Data]*1 as DateBlockIn, [(07)-Tipo di trasporto]*1 as DoganaTax1, [(09-A)-Controllo conferma]*1 as DoganaTax2, from [Sheet1$]; rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText rs.MoveFirst dbSh.Range("A2").CopyFromRecordset rs </code></pre> <p>this is the 2th test, I updated code (I change [data/time_Field] as customName to [data/time_Field]*1 as customName. the update show me all date fields like as data/time the qry run on 00:00:44:1244</p> <pre><code>cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" &amp; WsFrom.FullName &amp; "; Extended Properties=""Excel 8.0;HDR=Yes;"";" SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation, '' as Divisione, [(01-A)-Ordine d'acquisto] as Orders, switch([(07)D-Modalità Trasp] = 'AOG','AOG', [(07)D-Modalità Trasp] &lt;&gt; 'AOG','STD') as Trasporto, [(07)-Fine carico att]*1 as StartDateSap, [(07)-Ora attfine car] as StartTimeSap, [(01-A)-Data di reg]*1 as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap, [(07)-Inizio trasp att]*1 as StartDateBlock, [(07)-Ora attinizio trasp] as StartTimeBlock, [(07)-Data FINE Sdoganamento]*1 as EndDateBlock, [(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock, [(02)-Utente] as Users, [(06-A)-Blocco-In-Data]*1 as DateBlockIn, [(07)-Tipo di trasporto]*1 as DoganaTax1, [(09-A)-Controllo conferma]*1 as DoganaTax2, from [Sheet1$]; rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText rs.MoveFirst dbSh.Range("A2").CopyFromRecordset rs </code></pre> <p>So, my workaround work fine, for me is slow and I'm not sure that is a good code, there are a better way?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T10:23:34.347", "Id": "242891", "Score": "1", "Tags": [ "sql", "adodb" ], "Title": "there are a better solutions to set FIELDS as data at ADODB query from xls file (exported from SAP)" }
242891
<p>Would appreciate any input on these building blocks functions of tic tac toe.</p> <pre><code>def display_field(cells): print('''\ --------- | {} {} {} | | {} {} {} | | {} {} {} | ---------\ '''.format(*cells)) def analyze_field(cells): """ Args: cells (str): a string of an XO pattern Returns: (str): the result of the XO field """ num_x = cells.lower().count('x') num_o = cells.lower().count('o') rows = [[cells[j] for j in range(i, i + 3)] for i in range(0, 9, 3)] columns = [[row[i] for row in rows] for i in range(3)] first_diagonal = rows[0][0] + rows[1][1] + rows[2][2] second_diagonal = rows[0][2] + rows[1][1] + rows[2][0] if abs(num_x - num_o) not in [0, 1]: return 'Impossible' num_winners = 0 for row, column in zip(rows, columns): if len(set(row)) == 1: num_winners += 1 if len(set(column)) == 1: num_winners += 1 if num_winners &gt; 1: return 'Impossible' for row in rows: if len(set(row)) &lt;= 1: return f'{row[0]} wins' for column in columns: if len(set(column)) &lt;= 1: return f'{column[0]} wins' if len(set(first_diagonal)) &lt;= 1: return f'{first_diagonal[0]} wins' elif len(set(second_diagonal)) &lt;= 1: return f'{second_diagonal[0]} wins' # No winner else: if '_' in cells or ' ' in cells: return 'Game not finished' else: return 'Draw' cells = input('Enter cells:') display_field(cells) print(analyze_field(cells)) </code></pre> <pre><code>Enter cells:XO_XO_XOX --------- | X O _ | | X O _ | | X O X | --------- Impossible </code></pre>
[]
[ { "body": "<h2>Flat array for display</h2>\n\n<p>It looks like <code>display_field</code> accepts a one-dimensional array. By the time you're manipulating it with business logic and presenting it back to the user, it should be a two-dimensional array. Rather than one format string, you would then call <code>'\\n'.join()</code>.</p>\n\n<h2>Presentation vs. business logic</h2>\n\n<p>In several places your presentation (\"Impossible\", \"X\") is all conflated with your business logic. Do not use strings to return status from <code>analyze_field</code>. What to use instead depends on a number of factors; some options are:</p>\n\n<ul>\n<li>Use an Enum</li>\n<li>Use a callback object where there is one function per result option</li>\n</ul>\n\n<p>Along similar lines, do not store 'x' and 'o' strings in the cells. You can use an Enum here, perhaps with values <code>PLAYER1/PLAYER2</code>. Strings are unconstrained, and a matter of style/presentation/UI rather than business logic, which should be more verifiable.</p>\n\n<h2>Set membership</h2>\n\n<pre><code>if abs(num_x - num_o) not in [0, 1]:\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if abs(num_x - num_o) not in {0, 1}:\n</code></pre>\n\n<p>since order does not matter and set lookup has O(1) time complexity. That said, I think this is equivalent to</p>\n\n<pre><code>if not(-1 &lt;= num_x - num_o &lt;= 1):\n</code></pre>\n\n<p>assuming that <code>num_x</code> and <code>num_o</code> are integral.</p>\n\n<h2>Zip</h2>\n\n<p>I question this logic:</p>\n\n<pre><code>for row, column in zip(rows, columns):\n if len(set(row)) == 1:\n num_winners += 1\n if len(set(column)) == 1:\n num_winners += 1\n</code></pre>\n\n<p>I think what you're looking for is a chain, not a zip:</p>\n\n<pre><code>for sequence in chain(rows, columns):\n if len(set(sequence)) == 1:\n num_winners += 1\n</code></pre>\n\n<p>In other words, there's no point to checking a row and its corresponding column in the same loop iteration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:42:46.313", "Id": "242914", "ParentId": "242892", "Score": "3" } }, { "body": "<p>Your checks are inconsistent at best, and wrong at worst.</p>\n\n<p>Your code counts the number of winners in horizontal and vertical directions. And if this is greater than 1, you complain <code>Impossible</code>. However, you are ignoring any possible diagonal winners.</p>\n\n<p>But you are also forgetting it is possible to win in two directions at once. </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Enter cells:OXOX_XOXO\n---------\n| O X O |\n| X _ X |\n| O X O |\n---------\nGame not finished\n</code></pre>\n\n<p>X has one move left: the centre:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Enter cells:OXOXXXOXO\n---------\n| O X O |\n| X X X |\n| O X O |\n---------\nImpossible\n</code></pre>\n\n<p>Nope. Not impossible. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:46:48.237", "Id": "242915", "ParentId": "242892", "Score": "2" } } ]
{ "AcceptedAnswerId": "242914", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T11:06:38.603", "Id": "242892", "Score": "2", "Tags": [ "python" ], "Title": "Python Tic Tac Toe Building Block Function" }
242892
<p>The standard library <code>heapq</code> in python doesn't support updating keys as a public method, which makes it hard to be used as a priority queue. Although the official documentation has suggested a <a href="https://docs.python.org/2/library/heapq.html#priority-queue-implementation-notes" rel="nofollow noreferrer">workaround</a>, it is somewhat convoluted. So I decided to implement my own priority queue as a min-heap.</p> <p>Here is my code:</p> <pre><code>class HeapQueue: """Implement a priority queue in the form of a min-heap. Each entry is an (item, key) pair. Item with a lower key has a higher priority. Item must be hashable and unique. No duplicate items. Pushing an existing item would update its key instead. """ def __init__(self, entries=None): """ :argument: entries (iterable of tuples): an iterable of (item, key) pairs """ if entries is None: self._entries = [] self._indices = {} else: self._entries = list(entries) self._indices = {item: idx for idx, (item, _) in enumerate(entries)} self._heapify() def _heapify(self): """Enforce the heap properties upon initializing the heap.""" start = len(self) // 2 - 1 for idx in range(start, -1, -1): self._down(idx) def __contains__(self, item): """Return True if the item is in the heap.""" return item in self._indices def __len__(self): """Number of entries remaining in the heap.""" return len(self._entries) def __iter__(self): """Return an iterator of all items.""" for item, _ in self._entries: yield item """Helper methods""" def _swap(self, idx1, idx2): """Swap two entries.""" item1, _ = self._entries[idx1] item2, _ = self._entries[idx2] self._indices[item1] = idx2 self._indices[item2] = idx1 self._entries[idx1], self._entries[idx2] = self._entries[idx2], self._entries[idx1] def _up(self, idx): """Bring a violating entry up to its correct position recursively.""" if idx == 0: return parent = (idx - 1) // 2 # compare key with the parent if self._entries[idx][1] &lt; self._entries[parent][1]: self._swap(idx, parent) self._up(parent) def _smaller_child(self, idx): """Find the child with smaller key. If no child, return None.""" left = 2 * idx + 1 # case 1: no child if left &gt;= len(self): return None right = left + 1 # case 2: only left child if right == len(self): return left # case 3: two children if self._entries[left][1] &lt; self._entries[right][1]: return left else: return right def _down(self, idx): """Bring a violating entry down to its correct position recursively.""" child = self._smaller_child(idx) if child is None: return # compare key with the child with smaller key if self._entries[idx][1] &gt; self._entries[child][1]: self._swap(idx, child) self._down(child) """Priority queue operations""" def peek(self): """Return the item with the minimum key.""" item, _ = self._entries[0] return item def push(self, item, key): """Push an item into the heap with a given key. If the item already exists, update its key instead. """ if item not in self._indices: # insert the new item to the end and bring it up to the correct position idx = len(self) self._entries.append((item, key)) self._indices[item] = idx self._up(idx) else: # the item already exists, find its index and update its key idx = self._indices[item] item, old_key = self._entries[idx] self._entries[idx] = (item, key) # bring the entry to the correct position if key &lt; old_key: self._up(idx) if key &gt; old_key: self._down(idx) def pop(self): """Remove the item with the minimum key. The resulting (item, key) pair is also returned.""" # after swapping the first and the last entry, # the required entry goes from the beginning to the end self._swap(0, len(self) - 1) item, key = self._entries.pop() del self._indices[item] self._down(0) return item, key </code></pre> <p>Is there any improvement I can make?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T11:16:26.880", "Id": "242894", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "object-oriented", "heap" ], "Title": "Implement priority queue as min-heap in python" }
242894
<p>I know there's already a whole bunch of similar attempts at this and I've looked at a few of them to get some tips. My main aim with this was not to write anything fancy. I wanted to create a simple game with the most basic functionality but write it really well. In other words I'm more interested in making my code professional, efficient and of high quality. One way I've tried to do this is to keep the main function simple and use it mostly for initialisation and the game loop, whilst implementing most of the functionality in separate classes and functions. Also, I would appreciate any advice on comments and docstrings because I'm sure mine are far from perfect. I also noticed the clock speed is around 4.5 GHz while playing this, so I think this could definitely do with an efficiency boost.</p> <pre><code>#!/usr/bin/env python3 import pygame as pg from random import randint # Define window parameters BLOCK_SIZE = 20 WIN_SIZE = 500 class Head(): blue = (0, 0, 255) # Colour of snake start_params = (BLOCK_SIZE * 0.05, BLOCK_SIZE * 0.05, BLOCK_SIZE * 0.9, BLOCK_SIZE * 0.9) def __init__(self, pos): """Head of snake""" self.x = pos[0] self.y = pos[1] self.last_x = self.x self.last_y = self.y self.direction = [0, -BLOCK_SIZE] self.square = None def make_block(self): """ Create a surface to contain a square Draw a square Rect object onto said surface """ self.square = pg.Surface((BLOCK_SIZE, BLOCK_SIZE), pg.SRCALPHA) # Draw a square onto the "square" surface pg.draw.rect(self.square, self.blue, self.start_params) def update_pos(self): """Last coords are used to update next block in the snake""" self.last_x = self.x self.last_y = self.y self.x += self.direction[0] self.y += self.direction[1] def change_direction(self, new_dir): """Change direction of snake without allowing it to go backwards""" if new_dir == 'u' and self.direction != [0, BLOCK_SIZE]: self.direction = [0, -BLOCK_SIZE] elif new_dir == 'd' and self.direction != [0, -BLOCK_SIZE]: self.direction = [0, BLOCK_SIZE] elif new_dir == 'l' and self.direction != [BLOCK_SIZE, 0]: self.direction = [-BLOCK_SIZE, 0] elif new_dir == 'r' and self.direction != [-BLOCK_SIZE, 0]: self.direction = [BLOCK_SIZE, 0] def check_collision(self, pos_list): """Check if snake collides with wall or itself""" if self.x in (0, WIN_SIZE) or self.y in (0, WIN_SIZE): return True if (self.x, self.y) in pos_list[3:]: return True return False def get_pos(self): return (self.last_x, self.last_y) class Block(Head): def __init__(self, next_block): """Body of snake""" self.next = next_block pos = next_block.get_pos() self.x = pos[0] self.y = pos[1] self.last_x = self.x self.last_y = self.y self.ready = 0 def update_pos(self): """Use position of next block in snake to update current position""" self.last_x = self.x self.last_y = self.y next_pos = self.next.get_pos() self.x = next_pos[0] self.y = next_pos[1] def add_block(snake_arr): """Extend snake by adding a snake block to the snake array""" snake_arr.append(Block(snake_arr[-1])) snake_arr[-1].make_block() return snake_arr def check_keypress(input_event, block_object): """ Take input event and change direction if arrow key or quit game if esc key or other exit signal """ if input_event.type == pg.QUIT: return True elif input_event.type == pg.KEYDOWN: if input_event.key == pg.K_ESCAPE: return True elif input_event.key == pg.K_UP: block_object.change_direction('u') elif input_event.key == pg.K_DOWN: block_object.change_direction('d') elif input_event.key == pg.K_LEFT: block_object.change_direction('l') elif input_event.key == pg.K_RIGHT: block_object.change_direction('r') return False class Food(): def __init__(self): """Food block, created in the same way as a snake block""" self.exists = False self.x = None self.y = None self.square = None def add_food(self): """If no food present, create a new food block with random position""" if self.exists is False: # Create a surface to contain a square self.square = pg.Surface((BLOCK_SIZE, BLOCK_SIZE), pg.SRCALPHA) # Draw a square onto the "square" surface pg.draw.rect(self.square, (255, 0, 0), (BLOCK_SIZE * 0.05, BLOCK_SIZE * 0.05, BLOCK_SIZE * 0.9, BLOCK_SIZE * 0.9)) self.x = randint(1, (WIN_SIZE - BLOCK_SIZE)/BLOCK_SIZE) * BLOCK_SIZE self.y = randint(1, (WIN_SIZE - BLOCK_SIZE)/BLOCK_SIZE) * BLOCK_SIZE self.exists = True def check_if_eaten(self, snake): """If snake head is in food block, food is eaten""" snake_x, snake_y = snake[0] if (self.x &lt;= snake_x &lt;= self.x + BLOCK_SIZE * 0.9) and (self.y &lt;= snake_y &lt;= self.y + BLOCK_SIZE * 0.9): self.exists = False return True return False def main(): # Initialise PyGame pg.init() clock = pg.time.Clock() size = (WIN_SIZE, WIN_SIZE) # Size of window, (width, height) black = (0, 0, 0) # Background colour of window # Place head of snake in centre of window start_coord = (WIN_SIZE / 2) - (BLOCK_SIZE / 2) # Create window screen = pg.display.set_mode(size) head = Head([start_coord, start_coord]) head.make_block() # Make first three blocks of snake snake = [] snake.append(head) snake = add_block(snake) snake = add_block(snake) ticker = 0 game_over = False food = Food() # Game loop while game_over is False: # Run game at 60 FPS clock.tick(60) # Monitor events and check for keypresses for event in pg.event.get(): game_over = check_keypress(event, head) if game_over is True: continue snake_pos = [block.get_pos() for block in snake] game_over = head.check_collision(snake_pos) # Update snake position every 4 frames if ticker == 3: for s in snake: s.update_pos() ticker = 0 ticker += 1 food.add_food() eaten = food.check_if_eaten(snake_pos) if eaten is True: snake = add_block(snake) # Clear the window before the next frame screen.fill(black) # Draw block to window screen.blit(food.square, [food.x, food.y]) for s in snake: screen.blit(s.square, [s.x, s.y]) # Swap buffers pg.display.flip() pg.quit() if __name__ == "__main__": main() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:27:19.013", "Id": "476738", "Score": "1", "body": "_the clock speed is around 4.5 GHz_ - That's not a very useful measurement of CPU occupation. Instead, check the OS-reported CPU load percentage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:11:02.747", "Id": "476745", "Score": "0", "body": "The total CPU load percentage stays well under 10%, though the temperature and power rise considerably. Not to the point where the fans get noisy but more than I expected from such a simple program. I'm running an i9-9980HK if that helps clarify anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:17:04.033", "Id": "476746", "Score": "0", "body": "In theory, to accommodate for auto-scaling CPUs, you would want to measure operations per second, which is a linear factor of frequency and user-time percentage." } ]
[ { "body": "<h2>Unpacking arguments</h2>\n\n<p>This:</p>\n\n<pre><code> self.x = pos[0]\n self.y = pos[1]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>self.x, self.y = pos\n</code></pre>\n\n<p>One advantage of the latter is that it will catch weird sequences that have more than two items. The easier thing to do is simply have a uniform representation of coordinates, and use <code>x,y</code> everywhere instead of a random mixture of tuples and individual variables.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def __init__(self, pos):\n \"\"\"Head of snake\"\"\"\n self.x = pos[0]\n self.y = pos[1]\n self.last_x = self.x\n self.last_y = self.y\n self.direction = [0, -BLOCK_SIZE]\n self.square = None\n</code></pre>\n\n<p>can likely be</p>\n\n<pre><code>def __init__(self, pos: Tuple[int, int]):\n \"\"\"Head of snake\"\"\"\n self.x: int = pos[0]\n self.y: int = pos[1]\n self.last_x: int = self.x\n self.last_y: int = self.y\n self.direction: Tuple[int, int] = (0, -BLOCK_SIZE)\n self.square: pg.Surface = None\n</code></pre>\n\n<h2>Strongly-typed direction</h2>\n\n<p>Do not represent a direction as a <code>u/d/l/r</code> string. Either represent it as an enum, or a unit vector of <code>x,y in {(1,0), (-1,0), (0,1), (0,-1)}</code>.</p>\n\n<h2>Mystery position list</h2>\n\n<p><code>pos_list[3:]:</code> is spooky. It's not really a good idea to assign specific meanings to elements of a list such that you need to slice it for your business logic. What do the first three positions of the snake mean? Since they have a separate meaning, does it even make sense to keep them in the same list?</p>\n\n<h2>Magic constants</h2>\n\n<pre><code> if ticker == 3:\n</code></pre>\n\n<p>should have its constant pulled out, so that you can write</p>\n\n<pre><code> if ticket == UPDATE_FRAMES - 1:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:46:17.210", "Id": "476751", "Score": "0", "body": "Thank you for your review Reinderien, I have added these improvements and significantly tidied up the `change_direction` method. Regarding the `pos_list[3:]:` line, I've figured it out and changed it to `pos_list[1:]`, which hopefully isn't seemingly cryptic anymore. The reason this couldn't have worked before is because in the list of positions, I was storing the last position of every block. Since the 3 starting blocks are initialised in the same place, the body blocks' current coordinates would be the same as the head block's last coordinates. Hence, the game would quit immediately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:48:37.740", "Id": "476754", "Score": "0", "body": "So to fix this, I renamed `get_pos` to `get_last_pos` and added a `get_current_pos` method. This way, the head block can safely check the current coordinates of the body blocks, without quitting the game straight away. Then the index of `1` is simply because it doesn't make sense for the head to intersect itself, it just needs to check the rest of the body." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:25:24.830", "Id": "242912", "ParentId": "242896", "Score": "1" } } ]
{ "AcceptedAnswerId": "242912", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T12:39:41.830", "Id": "242896", "Score": "2", "Tags": [ "python", "python-3.x", "pygame" ], "Title": "Snake game implemented in PyGame and Python3" }
242896
<h1>Requirements</h1> <p>I have a table of the different diagnoses a patient has received, with the date the diagnosis was first recorded. It so happens that in medicine, diagnoses are recorded as codes from a huge list called ICD10, and sometimes several different codes are related to a single disease, for example a patient will get two separate rows with code A for a cataract and code B for impaired vision. A domain expert I am working with wants to see the table displayed by combinations, and has supplied me with a list of pairwise valid combinations. </p> <p>I am interested in the code having good performance, since this whole thing is wrapped in a function that gets called repeatedly for many thousands of patients. I also want to solve it with data.table, since I am using it heavily in other parts of my code, and I prefer to keep everything consistent. Also, I think that the lookup table with code pairs should be "clean" in the sense of never having a rule twice, even if the order is inverted (such as containing both the A, B and the B, A combinations), but I would prefer a solution that is robust and works even if such repeated rules occur. </p> <h1>MWE test case</h1> <p>To give you an MWE where the codes are replaced with capital letters, I am starting with a table like this: </p> <pre> code earliest.year A 2001 B 2002 C 2003 D 2004 E 2005 F 2006 G 2007 H 2008 </pre> <p>and a table to look up valid combinations: </p> <pre> first second A B A C C H D G E I </pre> <p>and want the output to look like this: </p> <pre> code.combination earliest.year A, B, C, H 2001 D, G 2004 E 2005 F 2006 </pre> <h1>My solution</h1> <p>I first tried doing it with vectorization, but got a list-formatted output from <code>apply</code> and couldn't convert the results back to a usable data.table. So I repeated it with a for loop and it worked. </p> <pre><code>library(magrittr) library(data.table) codes &lt;- data.table(code=LETTERS[1:8], earliest.year=c(2001:2008), group=0) setkey(codes, code) valid.combinations &lt;- data.frame(first=c("A", "A", "C", "D", "E"), second=c("B", "C", "H", "G", "I")) # solution A - vectorized codes.a &lt;- copy(codes) codes.a &lt;- sapply(codes.a$code, function(current.code) { if(codes.a[current.code, group==0]) codes.a &lt;- codes.a[current.code, group:=max(codes.a$group)+1] codes.a &lt;- codes.a[code %in% valid.combinations[valid.combinations$first==current.code, "second"], group:=codes.a[current.code, group]] return(codes.a[current.code,]) }) %&gt;% t %&gt;% data.table # First, the need for transposing it feels wrong. Second, this gives me a data.table whose columns are all lists, and I get all kinds of errors when trying to work with it. # Solution B - loop codes.b &lt;- copy(codes) for(current.code in codes.b$code) { if(codes.b[current.code, group==0]) codes.b[current.code, group:=max(codes.b$group)+1] codes.b &lt;- codes.b[code %in% valid.combinations[valid.combinations$first==current.code, "second"], group:=codes.b[current.code, group]] } codes.combined &lt;- codes.b[,.(code.combination=paste(code, collapse=", "), earliest.year=min(earliest.year)),by=group] </code></pre> <h1>Questions</h1> <ol> <li>How do I get the vectorized solution to work properly (<code>codes.a</code> should be the same as <code>codes.b</code>)? </li> <li>Generally, vectorization is supposed to have better performance in R. Can I also expect it to give me better performance in this case, or does the casting into lists and re-casting into data.table negate the performance advantages? </li> <li>Is there a better solution to the problem as a whole, and if yes, what is it? </li> </ol> <p>(I am interested to hear answers to 1 and 2 even if the answer to 3 is "yes")</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:18:06.533", "Id": "242898", "Score": "2", "Tags": [ "r", "vectorization" ], "Title": "Vectorize a function that, once per row, updates multiple rows in data.table" }
242898
<p>I have 2 asynchronous return values from 2 different classes, one from HealthKit, the other from MotionManager. I combine the outcome of these classes through a combinedViewModel. The code works, but I want to know if it is properly formatted and if all functions, ... are used in the right place. With other words, can I build an official app with this code or do I need to structure it differently. </p> <p>MotionManager.swift</p> <pre><code>struct MotionValues { var rotationX: Double = 0.0 var rotationY: Double = 0.0 var rotationZ: Double = 0.0 var pitch: Double = 0.0 var roll: Double = 0.0 var yaw: Double = 0.0 } class MotionManager { @Published var motionValues = MotionValues() private let manager = CMMotionManager() func startMotionUpdates() { manager.deviceMotionUpdateInterval = 1.0 manager.startDeviceMotionUpdates(to: .main) { (data, error) in guard let data = data, error == nil else { print(error!) return } self.motionValues.rotationX = data.rotationRate.x self.motionValues.rotationY = data.rotationRate.y self.motionValues.rotationZ = data.rotationRate.z self.motionValues.pitch = data.attitude.pitch self.motionValues.roll = data.attitude.roll self.motionValues.yaw = data.attitude.yaw } } func stopMotionUpdates() { manager.stopDeviceMotionUpdates() resetAllMotionData() } func resetAllMotionData() { self.motionValues.rotationX = 0.0 self.motionValues.rotationY = 0.0 self.motionValues.rotationZ = 0.0 self.motionValues.pitch = 0.0 self.motionValues.roll = 0.0 self.motionValues.yaw = 0.0 } } </code></pre> <p>HealthKitManager.swift</p> <pre><code>class HealthKitManager { private var healthStore = HKHealthStore() private var heartRateQuantity = HKUnit(from: "count/min") private var activeQueries = [HKQuery]() @Published var heartRateValue: Double = 0.0 func autorizeHealthKit() { let heartRate = HKObjectType.quantityType(forIdentifier: .heartRate)! let heartRateVariability = HKObjectType.quantityType(forIdentifier: .heartRateVariabilitySDNN)! let HKreadTypes: Set = [heartRate, heartRateVariability] healthStore.requestAuthorization(toShare: nil, read: HKreadTypes) { (success, error) in if let error = error { print("Error requesting health kit authorization: \(error)") } } } func fetchHeartRateData(quantityTypeIdentifier: HKQuantityTypeIdentifier ) { let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()]) let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -&gt; Void = { query, samples, deletedObjects, queryAnchor, error in guard let samples = samples as? [HKQuantitySample] else { return } self.process(samples, type: quantityTypeIdentifier) } let query = HKAnchoredObjectQuery(type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!, predicate: devicePredicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: updateHandler) query.updateHandler = updateHandler healthStore.execute(query) activeQueries.append(query) } private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) { for sample in samples { if type == .heartRate { DispatchQueue.main.async { self.heartRateValue = sample.quantity.doubleValue(for: self.heartRateQuantity) } } } } func stopFetchingHeartRateData() { activeQueries.forEach { healthStore.stop($0) } activeQueries.removeAll() DispatchQueue.main.async { self.heartRateValue = 0.0 } } } </code></pre> <p>CombinedViewModel.swift</p> <pre><code>class CombinedViewModel: ObservableObject { @Published var motionValues: MotionValues = MotionValues() @Published var heartRateValue: Double = 0.0 var motion = MotionManager() var health = HealthKitManager() var cancellables = Set&lt;AnyCancellable&gt;() init() { motion.$motionValues .combineLatest(health.$heartRateValue) .sink(receiveValue: { [weak self] combined in self?.motionValues = combined.0 self?.heartRateValue = combined.1 }) .store(in: &amp;cancellables) } } </code></pre> <p>ContentView.swift</p> <pre><code>struct ContentView: View { @State var isActive: Bool = false @ObservedObject var combined = CombinedViewModel() var body: some View { ScrollView { VStack(alignment: .leading) { Indicator(title: "X:", value: combined.motionValues.rotationX) Indicator(title: "Y:", value: combined.motionValues.rotationY) Indicator(title: "Z:", value: combined.motionValues.rotationZ) Divider() Indicator(title: "Pitch:", value: combined.motionValues.pitch) Indicator(title: "Roll:", value: combined.motionValues.roll) Indicator(title: "Yaw:", value: combined.motionValues.yaw) Divider() Indicator(title: "HR:", value: combined.heartRateValue) } .padding(.horizontal, 10) Button(action: { self.isActive.toggle() self.isActive ? self.start() : self.stop() }) { Text(isActive ? "Stop" : "Start") } .background(isActive ? Color.green : Color.blue) .cornerRadius(10) .padding(.horizontal, 5) }.onAppear { self.combined.health.autorizeHealthKit() } } private func start() { self.combined.motion.startMotionUpdates() self.combined.health.fetchHeartRateData(quantityTypeIdentifier: .heartRate) } private func stop() { self.combined.motion.stopMotionUpdates() self.combined.health.stopFetchingHeartRateData() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct Indicator: View { var title: String var value: Double var body: some View { HStack { Text(title) .font(.footnote) .foregroundColor(.blue) Text("\(value)") .font(.footnote) } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:32:57.773", "Id": "242899", "Score": "3", "Tags": [ "swift", "ios", "framework", "swiftui" ], "Title": "Combine asynchronous return values in SwiftUI" }
242899
<p>I have just read the Chapter 5 of <a href="https://rads.stackoverflow.com/amzn/click/com/B00S5XEY2E" rel="nofollow noreferrer" rel="nofollow noreferrer">Data Structures and Algorithms with Python</a>. The authors implemented hash sets using linear probing. However, linear probing may result in lots of clustering. So I decided to implement my hash table with a similar approach but using <a href="https://en.wikipedia.org/wiki/Linear_congruential_generator" rel="nofollow noreferrer">linear <strong>congruential</strong> probing</a> instead.</p> <p>Below is my code:</p> <pre><code>from collections.abc import MutableMapping def _probe_seq(key, list_len): """ Generate the probing sequence of the key by the linear congruential generator: x = (5 * x + c) % list_len In order for the sequence to be a permutation of range(m), list_len must be a power of 2 and c must be odd. We choose to compute c by hashing str(key) prefixed with underscore and c = (2 * hashed_string - 1) % list_len so that c is always odd. This way two colliding keys would likely (but not always) have different probing sequences. """ x = hash(key) % list_len yield x hashed_string = hash('_' + str(key)) c = (2 * hashed_string - 1) % list_len for _ in range(list_len - 1): x = (5 * x + c) % list_len yield x class HashTable(MutableMapping): """A hash table using linear congruential probing as the collision resolution. Under the hood we use a private list self._items to store the items. We rehash the items to a larger list (resp. smaller list) every time the original list becomes too crowded (resp. too sparse). For probing to work properly, len(self._items) must always be a power of 2. """ # _init_size must be a power of 2 and not too large, 8 is reasonable _init_size = 8 # a placeholder for any deleted item _placeholder = object() def __init__(self, items=None): """ :argument: items (iterable of tuples): an iterable of (key, value) pairs """ self._items = [None] * HashTable._init_size self._len = 0 if items is not None: for key, value in items: self[key] = value def __len__(self): """Return the number of items.""" return self._len def __iter__(self): """Iterate over the keys.""" for item in self._items: if item not in (None, HashTable._placeholder): yield item[0] def __getitem__(self, key): """Get the value corresponding to the key. Raise KeyError if no such key found """ probe = _probe_seq(key, len(self._items)) idx = next(probe) # return the value if key found while probing self._items while self._items[idx] is not None: if (self._items[idx] is not HashTable._placeholder and self._items[idx][0] == key): return self._items[idx][1] idx = next(probe) raise KeyError @staticmethod def _add(key, value, items): """Helper function for __setitem__ to probe the items list. Return False if found the key and True otherwise. In either cases, set the value at the correct location. """ loc = None probe = _probe_seq(key, len(items)) idx = next(probe) while items[idx] is not None: # key found, set value at the same location if items[idx] is not HashTable._placeholder and items[idx][0] == key: items[idx] = (key, value) return False # remember the location of the first placeholder found during probing if loc is None and items[idx] is HashTable._placeholder: loc = idx idx = next(probe) # key not found, set the item at the location of the first placeholder # or at the location of None at the end of the probing sequence if loc is None: loc = idx items[loc] = (key, value) return True @staticmethod def _rehash(old_list, new_list): """Rehash the items from old_list to new_list""" for item in old_list: if item not in (None, HashTable._placeholder): HashTable._add(*item, new_list) return new_list def __setitem__(self, key, value): """Set self[key] to be value. Overwrite the old value if key found. """ if HashTable._add(key, value, self._items): self._len += 1 if self._len / len(self._items) &gt; 0.75: # too crowded, rehash to a larger list # resizing factor is 2 so that the length remains a power of 2 new_list = [None] * (len(self._items) * 2) self._items = HashTable._rehash(self._items, new_list) @staticmethod def _remove(key, items): """Helper function for __delitem__ to probe the items list. Return False if key not found. Otherwise, delete the item and return True. (Note that this is opposite to _add because for _add, returning True means an item has been added, while for _remove, returning True means an item has been removed.) """ probe = _probe_seq(key, len(items)) idx = next(probe) while items[idx] is not None: next_idx = next(probe) # key found, replace the item with the placeholder if items[idx] is not HashTable._placeholder and items[idx][0] == key: items[idx] = HashTable._placeholder return True idx = next_idx return False def __delitem__(self, key): """Delete self[key]. Raise KeyError if no such key found. """ # key found, remove one item if HashTable._remove(key, self._items): self._len -= 1 numerator = max(self._len, HashTable._init_size) if numerator / len(self._items) &lt; 0.25: # too sparse, rehash to a smaller list # resizing factor is 1/2 so that the length remains a power of 2 new_list = [None] * (len(self._items) // 2) self._items = HashTable._rehash(self._items, new_list) else: raise KeyError </code></pre> <p>I would like same feedbacks to improve my code. Thank you.</p> <p><strong>Reference:</strong></p> <p>Data Structures and Algorithms with Python, Kent D. Lee and Steve Hubbard</p>
[]
[ { "body": "<h2>Tests</h2>\n\n<p>Given something this low-level, as well as your claims that it solves specific clustering problems - you need to test it. The tests for something like this, thankfully, are relatively easy. You may also want to do some rough profiling to get an idea of how this scales in comparison to the built-in hash method.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def __init__(self, items=None):\n</code></pre>\n\n<p>can probably be</p>\n\n<pre><code>HashableItems = Iterable[\n Tuple[Hashable, Any]\n]\n# ...\n\ndef __init__(self, items: Optional[HashableItems]=None):\n</code></pre>\n\n<h2>Class method</h2>\n\n<p><code>_rehash</code> and <code>_remove</code> should be <code>@classmethod</code> instead of <code>@staticmethod</code> because they reference <code>HashTable</code>, which can be replaced with <code>cls</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T16:36:55.993", "Id": "477131", "Score": "0", "body": "Thank you for your advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:23:03.803", "Id": "242907", "ParentId": "242900", "Score": "3" } } ]
{ "AcceptedAnswerId": "242907", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:42:31.403", "Id": "242900", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "object-oriented", "hash-map" ], "Title": "Implement hash table using linear congruential probing in python" }
242900
<p>I wrote some code to estimate the solution to the following problem:</p> <blockquote> <p>If you break a line segment at two random points, what is the probability that the new line segments can form a triangle?</p> </blockquote> <p>The code is relatively simple, and it works. However, I can't shake the feeling that each of the three functions I've created could be written more &quot;Pythonically.&quot; For example, the first function (<code>can_form_triangle</code>) explicitly writes out the combinations of pairs from <code>(a, b, c)</code> and then compares them to the element of <code>(a, b, c)</code> which is not in the pair. There must be a way to express this more succinctly, more elegantly — more Pythonically.</p> <p>To be clear, I'd just like advice on refactoring the code to be more elegant/Pythonic. I am not looking for advice on how to change the actual functionality to solve the problem more efficiently.</p> <p>Here's the code:</p> <pre><code>#!/usr/bin/python3 from random import random def can_form_triangle(a, b, c): '''Determines if lengths a, b, and c can form a triangle. Args: a, b, c: Number representing the length of a side of a (potential) triangle Returns: True if all pairs from (a, b, c) sum to greater than the third element False otherwise ''' ab = a + b ac = a + c bc = b + c if (ab &gt; c and ac &gt; b and bc &gt; a): return True return False def try_one_triangle(): '''Simulates breaking a line segment at two random points and checks if the segments can form a triangle. Returns: True if the line segments formed by breaking a bigger line segment at two points can form a triangle False otherwise ''' first_point = random() second_point = random() sorted_points = sorted((first_point, second_point)) return can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1]) def estimate_triangle_probability(): num_success = num_attempts = 0 for _ in range(10000000): num_success += 1 if try_one_triangle() else 0 num_attempts += 1 print('Success:', num_success) print('Attempts:', num_attempts) print('Ratio:', num_success / (num_attempts)) if __name__ == '__main__': estimate_triangle_probability() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:01:57.987", "Id": "476732", "Score": "1", "body": "Welcome to CR! In your `can_form_triangle()` you can directly `return ab > c and ac > b and bc > a`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:39:06.923", "Id": "476744", "Score": "1", "body": "@GrajdeanuAlex. you might want to add some more and make that an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T05:41:29.297", "Id": "476792", "Score": "0", "body": "Actually `return ab > c or ac > b or bc > a`" } ]
[ { "body": "<h2>Direct boolean return</h2>\n\n<p>As @Grajdeanu Alex says, this:</p>\n\n<pre><code>if (ab &gt; c and ac &gt; b and bc &gt; a):\n return True\n\nreturn False\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>return ab &gt; c and ac &gt; b and bc &gt; a\n</code></pre>\n\n<h2>Type hints</h2>\n\n<pre><code>def can_form_triangle(a, b, c):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def can_form_triangle(a: float, b: float, c: float) -&gt; bool:\n</code></pre>\n\n<h2>Sort unpack</h2>\n\n<pre><code>first_point = random()\nsecond_point = random()\nsorted_points = sorted((first_point, second_point))\n\nreturn can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1])\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> first_point, second_point = sorted((random(), random()))\n\n return can_form_triangle(first_point, second_point - first_point, 1 - second_point)\n</code></pre>\n\n<h2>Digit triples</h2>\n\n<p>10000000 is more easily read as <code>10_000_000</code>.</p>\n\n<h2>Attempt looping</h2>\n\n<p><code>num_attempts</code> will evaluate to <code>10_000_000</code> so it's not worth tracking unless you add an early-exit mechanism.</p>\n\n<p>The whole loop can be replaced with</p>\n\n<pre><code>num_success = sum(\n 1\n for _ in range(10_000_000)\n if try_one_triangle()\n)\n</code></pre>\n\n<h2>Redundant parentheses</h2>\n\n<pre><code>print('Ratio:', num_success / (num_attempts))\n</code></pre>\n\n<p>does not need the inner parens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:52:41.830", "Id": "476736", "Score": "0", "body": "Exactly what I was looking for! Thank you so much. I didn't know you could write `10000000` as `10_000_000`. That's pretty cool." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:31:35.820", "Id": "476739", "Score": "0", "body": "@JoshClark: [It's Python 3.6+](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep515)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:31:37.220", "Id": "242906", "ParentId": "242902", "Score": "10" } }, { "body": "<p>Quite nicely done. However there is always room for improvement. In order of severity</p>\n\n<h1>Looping</h1>\n\n<p>You do</p>\n\n<pre><code>def estimate_triangle_probability():\n num_success = num_attempts = 0\n for _ in range(10000000):\n num_success += 1 if try_one_triangle() else 0\n num_attempts += 1\n</code></pre>\n\n<p>If you were to need the loop counter inside the loop you would rather do</p>\n\n<pre><code>def estimate_triangle_probability():\n num_success = 0\n for num_attempts in range(10000000):\n num_success += 1 if try_one_triangle() else 0\n</code></pre>\n\n<p>As you do not need the counter inside the loop but using the value after the loop as 'number of runs' you shall do</p>\n\n<pre><code>def estimate_triangle_probability():\n num_success = 0\n num_attempts = 10000000\n for _ in range(num_attempts):\n num_success += 1 if try_one_triangle() else 0\n</code></pre>\n\n<p>Looping with extra counters is very error prone. you should really avoid that.</p>\n\n<p>As we already touch this code we also introduce <code>num_attempts</code> as parameter which gives nice testabilty</p>\n\n<pre><code>def estimate_triangle_probability(num_attempts):\n num_success = 0\n for _ in range(num_attempts):\n num_success += 1 if try_one_triangle() else 0\n</code></pre>\n\n<p>Another minor readability improvement is the ternary if</p>\n\n<pre><code>num_success = 0\nfor _ in range(num_attempts):\n num_success += 1 if try_one_triangle() else 0\n</code></pre>\n\n<p>which in this case is imho more readable in the form</p>\n\n<pre><code>num_success = 0\nfor _ in range(num_attempts):\n if try_one_triangle():\n num_success += 1\n</code></pre>\n\n<p>Differently we can eliminate the explicit loop for a comprehension</p>\n\n<pre><code>num_success = sum(1 for _ in range(num_attempts) if try_one_triangle())\n</code></pre>\n\n<p>So we get rid of the counter initialization and increment.</p>\n\n<h1>Return boolean expressions</h1>\n\n<p>You do</p>\n\n<pre><code>if (ab &gt; c and ac &gt; b and bc &gt; a):\n return True\n\nreturn False\n</code></pre>\n\n<p>which is an 'anti-pattern'. Instead do</p>\n\n<pre><code>return ab &gt; c and ac &gt; b and bc &gt; a\n</code></pre>\n\n<h1>Temporary variables</h1>\n\n<p>You do </p>\n\n<pre><code>ab = a + b\nac = a + c\nbc = b + c\n\nif (ab &gt; c and ac &gt; b and bc &gt; a):\n # ...\n</code></pre>\n\n<p>which has no better readability or documentation. There is nothing wrong with</p>\n\n<pre><code>if a + b &gt; c and a + c &gt; b and b + c &gt; a:\n # ...\n</code></pre>\n\n<p>The same goes for</p>\n\n<pre><code>first_point = random()\nsecond_point = random()\nsorted_points = sorted((first_point, second_point))\nreturn can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1])\n</code></pre>\n\n<p>which may read</p>\n\n<pre><code>sorted_points = sorted(random(), random())\nreturn can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1])\n</code></pre>\n\n<p>There is good reason for temporaries if the name of the temporary serves documentation. Here the names do not add value.</p>\n\n<p>To improve readability of the return expression we do</p>\n\n<pre><code>x, y = sorted((random(), random()))\nreturn can_form_triangle(x, y-x, 1-y)\n</code></pre>\n\n<h1>Overengineered</h1>\n\n<p>After removing unnecessary temporaries the remaining code looks like</p>\n\n<pre><code>#!/usr/bin/python3\n\nfrom random import random\n\n\ndef can_form_triangle(a, b, c):\n \"\"\"Determines if lengths a, b, and c can form a triangle.\n\n Args:\n a, b, c: Number representing the length of a side of a (potential) triangle\n\n Returns:\n True if all pairs from (a, b, c) sum to greater than the third element\n False otherwise\n \"\"\"\n\n return a + b &gt; c and a + c &gt; b and b + c &gt; a\n\n\ndef try_one_triangle():\n \"\"\"Simulates breaking a line segment at two random points and checks if the segments can form a triangle.\n\n Returns:\n True if the line segments formed by breaking a bigger line segment at two points can form a triangle\n False otherwise\n \"\"\"\n\n x, y = sorted((random(), random()))\n return can_form_triangle(x, y-x, 1-y)\n\n\ndef estimate_triangle_probability(num_attempts):\n num_success = sum(1 for _ in range(num_attempts) if try_one_triangle())\n\n print('Success:', num_success)\n print('Attempts:', num_attempts)\n print('Ratio:', num_success / num_attempts)\n\n\nif __name__ == '__main__':\n estimate_triangle_probability(10000000)\n</code></pre>\n\n<p>We notice that most functions have a single line of code. We have docstrings for two one-line helpers but none for the top level <code>estimate_triangle_probability(num_attempts)</code>. If we eliminate the two helpers we get</p>\n\n<pre><code>#!/usr/bin/python3\n\nfrom random import random\n\n\ndef estimate_triangle_probability(num_attempts):\n num_success = 0\n for _ in range(num_attempts):\n # break a line of length 1 two times to get three segments\n x, y = sorted((random(), random()))\n # segments can form a triangle if all are shorter than half the perimeter\n if all(s &lt; 0.5 for s in (x, y-x, 1-y)):\n num_success += 1\n return num_success / num_attempts\n\n\nif __name__ == '__main__':\n num_attempts = 10000000\n ratio = estimate_triangle_probability(num_attempts)\n print('Attempts:', num_attempts)\n print('Ratio:', ratio)\n</code></pre>\n\n<p>Here we also moved output code from the remaining function to main and introduced a return value instead. The final result is is maybe a little too dense for a programming course. Left to do: We could still improve some names. Also the remaining function needs documentation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T07:03:53.653", "Id": "477085", "Score": "0", "body": "Nice answer. In the last code, I would not even do the division,but let the caller worry about that, and just return `num_success` or a tuple `num_success, num_attempts`. You can also use the fact that a `True` counts as `1` when added to an `int` to rewrite the for-loop to `for _ in range(num_attempts):; x, y = sorted((random(), random())); num_success += all(s < 0.5 for s in (x, y-x, 1-y))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T12:22:14.413", "Id": "477103", "Score": "0", "body": "@MaartenFabré: Division - I did the division to fit the name and I actually prefer it like that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T18:53:19.597", "Id": "243075", "ParentId": "242902", "Score": "2" } } ]
{ "AcceptedAnswerId": "242906", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T15:24:50.120", "Id": "242902", "Score": "8", "Tags": [ "python", "mathematics" ], "Title": "Probability that Three Pieces Form a Triangle" }
242902
<p>I made the bellow macro to create a time line in excel.</p> <p>It shows the working days, the week numbers and the month together with the year.</p> <p>First I start with projectstart date and projectend date. As these dates can be any working day and I want my timeline to start on a monday and end on a friday, I find the firstmonday (minus 10 days to give some clearance) and the lastfriday (plus two weeks)</p> <p>I then create an Array containing all the working days in the interval. A collection with the months (mmm-yyyy) and a collection with the number of working days in these months</p> <p>And then I copy the workday range to excel on one line, the week numbers on the line above and the month-year on the line above.</p> <p>Even though it's working, I feel my code is quite messy and that there must be a much better way to do this. Especially the part for the months/year were I create 2 collections in a rather complicated logic and the way I transfer that on my worksheet. So I'd like to simplify this code as much as possible and maybe improve it's performance as it will run every time the starting/ending dates of the project are changing.</p> <p>I tried to make it operational for anyone to test it. All you have to do it name a cell as 'firstday' on the third row of an empty worksheet, resize that row height to 60, resize all the columns width to 2 for better readabylity and run the code.</p> <pre><code>Option Explicit Sub timeaxis() 'create days, weeks, months and years axis + vertical lines and redim the gantt chart area Dim startminus10 As Date, firstmonday As Date, lastfriday As Date, nbofworkdays As Long, axisday() As Date, axismonth As New Collection, axismonthlenght As New Collection Dim projectstart As Date Dim projectend As Date Dim rngday1 As Range Set rngday1 = Range("firstday") projectstart = "25/03/2020" projectend = "31/07/2020" Dim n As Long startminus10 = DateAdd("D", -10, projectstart) firstmonday = startminus10 - (Weekday(startminus10, vbMonday) - 1) lastfriday = DateAdd("D", 19 - Weekday(projectend, vbMonday), projectend) nbofworkdays = WorksheetFunction.NetworkDays(firstmonday, lastfriday) Dim counter As Long counter = 0 '''''Create timeaxis''''' ReDim axisday(nbofworkdays - 1) For n = 0 To nbofworkdays - 1 counter = counter + 1 axisday(n) = WorksheetFunction.WorkDay(firstmonday, n) If n = 0 Then axismonth.Add MonthName(DatePart("m", axisday(n))) &amp; " - " &amp; DatePart("yyyy", axisday(n)) counter = 0 ElseIf n = nbofworkdays - 1 Then axismonthlenght.Add counter + 1 ElseIf MonthName(DatePart("m", axisday(n))) &amp; " - " &amp; DatePart("yyyy", axisday(n)) = axismonth(axismonth.Count) Then 'do nothing Else axismonth.Add MonthName(DatePart("m", axisday(n))) &amp; " - " &amp; DatePart("yyyy", axisday(n)) axismonthlenght.Add counter counter = 0 End If Next 'days With Range(rngday1, rngday1.Offset(0, nbofworkdays - 1)) .Value = axisday .Orientation = 90 .Font.Name = "Calibri" .Font.Size = 10 .Font.Bold = False .NumberFormat = "dd/mm/yyyy" End With 'weeks n = 0 For n = 0 To (nbofworkdays / 5) - 1 With Range(rngday1.Offset(-1, n * 5), rngday1.Offset(-1, (n + 1) * 5 - 1)) .MergeCells = True .Font.Name = "Calibri" .Font.Size = 16 .Font.Bold = True .Font.ThemeColor = xlThemeColorLight1 .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter .NumberFormat = "General" .Value = DatePart("ww", axisday(n * 5 + 1), vbMonday, vbFirstFourDays) End With Next 'month/year With Range(rngday1.Offset(-2, 0), rngday1.Offset(-2, axismonthlenght(1) - 1)) .MergeCells = True .Value = axismonth(1) .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter .Borders(xlEdgeRight).ColorIndex = xlAutomatic End With n = 2 Dim offsetleft As Long Dim offsetright As Long offsetleft = 0 offsetright = 0 For n = 2 To axismonth.Count offsetleft = offsetleft + axismonthlenght(n - 1) offsetright = offsetleft + axismonthlenght(n) - 1 With Range(rngday1.Offset(-2, offsetleft), rngday1.Offset(-2, offsetright)) .MergeCells = True .Value = axismonth(n) .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter .Borders(xlEdgeRight).ColorIndex = xlAutomatic End With Next End Sub </code></pre>
[]
[ { "body": "<p>There are a few things you can do in your coding to improve both the logic and the organization of your application. Your code does work and kudos for already using a memory-based array to speed up the processing of (partially) filling out your date axis. My suggestion solution below does not use <code>Collections</code>, but creates a two-dimensional array for reasons I'll explain.</p>\n\n<p>As a general rule, I try and <a href=\"https://theexcelclub.com/stop-do-not-merge-cells-in-excel-heres-why-with-fixes/\" rel=\"nofollow noreferrer\">avoid merging cells</a> whenever possible. It causes many problems for the user, as well as for writing code. The solution is to <code>Center Across Selection</code>. Because the solution below is based on that concept, the memory-based array can now be created with two dimensions: three rows and N columns. The first two rows will contain many empty cells, which we'll use to our advantage in formatting later.</p>\n\n<p>The next point to make is that I try to separate the logic for creating a data set (or range in this case) from the logic to format the range. If you're careful about it, you can more easily change either how you create the data OR how you format the data without affecting the other. That's the goal anyway. It doesn't always work out quite that cleanly, but it's a philosophy that I attempt to apply whenever I can.</p>\n\n<p>I've done quite a bit of work with the idea of \"working days\". Long ago, I started using Craig Pearson's post for a <a href=\"http://www.cpearson.com/excel/betternetworkdays.aspx\" rel=\"nofollow noreferrer\">Better NetworkDays</a> function. I've included that module below with an added function to determine if a given date <code>IsAWorkDay</code>. </p>\n\n<p>I also try to consistently create an array of holidays to increase the accuracy of whatever calendar calculations I'm making. In the example below, I have created a function to return an array of holidays. This example is hard-coded, but in practice I most often create a table on a (possibly hidden) worksheet. That makes it far easier to update the list of holidays without changing the code.</p>\n\n<p>The second-to-last item to note are to <a href=\"https://stackoverflow.com/a/47902/4717755\">avoid the use of \"magic numbers\"</a>. While you may think your time axis rows will never change -- never say never :)</p>\n\n<p>And my last item is that my usual practice is to create a routine that is based on a <code>Range</code> to use parameters as inputs. This way, I can change where the range will go, i.e. a different sheet or starting in a different column, without re-coding the meat of the logic.</p>\n\n<p>Here is an example module showing code to illustrate the points above:</p>\n\n<pre><code>Option Explicit\n\nPrivate Const MONTH_ROW As Long = 1\nPrivate Const WEEK_ROW As Long = 2\nPrivate Const DATE_ROW As Long = 3\n\nSub test()\n With Sheet1\n '--- clear for testing\n .Range(\"firstday\").Offset(-2, 0).Resize(3, 500).Clear\n\n Dim axisRange As Range\n Set axisRange = CreateTimeAxis(.Range(\"firstday\"), #3/25/2020#, #7/31/2020#)\n FormatTimeAxis axisRange\n End With\nEnd Sub\n\nFunction CreateTimeAxis(ByRef timeAxisAnchor As Range, _\n ByVal start As Date, _\n ByVal finish As Date) As Range\n '--- make sure we account for any company holidays\n Dim holidays As Variant\n holidays = GetCompanyHolidays()\n\n Dim startMinus10 As Date\n Dim firstMonday As Date\n Dim lastFriday As Date\n Dim totalWorkingDays As Long\n startMinus10 = DateAdd(\"D\", -10, start)\n firstMonday = startMinus10 - (Weekday(startMinus10, vbMonday) - 1)\n lastFriday = DateAdd(\"D\", 19 - Weekday(finish, vbMonday), finish)\n totalWorkingDays = NetWorkdays2(firstMonday, lastFriday, Saturday + Sunday, holidays)\n\n '--- create three \"time\" rows:\n ' top row is months\n ' middle row is week number\n ' bottom row is working date\n Dim timeaxis As Variant\n ReDim timeaxis(1 To 3, 1 To totalWorkingDays)\n\n Dim axisDate As Date\n Dim previousMonth As Long\n Dim previousWeek As Long\n Dim i As Long\n i = 1\n For axisDate = firstMonday To lastFriday\n If IsAWorkDay(axisDate, holidays) Then\n '--- if this is a new month, this cell notes the first of the month\n If previousMonth &lt;&gt; Month(axisDate) Then\n timeaxis(MONTH_ROW, i) = DateSerial(Year(axisDate), Month(axisDate), 1)\n previousMonth = Month(axisDate)\n End If\n\n '--- if this is a new week number, this cell notes the new week number\n If previousWeek &lt;&gt; WorksheetFunction.IsoWeekNum(axisDate) Then\n previousWeek = WorksheetFunction.IsoWeekNum(axisDate)\n timeaxis(WEEK_ROW, i) = previousWeek\n End If\n\n '--- each cell on row 3 always gets a date\n timeaxis(DATE_ROW, i) = axisDate\n i = i + 1\n End If\n Next axisDate\n\n '--- copy the time axis to the worksheet at the given range anchor\n Dim axisRange As Range\n Set axisRange = timeAxisAnchor.Offset(-2, 0).Resize(3, totalWorkingDays)\n axisRange.Value = timeaxis\n\n Set CreateTimeAxis = axisRange\nEnd Function\n\nSub FormatTimeAxis(ByRef axisRange As Range)\n Application.ScreenUpdating = False\n\n '--- NOTE: the anchor cell may not be in column 1\n With axisRange\n '--- all rows\n .Font.Name = \"Calibri\"\n\n '--- month row\n .Rows(1).Font.Size = 16\n Dim i As Long\n Dim firstCol As Long\n firstCol = -1\n For i = 0 To (.Columns.Count - 1)\n If Not IsEmpty(.Offset(0, i).Cells(MONTH_ROW, 1)) Then\n If firstCol = -1 Then\n firstCol = i\n Else\n .Offset(0, firstCol).Resize(1, i - firstCol).Select\n Selection.HorizontalAlignment = xlCenterAcrossSelection\n Selection.NumberFormat = \"mmm-yyyy\"\n firstCol = i\n End If\n End If\n Next i\n '--- still (probably) need to center the last month\n .Offset(MONTH_ROW - 1, firstCol).Resize(1, i - firstCol).Select\n Selection.HorizontalAlignment = xlCenterAcrossSelection\n Selection.NumberFormat = \"mmm-yyyy\"\n\n '--- week row\n .Rows(2).Font.Size = 16\n firstCol = -1\n For i = 0 To (.Columns.Count - 1)\n If Not IsEmpty(.Offset(0, i).Cells(WEEK_ROW, 1)) Then\n If firstCol = -1 Then\n firstCol = i\n Else\n .Offset(1, firstCol).Resize(1, i - firstCol).Select\n Selection.HorizontalAlignment = xlCenterAcrossSelection\n Selection.NumberFormat = \"00\"\n End If\n End If\n Next i\n '--- still (probably) need to center the last month\n .Offset(WEEK_ROW - 1, firstCol).Resize(1, i - firstCol).Select\n Selection.HorizontalAlignment = xlCenterAcrossSelection\n Selection.NumberFormat = \"00\"\n\n '--- working date row\n With .Rows(DATE_ROW)\n .Orientation = 90\n .Font.Name = \"Calibri\"\n .Font.Size = 10\n .Font.Bold = False\n .NumberFormat = \"dd/mm/yyyy\"\n .RowHeight = 60#\n End With\n End With\n Application.ScreenUpdating = True\nEnd Sub\n\nPrivate Function GetCompanyHolidays() As Variant\n '--- holidays are hard-coded here, or can be listed on a worksheet and\n ' converted to the returned array (preferred)\n Dim theList As String\n theList = \"1-Jan-2020,12-Apr-2020,13-Apr-2020,1-May-2020,\" &amp; _\n \"8-May-2020,21-May-2020,1-Jun-2020,14-Jul-2020,15-Aug-2020,\" &amp; _\n \"1-Nov-2020,11-Nov-2020,25-Dec-2020\"\n\n Dim holidayList As Variant\n holidayList = Split(theList, \",\")\n\n Dim dateArray As Variant\n ReDim dateArray(1 To UBound(holidayList) + 1)\n\n Dim i As Long\n For i = 1 To UBound(dateArray)\n dateArray(i) = CDate(holidayList(i - 1))\n Next i\n GetCompanyHolidays = dateArray\nEnd Function\n</code></pre>\n\n<p>This is the CalendarSupport module:</p>\n\n<pre><code>'@Folder(\"Libraries\")\nOption Explicit\nOption Compare Text\n\n'--- from: http://www.cpearson.com/excel/betternetworkdays.aspx\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''\n' EDaysOfWeek\n' Days of the week to exclude. This is a bit-field\n' enum, so that its values can be added or OR'd\n' together to specify more than one day. E.g,.\n' to exclude Tuesday and Saturday, use\n' (Tuesday+Saturday), or (Tuesday OR Saturday)\n'''''''''''''''''''''''''''''''''''''''''''''''''''''\nPublic Enum EDaysOfWeek\n Sunday = 1 ' 2 ^ (vbSunday - 1)\n Monday = 2 ' 2 ^ (vbMonday - 1)\n Tuesday = 4 ' 2 ^ (vbTuesday - 1)\n Wednesday = 8 ' 2 ^ (vbWednesday - 1)\n Thursday = 16 ' 2 ^ (vbThursday - 1)\n Friday = 32 ' 2 ^ (vbFriday - 1)\n Saturday = 64 ' 2 ^ (vbSaturday - 1)\nEnd Enum\n\nPublic Function IsAWorkDay(ByRef thisDay As Date, Optional ByRef holidays As Variant) As Boolean\n If IsMissing(holidays) Then\n IsAWorkDay = (Workday2(thisDay - 1, 1, Sunday + Saturday) = thisDay)\n Else\n IsAWorkDay = (Workday2(thisDay - 1, 1, Sunday + Saturday, holidays) = thisDay)\n End If\nEnd Function\n\nPublic Function NetWorkdays2(ByVal StartDate As Date, _\n ByVal EndDate As Date, _\n ByVal ExcludeDaysOfWeek As Long, _\n Optional ByRef holidays As Variant) As Variant\n '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n ' NetWorkdays2\n ' This function calcluates the number of days between StartDate and EndDate\n ' excluding those days of the week specified by ExcludeDaysOfWeek and\n ' optionally excluding dates in Holidays. ExcludeDaysOfWeek is a\n ' value from the table below.\n ' 1 = Sunday = 2 ^ (vbSunday - 1)\n ' 2 = Monday = 2 ^ (vbMonday - 1)\n ' 4 = Tuesday = 2 ^ (vbTuesday - 1)\n ' 8 = Wednesday = 2 ^ (vbWednesday - 1)\n ' 16 = Thursday = 2 ^ (vbThursday - 1)\n ' 32 = Friday = 2 ^ (vbFriday - 1)\n ' 64 = Saturday = 2 ^ (vbSaturday - 1)\n ' To exclude multiple days, add the values in the table together. For example,\n ' to exclude Mondays and Wednesdays, set ExcludeDaysOfWeek to 10 = 8 + 2 =\n ' Monday + Wednesday.\n ' If StartDate is less than or equal to EndDate, the result is positive. If\n ' StartDate is greater than EndDate, the result is negative. If either\n ' StartDate or EndDate is less than or equal to 0, the result is a\n ' #NUM error. If ExcludeDaysOfWeek is less than 0 or greater than or\n ' equal to 127 (all days excluded), the result is a #NUM error.\n ' Holidays is optional and may be a single constant value, an array of values,\n ' or a worksheet range of cells.\n ' This function can be used as a replacement for the NETWORKDAYS worksheet\n ' function. With NETWORKDAYS, the excluded days of week are hard coded\n ' as Saturday and Sunday. You cannot exlcude other days of the week. This\n ' function allows you to exclude any number of days of the week (with the\n ' exception of excluding all days of week), from 0 to 6 days. If\n ' ExcludeDaysOfWeek = 65 (Sunday + Saturday), the result is the same as\n ' NETWORKDAYS.\n '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\n Dim TestDayOfWeek As Long\n Dim TestDate As Date\n Dim Count As Long\n Dim Stp As Long\n Dim Holiday As Variant\n Dim Exclude As Boolean\n\n If ExcludeDaysOfWeek &lt; 0 Or ExcludeDaysOfWeek &gt;= 127 Then\n ' invalid value for ExcludeDaysOfWeek. get out with error.\n NetWorkdays2 = CVErr(xlErrNum)\n Exit Function\n End If\n\n If StartDate &lt;= 0 Or EndDate &lt;= 0 Then\n ' invalid date. get out with error.\n NetWorkdays2 = CVErr(xlErrNum)\n Exit Function\n End If\n\n ' set the value used for the Step in\n ' the For loop.\n If StartDate &lt;= EndDate Then\n Stp = 1\n Else\n Stp = -1\n End If\n\n For TestDate = StartDate To EndDate Step Stp\n ' get the bit pattern of the weekday of TestDate\n TestDayOfWeek = 2 ^ (Weekday(TestDate, vbSunday) - 1)\n If (TestDayOfWeek And ExcludeDaysOfWeek) = 0 Then\n ' do not exclude this day of week\n If IsMissing(holidays) = True Then\n ' count day\n Count = Count + 1\n Else\n Exclude = False\n ' holidays provided. test date for holiday.\n If IsObject(holidays) = True Then\n ' assume Excel.Range\n For Each Holiday In holidays\n If Holiday.Value = TestDate Then\n Exclude = True\n Exit For\n End If\n Next Holiday\n Else\n ' not an Excel.Range\n If IsArray(holidays) = True Then\n For Each Holiday In holidays\n If Int(Holiday) = TestDate Then\n Exclude = True\n Exit For\n End If\n Next Holiday\n Else\n ' not an array or range, assume single value\n If TestDate = holidays Then\n Exclude = True\n End If\n End If\n End If\n If Exclude = False Then\n Count = Count + 1\n End If\n End If\n Else\n ' excluded day of week. do nothing\n End If\n Next TestDate\n ' return the result, positive or negative based on Stp.\n NetWorkdays2 = Count * Stp\n\nEnd Function\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Workday2\n' This is a replacement for the ATP WORKDAY function. It\n' expands on WORKDAY by allowing you to specify any number\n' of days of the week to exclude.\n' StartDate The date on which the period starts.\n' DaysRequired The number of workdays to include\n' in the period.\n' ExcludeDOW The sum of the values in EDaysOfWeek\n' to exclude. E..g, to exclude Tuesday\n' and Saturday, pass Tuesday+Saturday in\n' this parameter.\n' Holidays an array or range of dates to exclude\n' from the period.\n' RESULT: A date that is DaysRequired past\n' StartDate, excluding holidays and\n' excluded days of the week.\n' Because it is possible that combinations of holidays and\n' excluded days of the week could make an end date impossible\n' to determine (e.g., exclude all days of the week), the latest\n' date that will be calculated is StartDate + (10 * DaysRequired).\n' This limit is controlled by the RunawayLoopControl variable.\n' If DaysRequired is less than zero, the result is #VALUE. If\n' the RunawayLoopControl value is exceeded, the result is #VALUE.\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nPublic Function Workday2(ByVal StartDate As Date, _\n ByVal DaysRequired As Long, _\n ByVal ExcludeDOW As EDaysOfWeek, _\n Optional ByRef holidays As Variant) As Variant\n Dim N As Long ' generic counter\n Dim C As Long ' days actually worked\n Dim TestDate As Date ' incrementing date\n Dim HNdx As Long ' holidays index\n Dim CurDOW As EDaysOfWeek ' day of week of TestDate\n Dim IsHoliday As Boolean ' is TestDate a holiday?\n Dim RunawayLoopControl As Long ' prevent infinite looping\n Dim V As Variant ' For Each loop variable for Holidays.\n\n If DaysRequired &lt; 0 Then\n ' day required must be greater than or equal\n ' to zero.\n Workday2 = CVErr(xlErrValue)\n Exit Function\n ElseIf DaysRequired = 0 Then\n Workday2 = StartDate\n Exit Function\n End If\n\n If ExcludeDOW &gt;= (Sunday + Monday + Tuesday + Wednesday + _\n Thursday + Friday + Saturday) Then\n ' all days of week excluded. get out with error.\n Workday2 = CVErr(xlErrValue)\n Exit Function\n End If\n\n ' this prevents an infinite loop which is possible\n ' under certain circumstances.\n RunawayLoopControl = DaysRequired * 10000\n N = 0\n C = 0\n ' loop until the number of actual days worked (C)\n ' is equal to the specified DaysRequired.\n Do Until C = DaysRequired\n N = N + 1\n TestDate = StartDate + N\n CurDOW = 2 ^ (Weekday(TestDate) - 1)\n If (CurDOW And ExcludeDOW) = 0 Then\n ' not excluded day of week. continue.\n IsHoliday = False\n ' test for holidays\n If IsMissing(holidays) = False Then\n For Each V In holidays\n If V = TestDate Then\n IsHoliday = True\n ' TestDate is a holiday. get out and\n ' don't count it.\n Exit For\n End If\n Next V\n End If\n If IsHoliday = False Then\n ' TestDate is not a holiday. Include the date.\n C = C + 1\n End If\n End If\n If N &gt; RunawayLoopControl Then\n ' out of control loop. get out with #VALUE\n Workday2 = CVErr(xlErrValue)\n Exit Function\n End If\n Loop\n ' return the result\n Workday2 = StartDate + N\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T17:39:47.680", "Id": "476836", "Score": "0", "body": "Thank you for taking the time. I really like how you managed to replace my use of the collections by the 2 dimensional array as well as the \"Center Across Selection\" in order to avoid merging cells. Plus it must be more performant. I will definitly implement these.\nRegarding the holidays, I want to keep them in my time line but I can still use the logic in the \"Format\" part of the code to grey them out. I will take the time to thoroughly go through it tomorrow and come back here once I'm done!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T15:17:16.327", "Id": "242958", "ParentId": "242903", "Score": "3" } }, { "body": "<p>This is an answer based on @PeterT 's answer.</p>\n\n<p>So I kept the main logic of your code :</p>\n\n<ul>\n<li>No merging of cells but center across selection</li>\n<li>A 2 dimensional array</li>\n<li>Keep Data and formatting separate</li>\n<li>Removing magic numbers</li>\n</ul>\n\n<p>And I changed a few things : </p>\n\n<ul>\n<li>removed all .select</li>\n<li>I noticed that if I apply \"xlCenterAcrossSelection\" on the whole row it gives the same result</li>\n - \n</ul>\n\n<p>And I came up with the following code :</p>\n\n<pre><code>Option Explicit\n\nSub CreateTimeAxis()\n\n Application.ScreenUpdating = False\n\nConst MONTH_ROW As Long = 1\nConst WEEK_ROW As Long = 2\nConst DATE_ROW As Long = 3\nConst AXIS_ROWS As Long = 3\nConst StartClearance As Long = 10 'Calendar days\nConst FinnishClearance As Long = 19 '2x7 (two weeks) + 5 (Totalworkdays in a week)\nConst Saturday As Long = 6\nConst Friday As Long = 5\n\n'---only for testing\n 'Otherwise these are module private variables defined in the main Sub\n Range(\"firstday\").Offset(-2, 0).Resize(3, 500).Clear\n Dim day1 As Range\n Set day1 = Range(\"firstday\")\n Dim projectstart As Date\n Dim projectend As Date\n projectstart = \"25/03/2020\"\n projectend = \"31/07/2020\"\n\n'--- Compute array and copy to worksheet\n Dim startminus10 As Date\n Dim firstmonday As Date\n Dim lastfriday As Date\n Dim totalWorkingDays As Long\n startminus10 = DateAdd(\"D\", -StartClearance, projectstart)\n firstmonday = startminus10 - (Weekday(startminus10, vbMonday) - 1)\n lastfriday = DateAdd(\"D\", FinnishClearance - Weekday(projectend, vbMonday), projectend)\n totalWorkingDays = WorksheetFunction.NetworkDays(firstmonday, lastfriday)\n\n\n '--- create three \"time\" rows:\n ' top row is months\n ' middle row is week number\n ' bottom row is working date\n Dim timeaxis As Variant\n ReDim timeaxis(1 To AXIS_ROWS, 1 To totalWorkingDays)\n\n Dim axisDate As Date\n Dim previousMonth As Long\n Dim previousWeek As Long\n Dim i As Long\n i = 1\n For axisDate = firstmonday To lastfriday\n If Weekday(axisDate, vbMonday) &lt; Saturday Then\n '--- if this is a new month, this cell notes the first of the month\n If previousMonth &lt;&gt; Month(axisDate) Then\n timeaxis(MONTH_ROW, i) = DateSerial(Year(axisDate), Month(axisDate), 1)\n previousMonth = Month(axisDate)\n End If\n\n '--- if this is a new week number, this cell notes the new week number\n If previousWeek &lt;&gt; WorksheetFunction.WeekNum(axisDate) Then\n timeaxis(WEEK_ROW, i) = WorksheetFunction.WeekNum(axisDate)\n previousWeek = timeaxis(WEEK_ROW, i)\n End If\n\n '--- each cell on row 3 always gets a date\n timeaxis(DATE_ROW, i) = axisDate\n i = i + 1\n End If\n Next axisDate\n\n '--- copy the time axis to the worksheet at the given range anchor\n Dim axisRange As Range\n Set axisRange = day1.Offset(1 - AXIS_ROWS, 0).Resize(AXIS_ROWS, totalWorkingDays)\n axisRange.Value = timeaxis\n\n'--- Format axis\n With axisRange\n With .Rows(MONTH_ROW)\n .Font.Name = \"Calibri\"\n .Font.Size = 16\n .HorizontalAlignment = xlCenterAcrossSelection\n .Borders(xlEdgeRight).ColorIndex = xlAutomatic\n .Borders(xlInsideVertical).ColorIndex = xlAutomatic\n .NumberFormat = \"mmm-yyyy\"\n End With\n With .Rows(WEEK_ROW)\n .Font.Name = \"Calibri\"\n .Font.Size = 16\n .Font.Bold = True\n .HorizontalAlignment = xlCenterAcrossSelection\n .Borders(xlEdgeRight).ColorIndex = xlAutomatic\n .Borders(xlInsideVertical).ColorIndex = xlAutomatic\n End With\n With .Rows(DATE_ROW)\n .Orientation = 90\n .Font.Size = 10\n .NumberFormat = \"dd/mm/yyyy\"\n .RowHeight = 60#\n .ColumnWidth = 2#\n .HorizontalAlignment = xlCenter\n End With\n End With\n '--- Borders on DATE_ROW\n For i = 1 To UBound(timeaxis, 2)\n If Weekday(timeaxis(DATE_ROW, i), vbMonday) = Friday Then\n axisRange(DATE_ROW, i).Borders(xlEdgeRight).ColorIndex = xlAutomatic\n End If\n Next\n\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n\n<p>I'm a bit stubborn as I didn't make a routine with parameters as inputs but I think it is not really different as my input are public and defined in the main Sub. Also I kept the native VBA WorkDay / NetWorkDay functions at least for now. But I saved the one you shared for later use if needed</p>\n\n<p>Overall I'm quite happy with the result. It's much cleaner and runs about 4 times faster than my original code. Thanks to you!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T17:27:14.200", "Id": "243018", "ParentId": "242903", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T15:37:10.477", "Id": "242903", "Score": "4", "Tags": [ "performance", "vba", "excel", "macros" ], "Title": "Time axis with working days, weeks numbers, month-year" }
242903
<p>I am writing some code that performs a simple time-history integration solver (Newmark method for structural dynamics) and I looking for some suggestions in how I can improve the performance of my code. Currently, I am calculating a parameter called displacements for many time steps (think on the order of 5,000,000 steps). From profiling the code without using numba it is apparent that the matrix multiplication seems to be slowing down the script in the for-loop. Some details about the input:</p> <p>num_steps = number of time-steps to perform the calculation (5,000,000)</p> <p>dofs = number of degrees of freedom in the system, this also defines the matrix sizes as (dofs, dofs) before this function is called</p> <p>yF = vector of size (num_steps, 1)</p> <p>k_hat_inv, a1, a2, a3 = are all square, symmetric matrices of size (dofs, dofs)</p> <p>vel_const1, vel_const2, vel_const3, acc_const1, acc_const2, acc_const3 = are constant floats</p> <p>disp_save, disp_steps = are all ints</p> <p>For a simple example when dofs = 10 this code runs very quickly (~14s) but as dofs increases to 1280 the run time increases significantly (still running after 1.5 days) and I would like to find some ways to decrease this run time. I have tried running the algorithm using parallel = True and the prange function in Numba but this doesn't provide the correct solution. Are there any other ways that I can improve the performance of this code?</p> <pre><code>@jit(nopython=True, cache=True) def newmark_looper(num_steps, dofs, yF, k_hat_inv, a1, a2, a3, vel_const1, vel_const2, vel_const3, acc_const1, acc_const2, acc_const3, disp_save, disp_steps): # Time-stepping solution as per Chopra, 2017 print(' Time History Started') # Initialize some variables cdisp = np.zeros(dofs-2) cvel = np.zeros(dofs-2) caccel = np.zeros(dofs-2) loading_vec = np.zeros(dofs-2) disp_counter = 0 displacements = np.zeros((dofs-2, disp_steps)) for count in range(num_steps): # Obtain the force for the next time step, i.e i+1 loading_vec[-2] = yF[count+1] # Obtain the force for the next time step, i.e i+1 # P_i_p1 = loading_vec[:, count+1].copy() # Obtain P_i_p1_hat P_i_p1_hat = loading_vec + a1@cdisp + a2@cvel + a3@caccel # Calculate the displacement due to this force, u_i+1 = k_hat_inv * P_i_p1 u_i_p1 = k_hat_inv @ P_i_p1_hat # Calculate the velocity due to this displacement, u_dot_i+1 udot_i_p1 = vel_const1*(u_i_p1-cdisp) + vel_const2*cvel + vel_const3*caccel # Calculate the acceleration due to this displacement, u_2dot_i+1 u2dot_i_p1 = acc_const1*(u_i_p1-cdisp) - acc_const2*cvel - acc_const3*caccel # Get current values for the next step cdisp[:] = u_i_p1 cvel[:] = udot_i_p1 caccel[:] = u2dot_i_p1 # Write the displacement if count % disp_save == 0: disp_counter += 1 displacements[:, disp_counter] = u_i_p1 print(' Time History Analyzed') return displacements </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:20:51.753", "Id": "242905", "Score": "3", "Tags": [ "python", "python-3.x", "matrix", "numba" ], "Title": "Improving Performance of Numba For-Loop and Matrix Multiplication for Time Integration Solver" }
242905
<p>For learning purposes I'm writing a very simple mqueue based file transfer server. Below is a thread function that takes care of an incoming request: </p> <pre><code>static void * handle_client_request(const char *request_string) { char request_pathname[_part_delim_alloc_size], request_fifo_name[_part_delim_alloc_size]; bool parse_ret = parse_mqueue_request_string(request_string, (char *[]) {request_pathname, request_fifo_name}); if(!parse_ret) { fprintf(stderr, PROGNAME ": error parsing mqueue request string: %s\n", request_string); free(request_string); return NULL; } fprintf(stdout, PROGNAME ": received new request: (%s, %s) -- handling\n", request_pathname, request_fifo_name); // open requested file for reading int file_fd = open(request_pathname, O_RDONLY); if(file_fd == -1) { perror(PROGNAME ": error opening requsted file"); free(request_string); return NULL; } // construct full FIFO path char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1]; strcpy(full_fifo_path, FIFO_STORAGE_PATH); strncat(full_fifo_path, request_fifo_name, 11); // open FIFO for writing only -- this may block until client also opens the FIFO int fifo_fd = open(full_fifo_path, O_WRONLY); if(fifo_fd == -1) { perror(PROGNAME ": failed opening FIFO for writing"); close(file_fd); free(request_string); return NULL; } void *buf = malloc(DEFAULT_BUFSIZE); // 128 KiB, 2^17 bytes if(!buf) { perror(PROGNAME ": failed allocating buffer"); close(file_fd); close(fifo_fd); free(request_string); return NULL; } size_t bread; while((bread = read(file_fd, buf, DEFAULT_BUFSIZE)) &gt; 0) { // read call complete, "bread" bytes are now in "buf" ssize_t bwritten = write(fifo_fd, buf, bread); if(bwritten == -1) { // failed writing the batch of bytes received fprintf(stderr, PROGNAME ": failed writing to FIFO - request aborted (%s): %s\n", full_fifo_path, strerror(errno)); free(buf); free(request_string); close(file_fd); close(fifo_fd); return NULL; } /* fprintf(stdout, PROGNAME ": read %lu bytes of data and wrote %ld bytes of data\n", bread, bwritten); */ } fprintf(stdout, PROGNAME ": done processing request (%s, %s) last bread: %lu\n", request_pathname, request_fifo_name, bread); close(file_fd); close(fifo_fd); free(buf); return NULL; } </code></pre> <p>Its purpose is to transfer a local file (that the client requests) over a FIFO that the client connects to.</p> <p>The size of the buffer for <code>read(2)</code> and <code>write(2)</code> I've decided on is 128KiB. Increasing it doesn't seem to have an positive effect on performance.</p> <p>I am wondering - are there any trivial (or not so trivial) optimizations I could apply to this function to gain an ever so slight increase in performance?</p>
[]
[ { "body": "<h2>Const</h2>\n\n<p>I consider</p>\n\n<pre><code>const char *request_string\n</code></pre>\n\n<p>and </p>\n\n<pre><code>free(request_string);\n</code></pre>\n\n<p>to be in conflict. If the contract for this function is that it is responsible for freeing the string it was given, it should not be <code>const</code>. Conversely, if you really think it should be <code>const</code>, shift responsibility of freeing it onto the caller.</p>\n\n<h2>Stack allocation</h2>\n\n<p>In C terms, support for dynamic stack allocation of the kind seen in </p>\n\n<pre><code>char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1];\n</code></pre>\n\n<p>is relatively new. If I were you I would be concerned that a hostile caller could pass a huge string in <code>request_string</code>, which parses into a huge <code>request_fifo_name</code> and blows the stack. As long as you take care to free the memory yourself through the various <code>return</code> paths in this function, I would consider <code>malloc</code> safer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:36:43.627", "Id": "476769", "Score": "0", "body": "In this particular case the maximum allowed length of `request_string` is set as a runtime parameter, although it cannot exceed linux's maximum `mqueue` message length (`8192` bytes), which is still far less than the stack size. Still a good idea to switch to malloc though, will definitely do that! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:40:58.940", "Id": "242913", "ParentId": "242910", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T17:56:29.660", "Id": "242910", "Score": "1", "Tags": [ "c", "linux" ], "Title": "Further optimization of file transfer over FIFO on linux?" }
242910
<p>Last night I had to build dropdown for the menu on the website that I'm working on. As I'm still React newbie I first looked if there is some package for what I'm trying to achieve but there wasn't, so I had to try to build it on my own.</p> <p>So the menu has its menu items, whichever is hovered it should show its content and so on. The one thing I'm concered about is that I used too much code for the dropdown and I'm sure this can be built with less code. So I only want you to tell me what should be changed in a code and which approach isn't good from my side.</p> <p><strong>Object:</strong></p> <pre><code>const options = [ { index: '1', label: 'Title 1', links: [ 'demo link', 'demo link', 'demo link', 'demo link', ], image: 'imageURL', }, { index: '2', label: 'Title 2', links: [ 'demo link', 'demo link', 'demo link', 'demo link', ], image: 'imageURL', }, { index: '3', label: 'Title 3', image: 'imageURL', }, ]; </code></pre> <p><strong>Code:</strong></p> <pre><code>import React, { Component } from 'react'; import classNames from 'classnames'; import css from './demo.css'; const list = options =&gt; { return options.map(option =&gt; ({ index: option.index, label: option.label, links: option.links, })); }; class SecondaryNav extends Component { constructor(props) { super(props); this.onMouseEnter = this.onMouseEnter.bind(this); this.onMouseLeave = this.onMouseLeave.bind(this); this.state = { hideDropdown: true, dropdownIndex: null, activeLabel: null, columns: null, }; } onMouseEnter(index, label, links) { if (links != null) { this.setState({ hideDropdown: false, dropdownIndex: index, activeLabel: label, columns: links.length, }); } else { this.setState({ hideDropdown: true, dropdownIndex: null, activeLabel: null, columns: null, }); } } onMouseLeave() { this.setState({ hideDropdown: true, dropdownIndex: null, activeLabel: null, columns: null, }); } render() { // Form object array and return navigation items const items = list(options); const navItems = items.map(item =&gt; { const index = item.index; const label = item.label; const links = item.links; const isActive = item.index === this.state.dropdownIndex ? css.active : null; return ( &lt;li className={isActive} onMouseOver={() =&gt; this.onMouseEnter(index, label, links)} key={item.index} &gt; {item.label} &lt;/li&gt; ); }); // Form array of navigation items that have links const selected = options .filter(option =&gt; option.index === this.state.dropdownIndex) .map(selected =&gt; selected.links); const dropdownLinks = selected[0]; // Define active content in dropdown const activeContent = this.state.dropdownIndex != null &amp;&amp; dropdownLinks.map((label, key) =&gt; &lt;li key={key}&gt;{label}&lt;/li&gt;); // Define list label for the first dropdown const listLabel = this.state.dropdownIndex === '1' ? classNames(css.dropdown, css.listLabel) : css.dropdown; // Put content in two rows const columns = this.state.columns &gt;= 8 ? css.twoColumns : null; // Define dropdown image const dropdownImage = options .filter(image =&gt; image.index === this.state.dropdownIndex) .map((single, key) =&gt; { return &lt;img src={single.image} key={key} alt={this.state.activeLabel} /&gt;; }); // Form dropdown container const dropdown = !this.state.hideDropdown ? ( &lt;div className={css.dropdownContainer}&gt; &lt;h2 className={css.dropdownLabel}&gt;{this.state.activeLabel}&lt;/h2&gt; &lt;div className={css.dropdownContent}&gt; &lt;ul className={classNames(listLabel, columns)}&gt;{activeContent}&lt;/ul&gt; &lt;div className={css.dropdownImage}&gt;{dropdownImage}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) : null; return ( &lt;div className={css.secondaryNav} onMouseLeave={this.onMouseLeave}&gt; &lt;div className={css.navContainer}&gt; &lt;ul className={css.secondNav}&gt;{navItems}&lt;/ul&gt; &lt;/div&gt; {dropdown} &lt;/div&gt; ); } } export default SecondaryNav; </code></pre> <p>So everything works as I wanted and as I said I'm just concered that I haven't used good aproaches as I'm still a newbie. So any suggestion will mean a lot.</p>
[]
[ { "body": "<p>Your code is not too bad for one claiming to be a react newbie. I see only a few minor things I'd suggest cleaning or tightening up.</p>\n<ol>\n<li><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself (DRY Principle) with regards to object property accesses</li>\n<li>Consistent use of <code>===</code></li>\n</ol>\n<p>Using object destructing and object shorthand <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">property definitions</a>, and directly return the map result.</p>\n<pre><code>const list = (options) =&gt;\n options.map(({ index, label, links }) =&gt; ({\n index,\n label,\n links\n }));\n</code></pre>\n<p>Convert <code>onMouseEnter</code> and <code>onMouseLeave</code> to arrow functions. This allows you to drop the constructor as they will have <code>this</code> of the react class bound auto-magically. State can be declared a class property.</p>\n<p>Explicitly check <code>links !== null</code></p>\n<pre><code>class SecondaryNav extends Component {\n state = {\n hideDropdown: true,\n dropdownIndex: null,\n activeLabel: null,\n columns: null,\n };\n\n onMouseEnter = (index, label, links) =&gt; {\n this.setState(\n links !== null\n ? {\n hideDropdown: false,\n dropdownIndex: index,\n activeLabel: label,\n columns: links.length\n }\n : {\n hideDropdown: true,\n dropdownIndex: null,\n activeLabel: null,\n columns: null\n }\n );\n };\n\n onMouseLeave = () =&gt; {\n this.setState({\n hideDropdown: true,\n dropdownIndex: null,\n activeLabel: null,\n columns: null,\n });\n };\n</code></pre>\n<p>Destructure state values and object properties. Consistent use of <code>===</code>/<code>!==</code>. Move the conditional render of the dropdown container and use logical and (<code>&amp;&amp;</code>) as react will ignore the false value if <code>!hideDropdown</code> evaluates to false.</p>\n<pre><code>render() {\n const { activeLabel, columns, dropdownIndex, hideDropdown } = this.state;\n\n // Form object array and return navigation items\n const items = list(options);\n const navItems = items.map(({ index, label, links }) =&gt; {\n const isActive = index === dropdownIndex ? css.active : null;\n return (\n &lt;li\n className={isActive}\n onMouseOver={() =&gt; this.onMouseEnter(index, label, links)}\n key={index}\n &gt;\n {label}\n &lt;/li&gt;\n );\n });\n\n // Form array of navigation items that have links\n const selected = options\n .filter((option) =&gt; option.index === dropdownIndex)\n .map((selected) =&gt; selected.links);\n const dropdownLinks = selected[0];\n\n // Define active content in dropdown\n const activeContent =\n dropdownIndex !== null &amp;&amp;\n dropdownLinks.map((label, key) =&gt; &lt;li key={key}&gt;{label}&lt;/li&gt;);\n\n // Define list label for the first dropdown\n const listLabel =\n dropdownIndex === &quot;1&quot;\n ? classNames(css.dropdown, css.listLabel)\n : css.dropdown;\n\n // Put content in two rows\n const columnsStyle = columns &gt;= 8 ? css.twoColumns : null;\n\n // Define dropdown image\n const dropdownImage = options\n .filter(({ index }) =&gt; index === dropdownIndex)\n .map((single, key) =&gt; (\n &lt;img src={single.image} key={key} alt={activeLabel} /&gt;\n ));\n\n return (\n &lt;div className={css.secondaryNav} onMouseLeave={this.onMouseLeave}&gt;\n &lt;div className={css.navContainer}&gt;\n &lt;ul className={css.secondNav}&gt;{navItems}&lt;/ul&gt;\n &lt;/div&gt;\n {!hideDropdown &amp;&amp; (\n &lt;div className={css.dropdownContainer}&gt;\n &lt;h2 className={css.dropdownLabel}&gt;{activeLabel}&lt;/h2&gt;\n &lt;div className={css.dropdownContent}&gt;\n &lt;ul className={classNames(listLabel, columnsStyle)}&gt;\n {activeContent}\n &lt;/ul&gt;\n &lt;div className={css.dropdownImage}&gt;{dropdownImage}&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n )}\n &lt;/div&gt;\n );\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T07:05:20.390", "Id": "247645", "ParentId": "242911", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T18:01:14.277", "Id": "242911", "Score": "5", "Tags": [ "javascript", "html", "css", "react.js" ], "Title": "Custom react dropdown" }
242911
<p>I'm doing a little more grad school, and for a group project I wanted us to be able to quickly share and update our project, so I coded up a Python script to handle that. As usual, I'm proud of the work, but I'm here for you to tear it to shreds again.</p> <p>First, the imports, some globals, and the main:</p> <pre class="lang-py prettyprint-override"><code>import time from subprocess import run from pathlib import Path from datetime import datetime from shlex import split WD = Path.home() / 'project_name' SERVEDIR = Path('/var/www/main/project_name') def main(): while True: just_built = False try: if git_pull(): print('pulled at', datetime.now()) build() print('built at', datetime.now()) move() list_index() just_built = True except Exception as error: print(repr(error)) print('polled at ', datetime.now()) if not just_built: time.sleep(5 * 60) </code></pre> <p>The main function outlines the work of the script. The <code>just_built</code> variable ensures that if we just built the project (probably more than 5 minutes to do) we don't sleep for another 5 minutes, we first do another <code>git_pull()</code>. The <code>try</code> wasn't really used, but it would keep the script running if there was an problem encountered. The rest is straightforward.</p> <p>The <code>WD</code> is the working directory where the git repo resides. To make this work I did have to chown the serving subdirectory to my user from root.</p> <p>As a matter of style, I prefer to put my main function at the top - it's where the outline or table of contents <em>should</em> go, right? It calls the following functions in the rest of the script:</p> <pre><code>def git_pull(): proc = run(split("git pull --verbose"), cwd=WD, capture_output=True) print(proc.stdout) return b"Already up to date." not in proc.stdout def build(): run(split('nix-shell --pure --command "make all"'), cwd=WD) def move(): timestamp = datetime.now().isoformat(timespec="minutes", sep=" ") new_name = f'project{timestamp}.' for ext in ('pdf', 'html'): new = SERVEDIR / (new_name + ext) (WD / f'project.{ext}').rename(new) symlink = SERVEDIR / f'project.{ext}' symlink.unlink(missing_ok=True) symlink.symlink_to(new) def list_index(): files = sorted(SERVEDIR.iterdir()) files = [f'&lt;a href="{f.name}"&gt;{f.name}&lt;/a&gt;' for f in files if 'project' in f.name] index = SERVEDIR / 'index.html' index.write_text('\n&lt;br&gt;\n'.join(files)) if __name__ == '__main__': main() </code></pre> <p>To sum up, I poll every 5 minutes with <code>git pull</code> and if we don't pull down anything, we don't build. I do this under the presumption that git has the best API to check to see if there's anything to do. Yes I could have used github webhooks instead of polling, but I'm not set up to accept POSTs yet (and not sure I want to expose that functionality yet...) and besides, github didn't complain.</p> <p>To build, it calls <code>'nix-shell --pure --command "make all"'</code>. To sum up, Nix ensures the requirements (via <code>shell.nix</code>, at the bottom) and then make runs the <code>all</code> in my makefile:</p> <pre><code>.PHONY : all all: Rscript -e 'rmarkdown::render("project.Rmd", "all")' </code></pre> <p>In spite of calling <code>rmarkdown::render</code> one time, it seems to re-run all the R code twice.</p> <p>The upsides are all I had to do to kick off a build was </p> <pre><code>git commit -ac "descriptive comment" &amp;&amp; git push </code></pre> <p>(and then pull, reconcile, merge any changes, and re-push, if it's necessary.)</p> <p>Other features:</p> <ul> <li>retain every build (quick output comparisons, see image below), listed in <code>index.html</code></li> <li>canonical link points to the latest build (quick collaboration)</li> <li>lots of builds every day (fast iteration)</li> <li>updates merge early and often (continuously integrate)</li> <li>simple, easy to maintain Python</li> </ul> <p><a href="https://i.stack.imgur.com/iKOWG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iKOWG.png" alt="webpage with list of directory contents including symlink from canonical name to last build"></a></p> <p>One downside of this approach versus alternatives is that I had to have a user shell open and running it. I could have detached via tmux, but... I didn't. I'm locked down at home anyways, so no big deal.</p> <p>Other downsides: </p> <ul> <li>no unit tests or types checked with mypy</li> <li>no style checking</li> <li>not represented by any kind of reusable object model, just functions written in a very side-effect-y way - like a script.</li> </ul> <h2>Alternatives</h2> <p>I could have written this as a shell script, but I'm not an expert on shell substitution rules (yet). That might be a good response - how to do this with a shell script. I doubt we'd get noticeable improvements in performance or stability with a shell script, though.</p> <p>I could have used a cron job to run this every 5 minutes (without the while loop) but that seemed like unnecessary configuration fiddling, with the problem of which user to run under as well (a user with minimal perms, naturally).</p> <p>I could have also used Jenkins (which I will eventually get set up with regardless) but I didn't have the time to set it up, and until I do some version of this script will work fine.</p> <h2>shell.nix</h2> <p>Here's my shell.nix file, which ensures my requirements are in-place in the environment (i.e. in my PATH file) before building the project. I'm using NixOS on this server, so Nix is a natural choice for this purpose:</p> <pre><code>{ pkgs ? import &lt;nixpkgs&gt; {} }: with pkgs; mkShell { buildInputs = [ texlive.combined.scheme-full entr ncurses # for tput tree R pandoc rPackages.choroplethr rPackages.rmarkdown rPackages.nycflights13 rPackages.viridis rPackages.tidyverse rPackages.ALSM rPackages.nortest rPackages.alr4 rPackages.lmtest rPackages.EnvStats rPackages.GGally ]; shellHook = '' source ~/.bashrc || source /etc/bashrc ''; } </code></pre> <p>This all built an Rmarkdown file that's also the work of others, so we can't show that here.</p> <p>The question is, how do I improve my code?</p>
[]
[ { "body": "<h2>Great Code &amp; Question</h2>\n\n<p>Your codes look great and you seem to be a Python master already, but I would just raise a very minor issue that I'm not even myself good at it (not to mention that I'm not really a code reviewer and <a href=\"https://codereview.stackexchange.com/a/242935/190910\">here is a good review</a>). </p>\n\n<h2>You can certainly improve on naming your variables much better:</h2>\n\n<ul>\n<li><code>just_built</code>, maybe <code>realtime_built</code> or <code>near_realtime_built</code> could be easier to understand. </li>\n<li><code>new_name</code>, I guess <code>updated_project_name</code> might be closer. </li>\n<li><code>index</code> for instance could be <code>index_html</code>, or maybe something better.</li>\n<li><code>files</code></li>\n<li><code>list_index</code>, maybe <code>get_index_htmls</code> might be a bit elaborative. </li>\n</ul>\n\n<p>are some examples. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:59:25.937", "Id": "476774", "Score": "1", "body": "I appreciate the naming feedback. Could you make suggestions for replacements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T00:08:43.510", "Id": "476782", "Score": "2", "body": "if you're going on an upvote spree on my content here, please stop, the system will just roll back the votes..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:43:36.360", "Id": "242924", "ParentId": "242916", "Score": "2" } }, { "body": "<blockquote>\n<p>I could have used a cron job to run this every 5 minutes (without the while loop) but that seemed like unnecessary configuration fiddling, with the problem of which user to run under as well (a user with minimal perms, naturally).</p>\n</blockquote>\n<p>Instead of <code>cron</code>, you can register this as a <code>systemd</code> service with a <a href=\"https://wiki.archlinux.org/index.php/Systemd/Timers\" rel=\"nofollow noreferrer\"><code>timer</code></a>. This elevates the timing out of the Python script and enhances control over timing tenfold. You can then work with return codes of the Python script for further action (e.g. <code>Restart</code> and <code>RestartSec=300</code> keywords). This can get rid of the currently awkward <code>try</code>/<code>except</code> blocks and the helper <code>just_built</code>.</p>\n<p>NixOS seems to have the <a href=\"https://nixos.wiki/wiki/Nix_Cookbook\" rel=\"nofollow noreferrer\">capability</a> (under <em>Creating Periodic Services</em>).</p>\n<p>At the end, you have a clear and clean Python script that does not have to be kept alive continuously and does one thing well. Further, you leave the timing and success handling to a facility that is much better at it than a <code>time.sleep</code> can hope to be.</p>\n<p>The overhead configuration is not a lot; you seem to have more scripting experience than me, and I managed just fine. To get you started, the <code>systemd.service</code> file can be:</p>\n<pre class=\"lang-yaml prettyprint-override\"><code>[Unit]\nDescription=Build git project continuously\n\n[Service]\n# Type=oneshot is default\nType=oneshot\n\n# User= is required to find ~/.ssh for GitHub.\n# Otherwise, User=root is default, which will fail to find keys\nUser=&lt;user&gt;\n\nWorkingDirectory=/home/&lt;user&gt;/path/to/repo\n\nExecStart=/usr/bin/python3 -m &lt;your module/package&gt;\n</code></pre>\n<p>You can even play with things like <code>ExecStartPre=/usr/bin/git pull</code> to separate out the <code>git pull</code> part, which seems more natural as a <code>systemd</code> command than in a Python script (since there, it requires <code>run</code>, <code>split</code>, ...).</p>\n<p>More info on the <code>.service</code> syntax is found <a href=\"https://www.freedesktop.org/software/systemd/man/systemd.service.html\" rel=\"nofollow noreferrer\">here</a>, and <a href=\"https://www.freedesktop.org/software/systemd/man/systemd.time.html\" rel=\"nofollow noreferrer\">here</a> is more info for the <code>.timer</code> syntax.</p>\n<hr />\n<p>As a second thought, the <code>git_pull</code> function does not seem terribly robust.\nA quick check reveals that a <code>git pull</code> when already up-to-date returns <code>0</code> (which is fine, but not useful here), which is probably why you implemented the function the way you did.\nBut what if that status message string ever changes?</p>\n<p>A different approach is found <a href=\"https://stackoverflow.com/a/3278427/11477374\">here</a>, and put into your code, it can look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from subprocess import run\nfrom shlex import split\nfrom pathlib import Path\n\nWD = Path.cwd()\n\ndef git_pull(work_dir):\n # Instead of lambda, maybe use functools.partial:\n cwd_run = lambda cmd: run(split(cmd), cwd=work_dir, capture_output=True)\n\n cwd_run(&quot;git remote update&quot;)\n current_branch_short = &quot;@&quot;\n upstream_branch_short = &quot;@{u}&quot;\n current_branch_hash = cwd_run(f&quot;git rev-parse {current_branch_short}&quot;).stdout\n upstream_branch_hash = cwd_run(f&quot;git rev-parse {upstream_branch_short}&quot;).stdout\n\n branches_diverged = current_branch_hash != upstream_branch_hash\n if branches_diverged:\n cwd_run(&quot;git pull&quot;)\n return branches_diverged\n\ngit_pull(work_dir=WD)\n</code></pre>\n<p>This is more robust in the sense that it does not rely on a specific string in <code>stdout</code>.\nHowever, it has two distinct disadvantages:</p>\n<ol>\n<li><p>It polls the remote twice; once to update, once to actually pull. This overhead is probably not a lot.</p>\n</li>\n<li><p>The test can only check if branches have diverged, but not in which direction. If your local is ahead, the test passes as <code>True</code> and <code>git pull</code> is triggered, which does not make sense. Since this is run on your server that only ever pulls in changes and never has local ones, it is probably fine. In that case, a branch diversion is always equal to a remote change that requires a <code>pull</code>.</p>\n<p>In the link above, this disadvantage is solved using <code>git merge-base @ @{u}</code>, yielding a <em>base</em> at which the branches have diverged. So if implemented correctly/fully (not necessary for your case), it is not really a disadvantage.</p>\n</li>\n</ol>\n<p>See if this can work for you, since it is not a strict (no downsides) improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T08:52:09.193", "Id": "242935", "ParentId": "242916", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T19:57:26.837", "Id": "242916", "Score": "4", "Tags": [ "python" ], "Title": "Python script for ad-hoc continuous integration from Github to publish for a small group of collaborators" }
242916
<p>Please review my code for the performance and correctness, everything works and we get visible wifi access points by opening <code>http://esp8266_ip_addres/hotspots</code> except on refresh the values gets duplicated. and does not reset as I have done in the else block.</p> <pre><code>#include &lt;ESP8266WebServer.h&gt; #define HTTP_REST_PORT 80 #define WIFI_RETRY_DELAY 500 #define MAX_WIFI_INIT_RETRY 50 const char* wifi_ssid = "router_ssid"; const char* wifi_passwd = "ssid_password"; int mn; ESP8266WebServer http_rest_server(HTTP_REST_PORT); const int numParams = 20; String params [numParams]; String string = "['Please Select'"; String toString(String my_array[], int size) { for (int i = 0; i &lt; size; i++) { string = string + ", '" + my_array[i] + "'"; } return string + "]"; } int init_wifi() { int retries = 0; Serial.println("Connecting to WiFi AP.........."); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_passwd); // check the status of WiFi connection to be WL_CONNECTED while ((WiFi.status() != WL_CONNECTED) &amp;&amp; (retries &lt; MAX_WIFI_INIT_RETRY)) { retries++; delay(WIFI_RETRY_DELAY); Serial.print("#"); } return WiFi.status(); // return the WiFi connection status } void readParams(String (&amp; params) [numParams]) { for (int i = 0; i &lt; mn; i++) { params [i] = WiFi.SSID(i).c_str(); } } int store_mn = 0; String results; void listHotspots() { if (mn != store_mn) { results = toString(params, mn); store_mn = mn; } else { mn = WiFi.scanNetworks(); // this is not resetting as expected params[0] = (String)0; // this is not resetting as expected readParams (params); // after reseting I expected to be new values of params results = toString(params, mn); store_mn = mn; } http_rest_server.send(200, "application/json", results); } void config_rest_server_routing() { http_rest_server.on("/", HTTP_GET, []() { http_rest_server.send(200, "text/html", "Welcome to the ESP8266 REST Web Server"); }); http_rest_server.on("/hotspots", HTTP_GET, listHotspots); } void setup(void) { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.disconnect(); mn = WiFi.scanNetworks(); // scan for hotspots for the first time. readParams (params); WiFi.scanDelete(); if (init_wifi() == WL_CONNECTED) { Serial.print("Connetted to "); Serial.print(wifi_ssid); Serial.print("--- IP: "); Serial.println(WiFi.localIP()); } else { Serial.print("Error connecting to: "); Serial.println(wifi_ssid); } config_rest_server_routing(); http_rest_server.begin(); Serial.println("HTTP REST Server Started"); } void loop(void) { http_rest_server.handleClient(); } </code></pre> <p>Thank You.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T23:24:26.077", "Id": "476874", "Score": "2", "body": "Since this code does not work as expected, it is off-topic on this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T23:25:11.737", "Id": "476875", "Score": "1", "body": "Hint: `string` should be a local variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T16:26:39.293", "Id": "476932", "Score": "1", "body": "\"Working code\" doesn't mean it just compiles & runs, it also means code that *works as intended* - fixing your refresh logic is outside the scope of this site, please see [help/on-topic]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T20:35:29.950", "Id": "242917", "Score": "3", "Tags": [ "performance", "c", "embedded", "arduino" ], "Title": "esp8266 code for correctness of reset and overall performance" }
242917
<p>I am working on a hobby project implementing a card game server with scotty and websockets.</p> <p>The implementation of the game itself is more or less done. Now i am working on the server and I have an idea on how to structure it. Since I have never seen this approach anywhere, I am unsure whether I am missing something or there are problems I will probably run into.</p> <p>The basic idea is to have a separate thread for each game and the server itself only handles the creation of games and users joining.</p> <p>The types look something like this:</p> <pre class="lang-hs prettyprint-override"><code>newtype ServerState = ServerState (TVar (Map GameID Game)) data Game = Game { threadID :: ThreadId , putEvent :: TMVar Event } data Event = UserAction UserID Action | UserJoin User data User = User { name :: String , getAction :: IO Action , putMessage :: Message -&gt; IO () } </code></pre> <p>Each game thread would run in a loop, waiting for events (from the users or the Server), update the gamestate and send the new state to the users.</p> <p>The scotty server looks something like this:</p> <pre class="lang-hs prettyprint-override"><code> post "/newgame" $ do gameID &lt;- liftAndCatchIO $ createGame state json gameID createGame :: ServerState -&gt; IO GameID createGame (ServerState var) = do gameID &lt;- newGameID game &lt;- newGame atomically $ modifyTVar var (Map.insert gameID game) return gameID newGame :: IO Game newGame = do mvar &lt;- newEmptyTMVarIO thread &lt;- forkIO $ gameThread mvar-- start game thread return Game { threadID = thread, putEvent = \e -&gt; atomically (putTMVar mvar e) } </code></pre> <p>and websocket connections get handled like this:</p> <pre class="lang-hs prettyprint-override"><code>wsServer :: ServerState -&gt; ServerApp wsServer (ServerState var) pending = do connection &lt;- acceptRequest pending msg &lt;- receiveData connection case decode msg of Nothing -&gt; sendClose connection ("invalid join request" :: Text) Just j -&gt; do let user = .., gameID = .. game &lt;- Map.lookup gameID &lt;$&gt; readTVarIO var case game of Just g -&gt; putEvent game $ UserJoin User Nothing -&gt; return () </code></pre> <p>I already tested this with 1-2 games and it worked fine, but there is still a lot of work to do and i would like to know whether this approach is a dead end or will get complicated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T21:03:12.963", "Id": "242920", "Score": "1", "Tags": [ "haskell", "websocket" ], "Title": "Feedback on Haskell game server" }
242920
<p>I'm currently implementing a Minesweeper clone in Java using Swing. Rather than updating the tiles like so </p> <pre class="lang-java prettyprint-override"><code> @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (int row = 0; row &lt; rows; row++ ) { for (int column = 0; column &lt; columns; column++) { //Update each tile here... } } } </code></pre> <p>I've created a method that's called when the user clicks a game tile</p> <pre class="lang-java prettyprint-override"><code> public void updatePanel(int r, int c) { int state = 0; //In this case, recursive reveal happens so every tile needs to be checked if(frame.getModel().determineAdjacent(r, c) == 0) { for (int row = 0; row &lt; rows; row++) { for (int column = 0; column &lt; columns; column++) { state = frame.getModel().getState(row, column); updateTileImage(row, column, state); } } } //Otherwise, only one tile needs to be updated else { updateTileImage(r, c, frame.getModel().getState(r, c)); } //Display all mines if the player loses if (frame.getModel().isGameOver() &amp;&amp; frame.getModel().getMineCount() &gt; 0) { for (int row = 0; row &lt; rows; row++ ) { for (int column = 0; column &lt; columns; column++) { //If the tile flagged isn't a mine, display the falsely flagged mine image if (!frame.getModel().isMine(row, column) &amp;&amp; frame.getModel().getState(row, column) == MineBoard.FLAGGED) { tiles[row][column].setImage(falselyFlagged, IMAGE_SIZE, IMAGE_SIZE); } //Otherwise, if the tile is a mine and is not flagged, display the mine else if (frame.getModel().isMine(row, column) &amp;&amp; frame.getModel().getState(row, column) != MineBoard.FLAGGED) { tiles[row][column].setImage(mine, IMAGE_SIZE, IMAGE_SIZE); } } } //Update the clicked tile to display that it was the opened mine tiles[r][c].setImage(openedMine, IMAGE_SIZE, IMAGE_SIZE); JOptionPane.showMessageDialog(null, "Game Over. Mines Remaining: " + frame.getModel().getMineCount()); } //Otherwise, print out a method indicating the player's success else if (frame.getModel().isGameOver() &amp;&amp; frame.getModel().getMineCount() == 0) { JOptionPane.showMessageDialog(null, "You Win!"); } repaint(); } </code></pre> <p>This method is called here </p> <pre class="lang-java prettyprint-override"><code>public class GameButton extends JButton { private static final long serialVersionUID = 3942095583293438553L; public GameButton(MineFrame frame, int row, int col) { super(); this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (!frame.getModel().isGameOver()) { //Left-Click if (e.getButton() == 1) { frame.getModel().reveal(row, col); } //Right-Click else if (e.getButton() == 3) { switch (frame.getModel().getState(row, col)) { case MineBoard.HIDDEN_TILE: frame.getModel().flag(row, col); break; case MineBoard.FLAGGED: frame.getModel().question(row, col); break; case MineBoard.QUESTION: frame.getModel().hide(row, col); break; } } //Update the contents of the panel to reflect changes frame.getPanel().updatePanel(row, col); } } }); } </code></pre> <p>Furthermore, the constructor for MinePanel</p> <pre class="lang-java prettyprint-override"><code>public MinePanel(MineFrame frame) { super(); this.frame = frame; rows = frame.getModel().getRows(); columns = frame.getModel().getColumns(); tiles = new GameButton[rows][columns]; iconsList = initalizeImageList(); grid = new GridLayout(rows,columns); setLayout(grid); for (int x = 0; x &lt; rows; x++) { for (int y = 0; y &lt; columns; y++) { GameButton tile = new GameButton(frame, x, y); tiles[x][y] = tile; add(tile); updateTileImage(x, y, frame.getModel().getState(x, y)); } } repaint(); } </code></pre> <p>I initially implemented it this way as a means of being efficient and from my point of view it works perfectly, but is there anything inherently wrong with it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T22:31:24.473", "Id": "242925", "Score": "2", "Tags": [ "java", "swing" ], "Title": "Is it bad practice to update Graphics in Swing outside of paintComponent like this?" }
242925
<p>I've a scenario where 10K+ regular expressions are stored in a table along with various other columns and this needs to be joined against an incoming dataset. Initially I was using "spark sql rlike" method as below and it was able to hold the load until incoming record counts were less than 50K</p> <p><em>PS: The regular expression reference data is a broadcasted dataset.</em></p> <p><code>dataset.join(regexDataset.value, expr("input_column rlike regular_exp_column")</code></p> <p>Then I wrote a custom UDF to transform them using Scala native regex search as below,</p> <ol> <li>Below val collects the reference data as Array of tuples. </li> </ol> <pre><code>val regexPreCalcArray: Array[(Int, Regex)] = { regexDataset.value .select( "col_1", "regex_column") .collect .map(row =&gt; (row.get(0).asInstanceOf[Int],row.get(1).toString.r)) } </code></pre> <p>Implementation of Regex matching UDF,</p> <pre><code> def findMatchingPatterns(regexDSArray: Array[(Int,Regex)]): UserDefinedFunction = { udf((input_column: String) =&gt; { for { text &lt;- Option(input_column) matches = regexDSArray.filter(regexDSValue =&gt; if (regexDSValue._2.findFirstIn(text).isEmpty) false else true) if matches.nonEmpty } yield matches.map(x =&gt; x._1).min }, IntegerType) } </code></pre> <p>Joins are done as below, where a unique ID from reference data will be returned from UDF in case of multiple regex matches and joined against reference data using unique ID to retrieve other columns needed for result,</p> <pre><code>dataset.withColumn("min_unique_id", findMatchingPatterns(regexPreCalcArray)($"input_column")) .join(regexDataset.value, $"min_unique_id" === $"unique_id" , "left") </code></pre> <p>But this too gets very slow with skew in execution [1 executor task runs for a very long time] when record count increases above 1M. Spark suggests not to use UDF as it would degrade the performance, any other best practises I should apply here or if there's a better API for Scala regex match than what I've written here? or any suggestions to do this efficiently would be very helpful. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-27T05:22:49.720", "Id": "498126", "Score": "0", "body": "Do you really need to use regex? What is the actual purpose of the regexes? How complex are they? How does one regex differ from another?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-27T05:24:01.133", "Id": "498127", "Score": "0", "body": "Do the regexes fall into certain \"categories\" where you might be able to group the incoming data into several categories, so that you can break it up?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T00:12:37.470", "Id": "242927", "Score": "2", "Tags": [ "sql", "regex", "scala", "join", "apache-spark" ], "Title": "Spark Scala: SQL rlike vs Custom UDF" }
242927
<p>Used classes to make this simple tic tac toe game.</p> <p>Any improvements? </p> <pre><code>from itertools import chain class Field: def __init__(self, sequence): self.sequence = sequence self.rows = [[sequence[i] for i in range(j, j + 3)] for j in range(0, 9, 3)] self.columns = [[row[i] for row in self.rows] for i in range(3)] self.first_diagonal = self.rows[0][0] + self.rows[1][1] + self.rows[2][2] self.second_diagonal = self.rows[0][2] + self.rows[1][1] + self.rows[2][0] self.diagonals = [self.first_diagonal, self.second_diagonal] def __str__(self): return '''\ --------- | {} {} {} | | {} {} {} | | {} {} {} | ---------\ '''.format(*self.sequence) def get_value(self, x, y): return self.rows[x][y] def set_value(self, x, y, value): self.rows[x][y] = value sequence = ''.join(list(chain.from_iterable(self.rows))) self.__init__(sequence) # Reinitializing attributes. def get_state(self): num_x = self.sequence.lower().count('x') num_o = self.sequence.lower().count('o') if abs(num_x - num_o) not in {0, 1}: return 'Impossible' winners = [] for sequence in chain(self.rows, self.columns, self.diagonals): if len(set(sequence)) == 1: if sequence[0] not in winners and sequence[0].lower() in ['x', 'o']: winners.append(sequence[0]) if len(winners) &gt; 1: return 'Impossible' elif winners: return f'{winners[0]} wins' # No winner else: if '_' in self.sequence or ' ' in self.sequence: return 'Game not finished' else: return 'Draw' def convert_index(x, y): x, y = abs(y - 3), x - 1 return x, y def make_move(field, move, value): try: x, y = move.split() except ValueError: print('You should enter numbers!') return False if x.isnumeric() and y.isnumeric(): x, y = int(x), int(y) if x in {1, 2, 3} and y in {1, 2, 3}: x, y = convert_index(x, y) if field.get_value(x, y).lower() not in ['x', 'o']: field.set_value(x, y, value) return True else: print('This cell is occupied! Choose another one!') else: print('Coordinates should be from 1 to 3!') else: print('You should enter numbers!') return False field = Field('_' * 9) # Empty field. i = 1 while True: print(field) player = 'X' if i % 2 == 1 else 'O' ordinates = input() if make_move(field, ordinates, player): # Only change player if a move was successful i += 1 if field.get_state() not in ['Game not finished', 'Impossible']: print(field) print(field.get_state()) break <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Input</h2>\n<p>One thing I would suggest is provide a hint to the user about the format of their coordinates input. It's not immediately obvious that the format should be <code>x y</code>. I had to look at the code to figure that out. Intuitively, one might expect to type in <code>x</code> and <code>y</code> on separate lines or maybe separate them with a comma.</p>\n<p>One way to deal with this is to add a string in the input function, so rather than:</p>\n<p><code>ordinates = input()</code></p>\n<p>you could do something like:</p>\n<p><code>ordinates = input(&quot;Please enter your coordinates (example: 1 2): &quot;)</code></p>\n<p>Better yet, it would be easier to deal with only individual <code>x</code> and <code>y</code> coordinates throughout the program, rather than mixing them with strings combining the two. For this, you would simply ask for the two coordinates with separate <code>input()</code> statements (e.g. <code>input(&quot;Enter your x: &quot;</code>, <code>input(&quot;Enter your y: &quot;)</code>). Then you don't have to worry about splitting strings or unpacking tuples or anything or the sort.</p>\n<h2>Coordinates</h2>\n<p>Another point is that the vertical coordinates seem to be backwards, in that the 1st row is at the bottom and the 3rd row at the top. Again it would make the game more user friendly to either specify this to the user or rearrange the grid array so that [1, 1] is top left and [3, 3] is bottom right.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T11:21:10.783", "Id": "242939", "ParentId": "242929", "Score": "0" } } ]
{ "AcceptedAnswerId": "242939", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T06:56:24.303", "Id": "242929", "Score": "0", "Tags": [ "python" ], "Title": "Two player tic tac toe Python" }
242929
<h2>Question:- Why is this code so ugly ??</h2> <p>This is my first code, it is working fine, but I feel it doesn't looks as standard code … I am still studying java through youtube, as I have just completed two topics language fundamentals and operators and assignments in java.<br /> I have tried to create code that calculates loan on particular date and at particular rate of interest, it takes user inputs. Please Run This Code At Your IDE.</p> <p>I have created this code by just knowing two topics or say first two chapters of basic java.</p> <pre><code> package learningJava; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner (System.in); System.out.println(&quot;if Days is not calculated just type 0&quot;); System.out.print(&quot;Days: &quot;); double day = sc.nextDouble(); if (day&lt;=0) { System.out.println(&quot;Old Year: &quot;); double oldyear = sc.nextDouble(); System.out.println(&quot;Old Month: &quot;); double oldmonth = sc.nextDouble(); System.out.println(&quot;Old Date: &quot;); double olddate = sc.nextDouble(); System.out.println(&quot;New Year: &quot;); double newyear = sc.nextDouble(); System.out.println(&quot;New Month: &quot;); double newmonth = sc.nextDouble(); System.out.println(&quot;New Date: &quot;); double newdate = sc.nextDouble(); day = ((newyear*365)+(newmonth*30)+(newdate))-(((oldyear*365)+(oldmonth*30)+(olddate))); System.out.println(&quot;Days = &quot;+day); System.out.print(&quot;Principle: &quot;); double principle = sc.nextDouble(); System.out.print(&quot;Rate Of Interest: &quot;); double rateofinterest = sc.nextDouble(); double interest = (((principle*(rateofinterest/100))/30)*day); System.out.println(&quot;--------------------------------&quot;); System.out.println(&quot;Interest = Rs &quot; +interest); System.out.println(&quot; &quot;); System.out.println(&quot;Total Amount = Rs &quot; +(principle+interest)); System.out.println(&quot;--------------------------------&quot;); System.out.println(&quot;Thankyou!!&quot;); } else { System.out.print(&quot;Principle: &quot;); double principle = sc.nextDouble(); System.out.print(&quot;Rate Of Interest: &quot;); double rateofinterest = sc.nextDouble(); double interest = (((principle*(rateofinterest/100))/30)*day); System.out.println(&quot;--------------------------------&quot;); System.out.println(&quot;Interest = Rs &quot; +interest); System.out.println(&quot; &quot;); System.out.println(&quot;Total Amount = Rs &quot; +(principle+interest)); System.out.println(&quot;--------------------------------&quot;); System.out.println(&quot;Thankyou!!&quot;); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T08:58:35.223", "Id": "476794", "Score": "6", "body": "Try formatting your code to comply with the Java coding conventions and see how it changes your preception: https://www.oracle.com/technetwork/java/codeconvtoc-136057.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T14:25:00.250", "Id": "476925", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Except the formatting, your code does not looks ugly. It just looks procedural.</p>\n\n<p>Try to create classes for each roles. One that read and write to the console. One to compute the loan. And another to control the flow of your program. </p>\n\n<p>As said by Martin Fowler, <em>\"Any fool can write code that a computer can understand. Good programmers write code that humans can understand.\"</em></p>\n\n<p>\"understand\" is not only about being able to figure what your code does. But also about maintainability and evolvability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T23:34:51.690", "Id": "476876", "Score": "0", "body": "Classes are overkill here. After the 2nd lesson of a tutorial, a few simple methods are already enough to learn. By just defining a few methods, the code can be made much more beautiful already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T06:16:41.333", "Id": "476898", "Score": "0", "body": "You are right. However, @Neeraj say that \"it doesn't looks as standard code\". I assume that \"standard\" means \"production ready\", and such code should be evolvable and testable. Creating classes for each responsibility will increase the testability of his code and introduce extension points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T19:25:17.703", "Id": "476951", "Score": "0", "body": "I don't see how a class is \"better testable\" than a method, in this simple example code. At the beginning of a programmer's career, it's good to take very small steps. Adding classes in this early stage just increases the boilerplate code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T09:09:03.163", "Id": "242936", "ParentId": "242930", "Score": "2" } }, { "body": "<p>it is a bit hard to compare it with \"standard code\" if you only worked through first two chapters ;)</p>\n\n<p>You should consider three principles in the following order:</p>\n\n<ol>\n<li>The code should work</li>\n<li>The code should be readable</li>\n<li>The code should be extendable</li>\n</ol>\n\n<p>Only the 1st is proofable. But maybe not that easy as one might think. Consider <a href=\"https://en.wikipedia.org/wiki/Edge_case\" rel=\"noreferrer\">edge cases</a> and errors. It takes some experience to know them. But usually something like </p>\n\n<ol>\n<li>Boundary values - e.g. 0 for a lower boundary</li>\n<li>Wrong format of parameter e.g. <code>0,5</code> instead of <code>0.5</code> (for english local)</li>\n<li>Input is out of allowed boundary</li>\n</ol>\n\n<p>There are a lot of ways to handle them, like to ask for a new value or to simply abort.</p>\n\n<p>If your code is readable is matter of taste. I prefer short code blocks in methods that are named. Also repeated code should be avoided. \nThat said here is my first concrete suggestion for you: There are common code blocks where you ask the user for a value (<code>System.out.print(...)</code>) and then read the value (<code>sc.nextDouble()</code>). You could combine them to a method, like</p>\n\n<pre><code>private static double askForDouble(String label, Scanner scanner){\n System.out.print(label);\n return scanner.nextDouble();\n}\n</code></pre>\n\n<p>which you can use then instead of every occurance:</p>\n\n<pre><code>System.out.print(\"Days: \");\ndouble day = sc.nextDouble();\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>double day = askForDouble(\"Days: \", sc);\n</code></pre>\n\n<p>I would also put every calculation in separate functions although that would not give any benefit at the moment. But later you could write <a href=\"https://en.wikipedia.org/wiki/Unit_testing\" rel=\"noreferrer\">unit tests</a>.</p>\n\n<p>There are more possible improvements, but you should go on with the tutorials to learn about them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T09:17:10.213", "Id": "242937", "ParentId": "242930", "Score": "5" } }, { "body": "<p>Welcome to CodeReview!</p>\n<p><strong>Style Guide</strong></p>\n<p>You mentioned that you think your code looks &quot;ugly&quot;. This problem can be solved by reading a style guide (<a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">Google Style Guide</a>).</p>\n<p>Some important points:</p>\n<ul>\n<li>Use proper intendation</li>\n<li>Although you can use empty lines to structure your code, it is not useful to have empty lines after every line of code.</li>\n<li>Use useful names (public class Test is not useful). Also you should use camelCase for your variable-names.</li>\n</ul>\n<pre><code>import java.util.Scanner;\n\npublic class LoanCalculator {\n\n public static void main(String[] args) {\n Scanner sc = new Scanner (System.in);\n System.out.println(&quot;if Days is not calculated just type 0&quot;);\n System.out.print(&quot;Days: &quot;);\n double day = sc.nextDouble();\n\n if (day&lt;=0) {\n System.out.println(&quot;Old Year: &quot;);\n double oldYear = sc.nextDouble();\n\n System.out.println(&quot;Old Month: &quot;);\n double oldMonth = sc.nextDouble();\n\n System.out.println(&quot;Old Date: &quot;);\n double oldDate = sc.nextDouble();\n\n System.out.println(&quot;New Year: &quot;);\n double newYear = sc.nextDouble();\n\n System.out.println(&quot;New Month: &quot;);\n double newMonth = sc.nextDouble();\n\n System.out.println(&quot;New Date: &quot;);\n double newDate = sc.nextDouble();\n\n day = ((newYear * 365) + (newMonth * 30)+(newDate)) - (((oldYear * 365) + (oldMonth * 30) + (oldDate)));\n System.out.println(&quot;Days = &quot;+ day);\n System.out.print(&quot;Principle: &quot;);\n double principle = sc.nextDouble();\n System.out.print(&quot;Rate Of Interest: &quot;);\n double rateofinterest = sc.nextDouble();\n double interest = (((principle * (rateofinterest / 100)) / 30) * day);\n System.out.println(&quot;--------------------------------&quot;);\n System.out.println(&quot;Interest = Rs &quot; + interest);\n System.out.println(&quot; &quot;);\n System.out.println(&quot;Total Amount = Rs &quot; + (principle + interest));\n System.out.println(&quot;--------------------------------&quot;);\n System.out.println(&quot;Thank you!!&quot;);\n }\n\n else {\n System.out.print(&quot;Principle: &quot;);\n double principle = sc.nextDouble();\n System.out.print(&quot;Rate Of Interest: &quot;);\n double rateofinterest = sc.nextDouble(); \n double interest = (((principle * (rateofinterest / 100)) / 30) * day);\n System.out.println(&quot;--------------------------------&quot;);\n System.out.println(&quot;Interest = Rs &quot; + interest);\n System.out.println(&quot; &quot;);\n System.out.println(&quot;Total Amount = Rs &quot; + (principle + interest));\n System.out.println(&quot;--------------------------------&quot;);\n System.out.println(&quot;Thankyou!!&quot;);\n }\n }\n}\n</code></pre>\n<p><strong>Code Structure</strong></p>\n<p>To structure your code, it is highly recommended to use methods, especially for code that is used multiple times. One example:</p>\n<pre><code> public static double getInterest(double rateofinterest, double principle, double day) {\n return (((principle * (rateofinterest / 100)) / 30) * day);\n }\n</code></pre>\n<p>Then you can just use <code> double interest = getInterest(rateofinterest, principle, day);</code> in your main-method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T09:32:23.017", "Id": "242938", "ParentId": "242930", "Score": "4" } } ]
{ "AcceptedAnswerId": "242937", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T07:13:27.180", "Id": "242930", "Score": "1", "Tags": [ "java", "beginner" ], "Title": "First Code, But I Feel It Is So Ugly, Can You Explain Why?" }
242930
<p>Here is an implementation of Conway's Game of Life. It is kind of a brute force but it works fine. I have a special question about the method <code>cv::Mat render() const</code>, which renders and returns a <code>cv::Mat</code>. Should I return a reference <code>cv::Mat&amp; render() const</code> or allocate an object on the heap and return the pointer? I would also appreciate any constructive feedback about my coding style (especially about how I handle and access memory), which is very influenced by Java IMO. </p> <pre><code>#include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;opencv2/opencv.hpp&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;random&gt; #include &lt;windows.h&gt; #include &lt;vector&gt; #define UPSAMPLING 10 /** * Generating random number */ inline int random(int bottom, int top) { std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution &lt;std::mt19937::result_type&gt; dist(bottom, top - 1); return dist(rng); } /** * Board game */ class Board { public: std::vector &lt;std::vector&lt;bool&gt;&gt; cells; int width; int height; Board(int width, int height) : width(width), height(height) { this-&gt;cells = std::vector &lt; std::vector &lt; bool &gt;&gt; (height, std::vector&lt;bool&gt;(width, false)); std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution &lt;std::mt19937::result_type&gt; distX(0, width - 1); std::uniform_int_distribution &lt;std::mt19937::result_type&gt; distY(0, height - 1); for (int i = 0; i &lt; (width * height) / 2; i++) { int x = distX(rng); int y = distY(rng); cells[y][x] = true; } } inline int aliveNeighbors(int x, int y) const { int ret = 0; for (int yi = y - 1; yi &lt;= y + 1; yi++) { if ((yi &gt;= 0 &amp;&amp; yi &lt; this-&gt;height)) { for (int xi = x - 1; xi &lt;= x + 1; xi++) { if (xi &gt;= 0 &amp;&amp; xi &lt; this-&gt;width) { if (xi != x || yi != y) { ret += cells[yi][xi]; } } } } } return ret; } void nextRound() { std::vector &lt;std::vector&lt;bool&gt;&gt; ret(this-&gt;height, std::vector&lt;bool&gt;(width, false)); for (auto y = 0UL; y &lt; this-&gt;cells.size(); y++) { for (auto x = 0UL; x &lt; this-&gt;cells[y].size(); x++) { int aliveNs = this-&gt;aliveNeighbors(x, y); if (!cells[y][x]) { if (aliveNs == 3) { ret[y][x] = true; } } else { if (aliveNs &lt; 2 || aliveNs &gt; 3) { ret[y][x] = false; } else { ret[y][x] = true; } } } } this-&gt;cells = ret; } cv::Mat render() const { cv::Mat ret = cv::Mat::zeros(width * UPSAMPLING, height * UPSAMPLING, CV_8UC3); for (auto y = 0UL; y &lt; this-&gt;cells.size(); y++) { for (auto x = 0UL; x &lt; this-&gt;cells[y].size(); x++) { if (cells[y][x]) { cv::Vec3b color(random(0, 255), random(0, 255), random(0, 255)); for (auto kx = 1; kx &lt; UPSAMPLING; kx++) { for (auto ky = 1; ky &lt; UPSAMPLING; ky++) { ret.at&lt;cv::Vec3b&gt;(x * UPSAMPLING + kx, y * UPSAMPLING + ky) = color; } } } } } return ret; } }; int main() { int size = 100; Board board(size, size); cv::namedWindow("Conway game of life", cv::WINDOW_AUTOSIZE); while (cv::waitKey(1) != 27) { auto frame = board.render(); cv::imshow("Conway game of life", board.render()); board.nextRound(); Sleep(100); } cv::destroyAllWindows(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T12:43:31.070", "Id": "476804", "Score": "0", "body": "This seems to be missing the definitions of `HkCluster` and `generateColors`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T12:50:23.977", "Id": "476805", "Score": "0", "body": "@Edward I excluded the definition because it was not relevant for the implementation. However I forget to delete their usages. Thank you" } ]
[ { "body": "<p>This code is neat and easy to read and understand. Good job! Here are some things that may help you improve your program.</p>\n\n<h2>Write portable code</h2>\n\n<p>This code can easily compile and run on Linux as well as Windows with a few small changes. First, eliminate <code>#include &lt;windows.h&gt;</code> because it won't be needed. Next, instead of using <code>Sleep(100)</code> we could use this:</p>\n\n<pre><code> std::this_thread::sleep_for(100ms);\n</code></pre>\n\n<p>That makes it portable, but there's a better way.</p>\n\n<h2>Understand your code libraries</h2>\n\n<p>The <code>cv::waitKey</code> takes as its argument, the number of milliseconds to show the image. So what this means is that you can simply delete the line that says <code>Sleep(100)</code> and change the <code>while</code> loop to this:</p>\n\n<pre><code>while (cv::waitKey(100) != 27) {\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The variable <code>frame</code> in your main code is defined but never used. Since unused variables are a sign of poor code quality, you should seek to eliminate them. Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.</p>\n\n<h2>Use <code>const</code> and <code>constexpr</code> where practical</h2>\n\n<p>It's good that you used a named variable for <code>size</code> in <code>main</code> but it could be improved slightly by also declaring it <code>const</code> or better, <code>constexpr</code>. I'd do the same with the title, rather than repeating the string:</p>\n\n<pre><code>auto constexpr title = \"Conway game of life\";\n</code></pre>\n\n<p>Also the <code>UPSAMPLING</code> constant would be better as a <code>constexpr int</code> rather than a <code>#define</code>. Making that change allows for type checking and costs nothing in terms of runtime performance.</p>\n\n<h2>Use only required <code>#include</code>s</h2>\n\n<p>The code has several <code>#include</code>s that are not needed. This clutters the code and makes it more difficult to read and understand. Only include files that are actually needed. In this case, the only required includes are these:</p>\n\n<pre><code>#include &lt;opencv2/opencv.hpp&gt;\n#include &lt;random&gt;\n#include &lt;vector&gt;\n</code></pre>\n\n<h2>Don't reseed the random number generator more than once</h2>\n\n<p>The program currently constructs and reseeds the random number generator with every call to <code>random</code>. This is really neither necessary nor advisable. Instead, just call it once when the program begins. We can do that by making the first two variables <code>static</code> like this: </p>\n\n<pre><code>inline int random(int bottom, int top) {\n static std::random_device dev;\n static std::mt19937 rng(dev());\n std::uniform_int_distribution &lt;std::mt19937::result_type&gt; dist(bottom, top - 1);\n return dist(rng);\n}\n</code></pre>\n\n<h2>Make data members <code>private</code></h2>\n\n<p>There doesn't appear to be any reason for data members of <code>Board</code> to be public, so best practice is to make them private.</p>\n\n<h2>Simplify expressions</h2>\n\n<p>The code contains some expressions which seem overly verbose. For example, instead of this:</p>\n\n<pre><code>if (!cells[y][x]) {\n if (aliveNs == 3) {\n ret[y][x] = true;\n }\n} else {\n if (aliveNs &lt; 2 || aliveNs &gt; 3) {\n ret[y][x] = false;\n } else {\n ret[y][x] = true;\n }\n}\n</code></pre>\n\n<p>I would write this:</p>\n\n<pre><code>ret[y][x] = (aliveNs == 3) || (aliveNs == 2 &amp;&amp; cells[y][x]);\n</code></pre>\n\n<h2>Use standard library functions</h2>\n\n<p>The constructor for <code>Board</code> is currently this:</p>\n\n<pre><code>Board(int width, int height) : width(width), height(height) {\n this-&gt;cells = std::vector &lt; std::vector &lt; bool &gt;&gt; (height, std::vector&lt;bool&gt;(width, false));\n std::random_device dev;\n std::mt19937 rng(dev());\n std::uniform_int_distribution &lt;std::mt19937::result_type&gt; distX(0, width - 1);\n std::uniform_int_distribution &lt;std::mt19937::result_type&gt; distY(0, height - 1);\n for (int i = 0; i &lt; (width * height) / 2; i++) {\n int x = distX(rng);\n int y = distY(rng);\n cells[y][x] = true;\n }\n}\n</code></pre>\n\n<p>That's not wrong, but it's much more complicated than it needs to be. Here's how I'd write that:</p>\n\n<pre><code>Board(int width, int height, float density = 0.5) : \n width(width),\n height(height),\n cells((width + 2) * (height + 2))\n{\n std::random_device dev;\n std::mt19937 rng(dev());\n std::bernoulli_distribution b(density);\n std::generate(cells.begin(), cells.end(), [&amp;b, &amp;rng](){ return b(rng); });\n}\n</code></pre>\n\n<p>Now instead of explicitly looping, we use <code>std::generate</code> and we use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/bernoulli_distribution\" rel=\"nofollow noreferrer\"><code>std::bernoulli_distribution</code></a> explicitly to show that 50% of the cells should be populated by default, but it's a parameter (<code>density</code>) that may be altered by the caller. I've also changed the member data variable to this:</p>\n\n<pre><code>const unsigned width;\nconst unsigned height;\nstd::vector &lt;bool&gt; cells;\n</code></pre>\n\n<p>By having a single <code>vector</code>, we have a more compact structure. This requires some adjustments to the rest of the code, as shown in the following suggestion.</p>\n\n<h2>Use iterators instead of indexing</h2>\n\n<p>The double array indexing is not a particularly efficent way of traversing a data structure. Better, in my view, would be to use a single dimension array and then use an iterator. For instance, here is how I would write the <code>aliveNeighbors</code> function:</p>\n\n<pre><code>inline int aliveNeighbors(std::vector&lt;bool&gt;::const_iterator it) const {\n static const std::array&lt;int, 8&gt; deltas {\n -2-1-width, -2-width, -2+1-width,\n -1, +1,\n +2-1+width, +2+width, +2+1+width,\n };\n return std::accumulate(deltas.begin(), deltas.end(), 0, [this, it](int neighbors, int delta){\n return neighbors + *(it+delta);\n });\n}\n</code></pre>\n\n<p>This uses a number of things. First, it uses a <code>static const std::array</code> to store the <code>deltas</code> to the neighbors, given an iterator. That is, it allows the program to compute the location of each neighbor. Next, we use <code>std::accumulate</code> to iterate through the <code>deltas</code> and count the neighbors. It uses a <em>lambda</em> as the function to accumulate the neighbor count. There is another implicit feature that helps simplify the code. That feature is the next suggestion.</p>\n\n<h2>Simplify range checking by eliminating the need for it</h2>\n\n<p>The existing <code>aliveNeighbors</code> code does a lot of checking to make sure that all of the checked neighbors are in range. That's much better than not checking and overrunning the bounds of the board, but there's a simpler way to accomplish the same effect. You may have noticed that the initialization of <code>cells</code> above was this:</p>\n\n<pre><code>cells((width + 2) * (height + 2))\n</code></pre>\n\n<p>The purpose for the additional two rows and two columns is to act as a frame around the real board. This allows the <code>aliveNeighbors</code> code above to omit checking because the calling code assures that the iterator is always within the real board. So <code>nextRound()</code> looks like this:</p>\n\n<pre><code>void nextRound() {\n std::vector &lt;bool&gt; ret(cells.size());\n auto src = cells.begin() + 3 + width;\n auto dst = ret.begin() + 3 + width;\n for (auto y{height}; y; --y) {\n for (auto x{width}; x; --x) {\n int aliveNs = aliveNeighbors(src);\n *dst = (aliveNs == 3) || (aliveNs == 2 &amp;&amp; *src); \n ++src;\n ++dst;\n }\n src += 2;\n dst += 2;\n }\n std::swap(cells, ret);\n}\n</code></pre>\n\n<p>The last line uses <code>swap</code> as described in the next suggestion.</p>\n\n<h2>Use <code>swap</code> to replace large data structures</h2>\n\n<p>Unlike Java, C++ requires the programmer to manage memory. While modern C++ makes this mostly fairly painless, there are some aspect to be aware of. This is a slight variation on the <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\"><em>copy-and-swap</em> idiom</a>. Here, the <code>ret</code> is created and then populated, and then swapped with the original <code>cells</code> array. Because <code>ret</code> goes out of scope at the end of the function, the <em>destructor</em> will run. By using <code>swap</code>, the destructor will operate on the previous version of <code>cell</code>, neatly releasing the memory.</p>\n\n<h2>Fix the bug</h2>\n\n<p>In the current version of <code>render</code> we have this code:</p>\n\n<pre><code>cv::Mat ret = cv::Mat::zeros(width * UPSAMPLING, height * UPSAMPLING, CV_8UC3);\n</code></pre>\n\n<p>The problem is that the first two arguments to <code>zeros</code> are <em>rows</em> and <em>columns</em>, so these should be swapped for the code to work correctly for non-square boards. The same reversal is required for the <code>ret.at&lt;&gt;</code> line.</p>\n\n<h2>Thoughts on efficiency</h2>\n\n<p>Since a delay is part of the program, making the program run faster isn't necessarily a goal, but here are some thoughts on efficiency if you wanted to explore this further. First, I realized belatedly that I hadn't answered your question about the return value for <code>Board::render()</code>. In my view, you have it exactly right in the code now. Returning a reference would be an error because, as soon as the function ends and the <code>ret</code> variable goes out of scope, the destructor is called, rendering a reference invalid. When you return <em>by value</em> as the current code has it, notionally, a copy is created. (I say \"notionally\" because most compilers are, in fact, smart enough to implement <a href=\"https://en.cppreference.com/w/cpp/language/copy_elision\" rel=\"nofollow noreferrer\">Named Return Value Optimization (NRVO)</a> to avoid actually making a copy.) Also, while you could allocate on the heap and return a pointer, freeing that memory now becomes another problem. For all of these reasons, I'd say that the way you have it is just right.</p>\n\n<p>However, one option for a possible efficiency gain would be for the <code>Board</code> object to contain two copies of the board and simply keep track of which is the current view within <code>nextRound()</code> and <code>render()</code>. That way instead of reallocating a new one (and destroying one) on each call to <code>nextRound</code>, the program could simply use the same two vectors and simply swap them each loop iteration.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T20:14:50.583", "Id": "476857", "Score": "0", "body": "Thank you very much. I really enjoyed your detailed review which pointed out many things I overlooked. I wish you all the best." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T20:07:03.280", "Id": "242967", "ParentId": "242931", "Score": "5" } } ]
{ "AcceptedAnswerId": "242967", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T07:58:01.817", "Id": "242931", "Score": "3", "Tags": [ "c++", "game-of-life", "opencv" ], "Title": "Conway game of life implemented with C++/OpenCV" }
242931