body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I want to map functions from my functions library (<code>Map</code> called as <code>chain</code>) to input string <code>str</code>. Also that functions (<code>Twitter.removeRT</code>, ...) are regex which replace substrings in input <code>str</code>. I think it is better to save that regex-functions in Map like in my example.</p> <h2>So, the code:</h2> <p>Tail recursion variant</p> <pre><code> def filterTwitter2 (str: String): String = { @scala.annotation.tailrec def recFilter(str: String, chain: Map[String, (String) =&gt; String]): String = { chain.headOption match { case Some(v) =&gt; val filteredString = v._2(str) recFilter(filteredString, chain.tail) case None =&gt; str } } val chain = Map[String,(String) =&gt; String]( "f1"-&gt; Twitter.removeRT, "f2"-&gt; Twitter.removeNickName, "f3"-&gt; Twitter.removeURL, "f6"-&gt; Emoticons.removePunctRepetitions, "f7"-&gt; Emoticons.removeHorizontalEmoticons, "f9"-&gt; Emoticons.normalizeEmoticons, "f10"-&gt; Beautify.removeCharRepetitions, "f12"-&gt; Beautify.removeNSpaces ) recFilter(str, chain) } </code></pre> <p><code>foreach</code> variant</p> <pre><code> def filterTwitter (str: String): String = { var tmp = str val chain = Map[String,(String) =&gt; String]( "f1"-&gt; Twitter.removeRT, "f2"-&gt; Twitter.removeNickName, "f3"-&gt; Twitter.removeURL, "f6"-&gt; Emoticons.removePunctRepetitions, "f7"-&gt; Emoticons.removeHorizontalEmoticons, "f9"-&gt; Emoticons.normalizeEmoticons, "f10"-&gt; Beautify.removeCharRepetitions, "f12"-&gt; Beautify.removeNSpaces ) chain.foreach { case (name, func) =&gt; tmp = func(tmp) } tmp } </code></pre> <h2>So, the questions:</h2> <ol> <li>Is it normal to save functions in map? What can be better for it? </li> <li>What better: tail recursion variant or variant with <code>foreach</code>?</li> <li>Maybe there is any better solution for that problem?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T20:53:04.980", "Id": "483409", "Score": "0", "body": "2nd: In this case `foreach` is very easy to understand, use it. But it will be more clear if you define `var tmp` 1 line before `chain.foreach`." } ]
[ { "body": "<p>You never use your <code>Map</code> to lookup a filter function by its key. If you don't need any of the keys then you don't really need a <code>Map</code>.</p>\n\n<pre><code>def filterTwitter(str :String) :String =\n List(Twitter.removeRT\n ,Twitter.removeNickName\n ,Twitter.removeURL\n ,Emoticons.removePunctRepetitions\n ,Emoticons.removeHorizontalEmoticons\n ,Emoticons.normalizeEmoticons\n ,Beautify.removeCharRepetitions\n ,Beautify.removeNSpaces\n ).foldRight(str)(_(_))\n</code></pre>\n\n<hr>\n\n<h2>EXPLANATION</h2>\n\n<p>The 1st underscore is an element from the <code>List</code> that is being folded. Because this is a fold <strong>Right</strong>, it will start with the last element (<code>removeNSpaces</code>) and work toward the head (<code>removeRT</code>).</p>\n\n<p>The 2nd underscore is the result from the previous invocation and it is being passed as an argument to the filter function. (Actually it's a little more complicated than that, but this is an easy way to think about it.)</p>\n\n<p>So this is what's going down:</p>\n\n<pre><code>removeNSpaces(str) ===&gt; resStr1\nremoveCharRepetitions(resStr1) ===&gt; resStr2\nnormalizeEmoticons(resStr2) ===&gt; resStr3\n. . .\nremoveRT(prevResStr) ===&gt; finalResStr\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T04:44:02.453", "Id": "467116", "Score": "0", "body": "Yes it is, so you here, with `List`, right. Also i will look at `foldRight(str)(_(_))` to understand how it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T06:33:05.693", "Id": "467117", "Score": "1", "body": "It's a syntactic abbreviation of: `foldRight(str){case (f, s) => f(s)}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T21:18:49.740", "Id": "467190", "Score": "0", "body": "can you explain what is 1st underscore in brackets and what is 2nd underscore which in brackets of brackets? as i suppose, 1st - is element of list which in my case is function (like `Twitter.removeRT`), but i can`t understand what that function from list applay in place of 2nd underscore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T07:30:43.563", "Id": "467200", "Score": "1", "body": "@Gudsaf; See my update." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T02:11:10.053", "Id": "238179", "ParentId": "238137", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T20:44:20.683", "Id": "238137", "Score": "2", "Tags": [ "scala", "tail-recursion" ], "Title": "What is better to use for mapping value to Map of functions: tail recursion or foreach?" }
238137
<p>I've written up some code that represents the Mandelbrot set in an, admittedly, quite inefficient way. It probably looks awful due to the fact that I did this completely solo, without any external sources aside from the wiki page. What I was wondering is, how can I, without rewriting it completely, fix my code so that it either runs faster, or is higher definition?</p> <p>Final image: </p> <p><a href="https://i.stack.imgur.com/Aqsnf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aqsnf.png" alt="final image"></a></p> <pre><code>import turtle x = -200 y = 99 RN = -2 i = float(1.0) c = complex(RN+i) win = turtle.Screen() win.setup(400,400) t = turtle.Turtle() t.speed(0) t.penup() t.ht() pattern = [] #this calculates what the color hex value each pixel will be. if the 10th #iteration results in a number greater than 2, then that pixel is outside #of the set. def set_color(RN,pattern,z,c): for v in range(10): z = z**2 + c pattern.append(z) if abs(z) &gt; 3.7918623e+90: t.color("#191970") elif abs(z) &gt; 1.9472705e+45: t.color("#16167F") elif abs(z) &gt; 4.4127888e+22: t.color("#13138F") elif abs(z) &gt; 210066388901: t.color("#10109F") elif abs(z) &gt; 458330: t.color("#0D0DAF") elif abs(z) &gt; 677: t.color("#0B0BBF") elif abs(z) &gt; 26: t.color("#0808CF") elif abs(z) &gt; 5: t.color("#0505DF") elif abs(z) &gt; 2: t.color("#0202EF") elif abs(z) &gt; 1.75: t.color("yellow") elif abs(z) &gt; 1.5: t.color("gold") elif abs(z) &gt; 1.25: t.color("goldenrod") elif abs(z) &gt; 1: t.color("darkgoldenrod") else: t.color("black") #draws the set def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c): #draws line by line, 100 times for e in range(100): t.pendown() #draws one line for e in range(precision): z = 0 set_color(RN,pattern,z,c) pattern = [] RN = float(RN + move_rate) c = complex(RN,i) x = x + check_rate t.setposition(x,y) #sets up values you'll need next row RN = -2.0 i = i-.02 t.penup() x = -200 y = y - 2 t.setposition(x,y) t.penup() #purely decorative black background for the set def borders(): t.color("black") t.setposition(-200,200) t.pendown() t.begin_fill() for i in range(4): t.forward(400) t.right(90) t.end_fill() precision = 400 check_rate = float(400 / precision) move_rate = float(check_rate/100) t.penup() borders() t.setposition(x,y) Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c) </code></pre>
[]
[ { "body": "<p>Wow! That is really slow. I changed <code>range(100)</code> to <code>range(5)</code>, just to get some timing numbers without dying of boredom. So with that as my baseline, let's work on speeding it up.</p>\n\n<h1>set_color</h1>\n\n<pre><code>def set_color(RN,pattern,z,c):\n for v in range(10):\n z = z**2 + c\n pattern.append(z)\n if abs(z) &gt; 3.7918623e+90:\n t.color(\"#191970\")\n elif abs(z) &gt; 1.9472705e+45:\n t.color(\"#16167F\")\n elif abs(z) &gt; 4.4127888e+22:\n t.color(\"#13138F\")\n elif abs(z) &gt; 210066388901:\n t.color(\"#10109F\")\n elif abs(z) &gt; 458330:\n t.color(\"#0D0DAF\")\n elif abs(z) &gt; 677:\n t.color(\"#0B0BBF\")\n elif abs(z) &gt; 26:\n t.color(\"#0808CF\")\n elif abs(z) &gt; 5:\n t.color(\"#0505DF\")\n elif abs(z) &gt; 2:\n t.color(\"#0202EF\")\n elif abs(z) &gt; 1.75:\n t.color(\"yellow\")\n elif abs(z) &gt; 1.5:\n t.color(\"gold\")\n elif abs(z) &gt; 1.25:\n t.color(\"goldenrod\")\n elif abs(z) &gt; 1:\n t.color(\"darkgoldenrod\")\n else:\n t.color(\"black\")\n</code></pre>\n\n<p>The first argument, <code>RN</code>, is not used in this function. So we can omit that, and save a little time not passing a useless argument.</p>\n\n<pre><code> z = 0\n set_color(RN,pattern,z,c)\n pattern = []\n</code></pre>\n\n<p>The second argument, <code>pattern</code>, is being accumulated, and then discarded. So busy work involving memory allocation for extending a list who's value is never used. We can remove that argument and <code>pattern.append(z)</code>.</p>\n\n<p>The third argument, <code>z</code>, is always coming in as zero. No point passing it as an argument; just initialize it inside the <code>set_color</code> function, which will save a little bit of time because we don't pass the extra argument.</p>\n\n<p>Which just leaves passing in the argument <code>c</code>. Getting better.</p>\n\n<p>Then, you have a long string of <code>if abs(z) &gt; #</code> checks. How many times are you computing <code>abs</code> of a complex number? How many times will the result be different? Maybe we can compute it just once?</p>\n\n<pre><code> abs_z = abs(z)\n if z &gt; 3.7918623e+90:\n t.color(\"#191970\")\n elif abs_z &gt; 1.9472705e+45:\n ...\n</code></pre>\n\n<p>Unfortunately, that still leaves an ugly long string of <code>if</code>/<code>elif</code>/<code>elif</code>/<code>else</code> statements. With 14 possibilities, you take an average of 7 tests to determine the correct value; with a binary search, this would reduce to 4. We just need to put the values in a list, and use <a href=\"https://docs.python.org/3/library/bisect.html?highlight=bisect#bisect.bisect\" rel=\"nofollow noreferrer\"><code>bisect.bisect</code></a> to determine where the <code>abs(z)</code> would be inserted in the list.</p>\n\n<pre><code>import bisect\n\nMAG = (1, 1.25, 1.5, 1.75, 2, 5,\n 26, 677, 458330, 210066388901, 4.4127888e+22, 1.9472705e+45,\n 3.7918623e+90)\n\nCOLOR = (\"black\", \"darkgoldenrod\", \"goldenrod\", \"gold\", \"yellow\", \"#0202EF\",\n \"#0505DF\", \"#0808CF\", \"#0B0BBF\", \"#0D0DAF\", \"#10109F\", \"#13138F\",\n \"#16167F\", \"#191970\")\n\ndef set_color(c):\n z = 0\n for _ in range(10):\n z = z**2 + c\n t.color(COLOR[bisect.bisect(MAG, abs(z))])\n</code></pre>\n\n<p>My timing hasn't shown a significant impact in speed yet, but I certainly like the <code>set_color</code> function much better now. If you want to add more colours, it is simply a matter of filling in additional values in the arrays.</p>\n\n<h1>Mandelbrot</h1>\n\n<pre><code>def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c):\n#draws line by line, 100 times\n for e in range(100):\n t.pendown()\n#draws one line\n for e in range(precision):\n set_color(c) # Note: modified for new set_color\n RN = float(RN + move_rate)\n c = complex(RN,i)\n x = x + check_rate\n t.setposition(x,y)\n#sets up values you'll need next row\n RN = -2.0\n i = i-.02\n t.penup()\n x = -200\n y = y - 2\n t.setposition(x,y)\n t.penup()\n</code></pre>\n\n<p>This looks backwards. You pass in <code>RN</code>, but <code>RN</code> is computed in the loop. You pass in <code>x</code>, but <code>x</code> is initialize to <code>-200</code> each time through the loop. You pass in <code>c</code>, but <code>c</code> is computed in the loop. And most things seem to be computed just after they've been used for the next loop iteration!</p>\n\n<p>Let's re-work this, moving calculation to before they are used, and see what it looks like. Along the way, <code>variable = variable + adjustment</code> will be replaced with <code>variable += adjustment</code>, because it results in one less variable lookup in the Python interpreter. Also, <code>RN + move_rate</code> is already a <code>float</code>, so we can omit the redundant <code>float()</code> call. When looping over a range of values (<code>y</code> starting at 99, and going down by two 100 times, a <code>for y in range(...)</code> construct is used:</p>\n\n<pre><code>def mandelbrot(precision, check_rate, move_rate):\n i = 1.0\n t.penup()\n\n for y in range(99, 99 - 2 * 100, -2):\n rn = -2.0\n x = -200\n t.setposition(x, y)\n\n t.pendown()\n for _ in range(precision):\n c = complex(rn, i)\n set_color(c)\n\n rn += move_rate\n x += check_rate\n t.setposition(x, y)\n\n i -= 0.02\n t.penup()\n</code></pre>\n\n<p>Several PEP-8 changes: commas are followed by a space, variable names and method names are lowercase (technically, <code>snake_case</code>). <code>_</code> is used as the unused variable. Operators have a space on each side.</p>\n\n<h1>Main</h1>\n\n<p>Again, <code>float( )</code> calls are unnecessary.</p>\n\n<pre><code>if __name__ == '__main__':\n precision = 400\n check_rate = 400 / precision\n move_rate = check_rate / 100\n\n t.penup()\n borders()\n mandelbrot(precision, check_rate, move_rate)\n</code></pre>\n\n<h1>Speed Up?</h1>\n\n<p>Despite my initial efforts, my very rough timing measurements don't show I've sped things up any. But I do think the code has been cleaned up significantly.</p>\n\n<p>Next step in my efforts will be to split this up into two parts:</p>\n\n<ol>\n<li>computing a grid of Mandelbrot colour index values</li>\n<li>drawing the image (using the computed grid of colour index values) with turtle graphics</li>\n</ol>\n\n<p>Then, I can get more accurate timing information for each section.</p>\n\n<p>Step 1 is open to parallel processing (Python threads won't help, due to the Global Interpreter Lock (GIL), but using processes should help), but that will only help if it is the large consumer of time. I fear it is the turtle graphics.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T18:39:28.470", "Id": "467186", "Score": "0", "body": "Wow! This helps a ton. I'll fix my code to match yours, and see what I can do from there. This is way more intuitive than mine, as my code was done almost completely brute-force. Can't thank you enough! However, in set_color(c), couldn't I just use indices to choose which color value to use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T19:33:09.630", "Id": "467187", "Score": "0", "body": "Just realized that when i plug in the set_color(c) part, it throws me this error:\n\nNotImplementedError: bisect is not yet implemented in Skulpt on line -181\n\nWhy does this happen?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T22:12:45.997", "Id": "467192", "Score": "0", "body": "What is Skulpt? Seems like the bisect module isn't present, which is odd 'cause that is a standard library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T04:33:27.033", "Id": "467196", "Score": "0", "body": "Interesting. I am using a coding website called repl.it, though I don't see why that would change anything, as all other modules I've checked work. I think that Skulpt is an in-browser version of Python, though I have no idea why it would needed in any way for a Python module. I wonder if it says the same thing in IDLE and PyCharm." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T06:29:43.540", "Id": "238185", "ParentId": "238141", "Score": "2" } } ]
{ "AcceptedAnswerId": "238185", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T22:48:18.753", "Id": "238141", "Score": "3", "Tags": [ "python", "performance", "turtle-graphics" ], "Title": "A representation of the Mandelbrot Set" }
238141
<p>I wrote the below code today:</p> <pre><code>class Hosts(object): def __init__(self): super(Hosts, self).__init__() engine, connection = _core.get_engine() self._engine = engine self._connection = connection self._lan_table = self.get_table() def _get_selected_field_value(self, table, fields, col_value=None, limit=1): """Performs select Operation and gets the value of field. Arguments: table (sqlalchemy.Table) : table to select data from. fields (list) : fields whose value to retrieve. col_value (dict) : where column of table has value. """ col_value = col_value or {} stmt = db.select(fields).where( and_(*[ getattr( table.columns, column ) == value for column, value in col_value.items() ]) ).order_by(db.desc(table.columns.id)).limit(limit) _log.debug(stmt) ResultProxy = self._connection.execute(stmt) ResultSet = ResultProxy.fetchall() for item in ResultSet: yield item def _get_user_and_hostname(self): """Gets the hostname of the machine from host table. """ _log.debug("Using table %s", self._lan_table) column_value = {"ip_address": self._ip} return next(self._get_selected_field_value( self._lan_table, [self._lan_table.columns.name, self._lan_table.columns.user], col_value=column_value ), None ) def _get_all(self): limit = self._engine.scalar(self._lan_table.count()) columns = Host.metadata.tables['host'].columns.keys() columns.pop(columns.index("mac_address")) _host = namedtuple("Host", columns) select_fields = [getattr(self._lan_table.columns, column) for column in columns] self._rows = [] for rows in self._get_selected_field_value( self._lan_table, select_fields, limit=limit ): self._rows.append(_host(*rows)) return self._rows def __iter__(self): table_data = self._get_all() return iter(table_data) </code></pre> <p>Here is the <code>self._lan_table</code></p> <pre><code>+-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(250) | NO | | NULL | | | user | varchar(20) | NO | | root | | | ip_address | varchar(18) | NO | UNI | NULL | | | mac_address | varchar(250) | NO | | NULL | | | is_linux | tinyint(1) | NO | | 1 | | +-------------+--------------+------+-----+---------+----------------+ </code></pre> <p><strong>my question</strong> is for the intuitive and pythonic approach and correctness of sqlalchemy !</p> <p>I know when I <code>fetchall</code> it pulls all data at once, however my table has just 12 rows.</p> <p>As is understood the appraoch in code is letting me do this:</p> <pre><code>hosts = Hosts() for item in hosts: print(item) </code></pre> <p><strong>Take the Challenge !</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T21:36:20.560", "Id": "467835", "Score": "0", "body": "What Problem are you trying to solve with this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T21:49:44.370", "Id": "467837", "Score": "0", "body": "Host column fields and their values are available when class object is iterated rather than sqlalchemy object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T21:52:16.670", "Id": "467838", "Score": "0", "body": "your title just seems really lengthy, but I think I get it. if you can make the title shorter you should." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T23:11:54.703", "Id": "238143", "Score": "2", "Tags": [ "python", "python-3.x", "database", "sqlalchemy" ], "Title": "Gathering data using sqlalchemy from database and making it available using simplified namedtuple object in an iterable class" }
238143
<p>I managed to find a way to rotate a slice in-place (<a href="https://stackoverflow.com/questions/60443977">previous question on SO</a>). The slice is linear, but represents a 2d square of elements.</p> <p>Is this approach efficient?</p> <p>Please check the previous question linked above if anything is unclear about the algorithm.</p> <h1>Code</h1> <pre><code>enum Rotation { Clockwise, Counterclockwise, } fn rotate_square_slice&lt;T&gt;(slice: &amp;mut [T], s: usize, rotation: Rotation) { // iterate ringwise, from outer to inner // skip center when size % 2 == 1 for r in 0..s / 2 { // for all unique indices under rotational symmetry ... for i in 0..s - (2 * r) - 1{ // ... get their 4 corresponding positions ... let a = s * ( r ) + r+i ; let b = s * ( r+i ) + s-r-1 ; let c = s * ( s-r-1 ) + s-r-i-1 ; let d = s * (s-r-i-1) + r ; //... and swap them in the correct direction. match rotation { Rotation::Clockwise =&gt; { slice.swap(a, b); slice.swap(a, c); slice.swap(a, d); }, Rotation::Counterclockwise =&gt; { slice.swap(a, b); slice.swap(c, d); slice.swap(b, d); } } } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T01:15:14.550", "Id": "238145", "Score": "2", "Tags": [ "performance", "algorithm", "array", "rust" ], "Title": "Rotational Symmetry Indexing in a 1D “Square” Array" }
238145
<p>I was looking to replace my use of axios with just fetch, but I didn't like how verbose fetch was with regard to handling JSON output (having to have a separate <code>then</code> call just to return the json). Unfortunately calling <code>text()</code> first to see if it's a JSON response and then only calling <code>json()</code> if so seems wasteful because it first has to parse the response as text. If you have a large response payload (as I do in several cases) then double parsing seems inefficient.</p> <p>So this isn't as complex as it could be because I only really need something simple. All of my requests are prefixed with <code>/api/</code> except one that has to call AWS, so I used <code>startsWith</code> for that case. Also, the only time I call <code>PUT</code> in the entire application is when I need to update an AWS resource.</p> <pre><code> initializeRequestFactory = () =&gt; { const prefix = "/api/"; let thenFunction = response =&gt; { // only time response isn't from app server is when it's from AWS // avoid expensive text() call in general case let data = response.ok &amp;&amp; response.url.startsWith("https://s3") ? response.text() : response.json(); if (response.ok) { return data.then(json =&gt; { return { data: json, response: response }; }).catch(err =&gt; { return { response: response }; }); } else { return { response: response }; } }; window.request = { get: url =&gt; { let theUrl = url.startsWith("http") ? url : prefix + url; return fetch(theUrl, { method: "GET", credentials: 'include', headers: { 'sseid': window.globals.sseid } }).then(thenFunction); }, post: (url, body) =&gt; { let theUrl = url.startsWith("http") ? url : prefix + url; return fetch(theUrl, { method: "POST", credentials: 'include', headers: { 'Content-Type': 'application/json', 'sseid': window.globals.sseid }, body: JSON.stringify(body) }).then(thenFunction); }, put: (url, body, config) =&gt; { let theUrl = url.startsWith("http") ? url : prefix + url; return fetch(theUrl, { method: "PUT", credentials: 'omit', headers: config.headers, body: body }).then(thenFunction); } }; } </code></pre> <p>I generally call it like this:</p> <pre><code>window.request.post("reply-to-thread", { thread_id: this.props.data.thread_id }); window.request.get("get-my-profile").then(response =&gt; { this.setState({ profile: response.data }); }); </code></pre> <p>It all seems to work but I was wondering if anyone had any ideas for improvements. Thanks for reading!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T02:25:42.127", "Id": "238146", "Score": "1", "Tags": [ "javascript", "performance", "http" ], "Title": "Short wrapper for fetch (similar to axios)" }
238146
<p>Based on <a href="https://stackoverflow.com/questions/60422866/employee-shift-table-constructing-with-some-criteria-by-days-of-a-month-with">this question</a></p> <p>Thought it was a nice puzzle</p> <p>Main idea: How to randomly assign shifts to employees based on these restrictions:</p> <p>As per the O.P.:</p> <blockquote> <ol> <li>Randomly write to cells "1" or "0"</li> <li>Employees' total shifts in a month can't be more than 7 and less than 4</li> <li>According to a few criteria like "Vacation" or "Definite shift demands"</li> <li>One employee per one day</li> </ol> </blockquote> <p>This is my setup:</p> <p><a href="https://i.stack.imgur.com/KCAF4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KCAF4.png" alt="setup"></a></p> <p><a href="https://1drv.ms/x/s!ArAKssDW3T7wnaEGPKQ05qGS5-9syA" rel="nofollow noreferrer">Link to current workbook</a></p> <p>Note: Open to improvements</p> <p><strong>Code:</strong></p> <pre><code>Option Explicit Sub AssignAllShifts() Dim targetSheet As Worksheet Dim availableRange As Range Dim employeeRange As Range Dim previousRange As Range Dim emptyRange As Range Dim lastRow As Long Dim counter As Long Set targetSheet = ThisWorkbook.Worksheets("tablo") lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row ' For dev... targetSheet.Range("B2:AE" &amp; lastRow).ClearContents targetSheet.Range("C2").Value = "V" targetSheet.Range("I2").Value = "V" targetSheet.Range("N2").Value = "V" targetSheet.Range("D3").Value = "V" targetSheet.Range("E3").Value = "V" targetSheet.Range("F4").Value = "V" For counter = 2 To lastRow ' Get days without shifts assigned Set availableRange = nonEmptyColsInRange(Range("B2:AE" &amp; lastRow)) Set employeeRange = Intersect(targetSheet.Range("B" &amp; counter &amp; ":AE" &amp; counter), availableRange) ' Init random func Randomize AssignShiftsInRange employeeRange Next counter End Sub Private Sub AssignShiftsInRange(ByVal availableRange As Range) Dim cellAddrArray As Variant Dim randomCellPos As Variant Dim totalShifts As Long Dim counter As Long ' Get random value to assign to employee totalShifts = Int((7 - 4 + 1) * Rnd + 4) ' Store range cells' addresses in array cellAddrArray = rangeAddrToArray(availableRange) ' Get x num of cells positions in employe range randomCellPos = randomNumsToArray(totalShifts, 1, availableRange.Cells.Count) ' Choose x random cells addresses For counter = 0 To UBound(randomCellPos) ' Assign 1 to cell address availableRange.Parent.Range(cellAddrArray(randomCellPos(counter))).Value = 1 Next counter End Sub Private Function nonEmptyColsInRange(ByVal sourceRange As Range) As Range Dim column As Range Dim result As Range For Each column In sourceRange.Columns If column.SpecialCells(xlCellTypeBlanks).Count = column.Cells.Count Then If result Is Nothing Then Set result = column Else Set result = Union(result, column) End If End If Next column Set nonEmptyColsInRange = result End Function Private Function rangeAddrToArray(ByVal sourceRange As Range) As Variant Dim cell As Range Dim result As Variant Dim counter As Long ReDim result(sourceRange.Cells.Count) For Each cell In sourceRange.Cells result(counter) = cell.Address counter = counter + 1 Next cell rangeAddrToArray = result End Function Private Function randomNumsToArray(ByVal totalNums As Long, ByVal lowerLimit As Long, ByVal upperLimit As Long) As Variant Dim result As Variant Dim arrayPosition As Long Dim randomNum As Long ReDim result(totalNums - 1) If totalNums &gt;= upperLimit Then Err.Raise 5, , "Minimum shifts is greater than available slots" End If Do randomNum = Int((upperLimit - lowerLimit) * Rnd + lowerLimit) If Not IsNumberInArray(randomNum, result) Then result(arrayPosition) = randomNum arrayPosition = arrayPosition + 1 End If Loop While arrayPosition &lt;= UBound(result) randomNumsToArray = result End Function Private Function IsNumberInArray(ByVal randomNumber As Long, ByVal targetArray As Variant) As Boolean IsNumberInArray = Not IsError(Application.Match(randomNumber, targetArray, 0)) End Function </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T05:52:40.433", "Id": "238147", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Assign random shift with restrictions" }
238147
<p>In the following code, there are some repeated commands. How can I reduce it and make the code more concise and automate it more? In the following code, I am trying to read different folder files. The folders have a fixed kind of structure for all different set of data. I want to access those folders in easier way such that i remove the repeated commands used. Directory + file structure is given as follows</p> <pre><code>main_path ├── Proband28 ├── GAIT ├── FG_Color ├── FG_Depth ├── FG_Results ├── GAITWCOG ├── CB3_Color ├── CB3_Depth ├── CB3_Results ├── Proband29 ├── GAIT ├── FG_Color ├── FG_Depth ├── FG_Results ├── GAITWCOG ├── CB3_Color ├── CB3_Depth ├── CB3_Results ├── Proband30 ... </code></pre> <p>Code is as follows:</p> <pre><code>path2 = "F:/Daten1/" # Give the path of the folder of which the gait parameter is to be calculated. print(path2) print(len([name for name in os.listdir(path2)])) # Gives the number of folders in the directory # ---------------------------------------------------------------------------------------------------------------------- i = 1 for i in range(len([name for name in os.listdir(path2)])-5): ''' The following part of code assign links to the variables with Proband numbers, create the folder if it is not available and later also assigns the list of files available in the folder. For example, lets take color_img color_img is assigned with the path which has multiple Probands. So 'F:/Daten1/' is the path where multiple Probands are available with Proband numbers in sequence. Proband{0} is the place where a particular number will be assigned with the help of i. Here if you want to access Proband1 then you should have .format(i+1). If you want to access Proband28 then you should have .format(i+28). GAITWCOG/CB3_color is the path where color files of the CB3 experiment are stored. The later part of the code creates a folder of CB3_color if it not available. The list of files available in CB3_color is assigned to Pathh1 which is later used for deleting files when 3D Pose estimation is achieved. ''' color_img ='F:/Daten1/Proband{0}\GAITWCOG\CB3_color'.format(i+28) try: os.makedirs(color_img) except FileExistsError: # directory already exists pass pathh1 = os.listdir(color_img) depth_img ='F:/Daten1/Proband{0}\GAITWCOG\CB3_Depth'.format(i+28) try: os.makedirs(depth_img) except FileExistsError: # directory already exists pass pathh2 = os.listdir(depth_img) json = 'F:/Daten1/Proband{0}\GAITWCOG\CB3_color\json'.format(i+28) try: os.makedirs(json) except FileExistsError: # directory already exists pass pathh3 = os.listdir(json) Openpose = 'F:/Daten1/Proband{0}\GAITWCOG/CB3_color/2dOutput/'.format(i+28) twoDOutput = 'F:/Daten1/Proband{0}\GAITWCOG/CB3_color/2dOutput/'.format(i+28) try: os.makedirs(twoDOutput) except FileExistsError: # directory already exists pass pathh4 = os.listdir(twoDOutput) selected_color ='F:/Daten1/Proband{0}\GAITWCOG\CB3_color\selected'.format(i+28) try: os.makedirs(selected_color) except FileExistsError: # directory already exists pass pathh5 = os.listdir(selected_color) selected_depth ='F:/Daten1/Proband{0}\GAITWCOG\CB3_Depth\selected'.format(i+28) try: os.makedirs(selected_depth) except FileExistsError: # directory already exists pass pathh6 = os.listdir(selected_depth) mat = 'F:/Daten1/Proband{0}\GAITWCOG\CB3_color\mat'.format(i+28) try: os.makedirs(mat) except FileExistsError: # directory already exists pass pathh7 = os.listdir(mat) results = 'F:/Daten1/Proband{0}\GAITWCOG\CB3_results'.format(i+28) try: os.makedirs(results) except FileExistsError: # directory already exists pass pathh8 = os.listdir(results) Openpose2D = 'F:/Daten1/Proband{0}\GAITWCOG/CB3_color/2dOutput'.format(i+28) if not os.path.exists('Openpose2D'): os.makedirs('Openpose2D') excel = 'F:\Daten1/Results3\Proband{0}_CB3.xls'.format(i+28) ''' excel is the path where the result of 3D Pose estimation is stored. ''' print(color_img) ''' This part deletes all the generated files to save memory for running the code for next set of folders. ''' for item in pathh1: if item.endswith(".bmp"): os.remove(os.path.join(color_img, item)) for item in pathh2: if item.endswith(".bmp"): os.remove(os.path.join(depth_img, item)) for item in pathh3: if item.endswith(".json"): os.remove(os.path.join(json, item)) for item in pathh4: if item.endswith(".png"): os.remove(os.path.join(twoDOutput, item)) for item in pathh5: if item.endswith(".png"): os.remove(os.path.join(selected_color, item)) for item in pathh6: if item.endswith(".png"): os.remove(os.path.join(selected_depth, item)) for item in pathh7: if item.endswith(".mat"): os.remove(os.path.join(mat, item)) # --------------------------------------------------------------------------------------------------------------------- </code></pre> <ol> <li>In the above code, I am changing the pathname every time to start the loop at all the places like color_img, depth_img, etc and all these have a common part '.../Proband{number}/GAIT/'. So how can I reduce the code and make it in such a way that I give the main folder path and all other paths are assigned automatically? </li> <li>Also in the above program, I also change (i+28), etc every time I start the loop according to the first folder name and number like Proband28, etc. Can I read the first folder name and get the Proband number directly (i.e number 28) and assign that value to a variable b such that the loop automatically starts from i+b?</li> <li>I am currently running two sets of above code in such a way that I always change the path names from GAITWCOG/CB3_color/ to GAIT/FG_color etc to access files of another folder. Is it possible to somehow club both the codes in one file maybe with some if condition?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T11:54:37.040", "Id": "467067", "Score": "5", "body": "To answer this question yourself, you should describe _the purpose_ of the code. What should be the effect of running the code? Explain it to a non-programmer, using no programming terms at all. This explanation should be the introduction of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T19:06:27.940", "Id": "467375", "Score": "0", "body": "Why did you never fix your previous question?" } ]
[ { "body": "<p>First, <code>os.listdir</code> already returns a list, so <code>len(os.listdir(...))</code> is sufficient.</p>\n\n<p>Next, you are mixing <code>\\</code> and <code>/</code> in your file paths. Decide which one you want to use. In any case, you should probably use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib.Path</code></a> so you don't have to worry about compatibility between Windows and Linux anyway and can use the division operator (<code>/</code>) to concatenate paths.</p>\n\n<p><code>os.makedirs</code> has the <code>exist_ok</code> flag which just makes it ignore existing folders.</p>\n\n<p>Finally, you should avoid repetition. All of your paths are almost the same, and need almost the same thing done. So, just put them in a datastructure and iterate over it:</p>\n\n<pre><code>patterns = {'CB3_Depth': '.bmp',\n 'CB3_Depth/selected': '.png',\n 'CB3_color': '.bmp',\n 'CB3_color/2dOutput': '.png',\n 'CB3_color/json': '.json',\n 'CB3_color/mat': '.mat',\n 'CB3_color/selected': '.png',\n 'CB3_results': None}\n\nstart = 28\nend = -5\nfor i in range(start, start + len(os.listdir(path2)) + end):\n base_path = Path(f\"F:/Daten1/Proband{i}/GAITWCOG\")\n excel = Path(f\"F:/Daten1/Results3/Proband{i}_CB3.xls\")\n for path, pattern in patterns.items():\n os.makedirs(base_path / path, exist_ok=True)\n if pattern is not None:\n for file in os.listdir(base_path / path):\n if file.endswith(pattern):\n os.remove(base_path / path / file)\n</code></pre>\n\n<p>Note that I removed the duplicate entry <code>CB3_color/2dOutput</code> and used the relatively recent <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\"><code>f-string</code></a> for the formatting. I also moved setting the offsets into variables, this way you can give them a name and they are not just magic values.</p>\n\n<p>Currently the variable <code>excel</code> is unused.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T22:39:07.610", "Id": "467657", "Score": "0", "body": "Thank you for the answer. This removes lot of duplicates. I have just one more question. In the above code of mine, I assign the paths to a variable like **color_img , pathh1, depth_img** etc. How can I assign those variables in the above code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T00:14:14.417", "Id": "467666", "Score": "0", "body": "@AnkitJaiswal In your code you also don't need it, except for the removing of files. It depends on what you need it for, but in the end we can only give you advice on the code you posted, not anything else you might have that you are not showing us. You could certainly put them into a list, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T07:04:47.757", "Id": "467684", "Score": "0", "body": "Okk. I thought those parts will just confuse everyone so didn't put it. There are some Python functions that have been defined and I m using those variables to pass it as shown in the above code. I have edited the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T12:16:02.683", "Id": "467712", "Score": "4", "body": "@AnkitJaiswal: I'm sorry, but the question and answer nature of this site makes it so that you are not allowed to modify the code after having received any answers. Otherwise it would cause too much confusion in which version of the question answers target. Have a look at [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers). I rolled your edit back for now. You can always ask a new question (referencing this question is encouraged, though). Feel free to incorporate feedback from my answer to avoid hearing the same advice again." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T08:44:25.343", "Id": "238350", "ParentId": "238148", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T07:22:05.493", "Id": "238148", "Score": "4", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Using several file system commands repeatedly. How can the code size be reduced?" }
238148
<p>I'm learning OS development and have written a single stage bootloader that loads the kernel, enters to protected mode and finally jumps to the kernel.</p> <p>I'll very appreciate any feedback and suggestion about the code. I'll be definitely glad to see any suggestions on my build system (<code>Makefile</code> and the linker scripts) and how I can improve it. Should I write two separate <code>Makefile</code>s for both the bootloader and the kernel?</p> <p>You can take a look on the files in the <a href="https://github.com/Eanmos/mia" rel="noreferrer">Github repository</a> if it will be more comfortable.</p> <p><em>Thanks for your time!</em></p> <p><strong><code>src/bootloader/bootloader.s</code></strong>:</p> <pre><code>/* =============================================================================== SECTION .text.bootentry =============================================================================== */ .section .text.bootentry .code16 .global bootentry bootentry: /* When BIOS finds a boot sector, BIOS loads it into memory at * 0x0000:0x7C00, but some BIOSes loads it into memory at 0x07C0:0x0000, * so it is a good practice to enforce CS:IP at the very first part of * a boot sector. * * We can not manually set CS or IP, but we can long jump to the * memory address we need: 0x0000:$bootentry.start. */ jmp $0x0000,$bootentry.start bootentry.start: /* This early execution environment is highly implemetation defined, * meaning the implementation of your particular BIOS. * * So we do not ever make any assumptions on the content of the * registers, so we need to initialize at least the data segment * register because we use it anytime when we access the data in * our code. */ xor %ax, %ax mov %ax, %ds /* We also have to initialize stack since we want to use * procedure calls. * * BIOS memory map description found on the OSDev: * * &lt;https://wiki.osdev.org/Memory_Map_(x86)&gt;. * * states that memory area from 0x500 to 0x7BFF is guarranteed * free to use. So we will use it for our stack. * * Note that we have to set the SS:SP pair back-to-back (no other * instructions in between) because CPU's interruptions can harm * this pair. All x86 processors protect the instruction following * a write to SS from interruption, but some old 8086's had an error * in them requiring us to use CLI/STI as a protection. * * We do not target on old infamous 8086's, so we rely that the * processor does the protection itself. */ mov %ax, %ss mov $0x7C00, %sp /* The only thing that is certain after the boot sector is loaded is * that the DL registers holds the drive code from where the boot * sector was loaded. We need to keep it for later usage. */ mov %dl, boot_drive /* Read the second sector from the floopy disk that contains our * boot sector and place it into the memory address 0x0000:0x8000. * * TODO: check if reading failed. */ xor %ax, %ax mov %ax, %es mov $0x8000, %bx mov (boot_drive), %dl mov $0x0, %dh mov $0x2, %cl mov $0x0, %ch mov $0x3, %al call read_sectors_from_floppy /* Check whenever A20 line is already enabled or not. * * TODO: enable A20 line if it is disabled. */ call check_a20 test %al, %al jne bootentry.a20_is_disabled /* Clear interrupts, load the Global Descriptor Table (GDT) and * switch to the protected mode by setting the first bit of the CR0 register. */ cli lgdt (gdtr) mov %cr0, %eax or $0x1, %eax mov %eax, %cr0 /* We are in protected mode now. We need to clear the instructions pipeline * that contains garbage 16-bit instructions. To clear the pipeline we * need to only make a far jump. * * $0x8 is the offset of our second descriptor in the GDT since the first * descriptor is the reserved null-descriptor. Thus, it is our code segment. */ jmp $0x08, $bootentry.clear_pipe .code32 bootentry.clear_pipe: /* We have to setup the segment register with our data segment (the third * GDT's entry, in our case, with offset 0x10). */ mov $0x10, %ax mov %ax, %ds mov %ax, %es mov %ax, %fs mov %ax, %gs /* Setup the stack: */ mov %ax, %ss mov $0x7C000, %esp /* And jump to the kernel. We will never return from there. */ call 0x8000 /* But… if we actually somehow return from the kernel * halt the CPU. */ bootentry.hang32: hlt jmp bootentry.hang32 .code16 /* If the A20 line is disabled, print a message about it and * halt the CPU. */ bootentry.a20_is_disabled: mov $a20_is_disabled, %si call print_string_in_teletype_mode bootentry.hang: hlt jmp bootentry.hang /* =============================================================================== SECTION .data =============================================================================== */ .section .data .global a20_is_disabled .global boot_drive .global gdt .global gdt_null_segment_descriptor .global gdt_code_segment_descriptor .global gdt_data_segment_descriptor .global gdt_end a20_is_disabled: .asciz "A20 is disabled. Halt the CPU." boot_drive: .byte 0x00 /* All the GDT descriptors was generated by a tool found at the OSDev Wiki: * * &lt;https://wiki.osdev.org/GDT_Tutorial&gt;. * * The GDT_CODE_PL0 and GDT_DATA_PL0 presets was used. * * This is the simplest, «Basic Flat Model», memory model. Both segment * descriptors have the same base address value of 0 and the same segment * limit of 4 GByte space. * * This memory model is detaily described in Intel's manual: Volume 3, * Chapter 3. */ gdt: gdt_null_segment_descriptor: .quad 0x0000000000000000 gdt_code_segment_descriptor: .quad 0x00CF9A000000FFFF gdt_data_segment_descriptor: .quad 0x00CF92000000FFFF gdt_end: gdtr: .word gdt_end - gdt - 1 .long gdt /* =============================================================================== SECTION .text =============================================================================== */ .section .text .code16 .global print_string_in_teletype_mode .global read_sectors_from_floppy .global check_a20 .equ BIOS_VIDEO_TELETYPE_OUTPUT, 0x0E .equ BIOS_DISK_READ_SECTORS_INTO_MEMORY, 0x02 /* ======================================= PROCEDURE print_string_in_teletype_mode(str) Description: Prints a null-terminated string that is pointed to by str in BIOS teletype mode to the page #0. Implementation details: The BIOS teletype output has the function code 0xE. It also requires the page number (BH), the color of the character (BL, only in graphic mode) and the character itself (AL). The function is called by calling the 0x13 interrupt while AH contains the function code (0xE). The documentation about this BIOS interrupt can be found at the address &lt;http://www.ctyme.com/intr/rb-0106.htm&gt;. Inputs: - SI = pointer to the C-style string. Returns: Nothing. ======================================= */ print_string_in_teletype_mode: push %ax push %bx cld xor %bh, %bh mov $BIOS_VIDEO_TELETYPE_OUTPUT, %ah print_string_in_teletype_mode.loop: lodsb test %al, %al je print_string_in_teletype_mode.done int $0x10 jmp print_string_in_teletype_mode.loop print_string_in_teletype_mode.done: pop %bx pop %ax ret /* ======================================= PROCEDURE read_sectors_from_floppy(segment, offset, number_of_sectors, cylinder, sector, head, drive) Description: Read sectors from floopy disk to data buffer. Implementation details: BIOS fuction 0x13/0x02 (read sectors into memory) allow to read from the hard drive, but this function can read sectors only from the floppy disks. The documentation for this BIOS function can be found at &lt;http://www.ctyme.com/intr/rb-0607.htm&gt;. This function also doesn't returns additional information if failed. You can use the 0x13/0x01 BIOS function (get status of the last operation) to see what caused the problem. Status codes can be found at &lt;http://www.ctyme.com/intr/rb-0606.htm#Table234&gt;. Inputs: - ES:BX = data buffer. - AL = number_of_sectors (must be nonzero). - CH = cylinder number (0-based). - CL = sector to start reading from (1-based, in range from 1 to 63). - DH = head number (0-based). - DL = drive number. Returns: Returns 0 in AX if successfull and a nonzero value otherwise. ======================================= */ read_sectors_from_floppy: mov $BIOS_DISK_READ_SECTORS_INTO_MEMORY, %ah int $0x13 jc read_sectors_from_floppy.read_error xor %ax, %ax read_sectors_from_floppy.read_error: /* We don't have to explicitly store a nonzero value into AX since * BIOS cares that AH contains the status of the last operation and * it is already nonzero on failure. */ ret /* ======================================= PROCEDURE check_a20() Description: The function tests whether the A20 line is enabled or not. Implementations details: We can check if A20 line is enabled using a simple method: the logical addresses 0x0000:0x0510 and 0xFFFF:0x0500 points to the same 20-bit physical address. So if we place a magic byte into one of the address and get the same magic byte from the other address then A20 line is disable because memory wraps around. Otherwise A20 line is enabled. Additional information about A20 line can be found at the address: &lt;https://wiki.osdev.org/A20&gt;. Inputs: Nothing. Returns: Returns 0 (AX) if A20 is enabled and 1 (AX) otherwise. ======================================= */ check_a20: pushf push %ds push %di push %es push %si cli /* DS:DI = 0x0000:0x0510. */ xor %ax, %ax mov %ax, %ds mov $0x510, %di /* ES:SI = 0xFFFF:0x500. */ not %ax mov %ax, %es mov $0x500, %si /* Move bytes at the memory location 0xFFFF:0x500 and 0x0000:0x510 * in order to restore it later. */ movb %ds:(%di), %al push %ax movb %es:(%si), %al push %ax /* And now actually check if memory wraps around: */ movb $0x00, %es:(%si) movb $0xBE, %ds:(%di) cmpb $0xBE, %es:(%si) /* Restore the original memory state: */ pop %ax movb %al, %es:(%si) pop %ax movb %al, %ds:(%di) /* Return the result: */ xor %ax, %ax je check_a20.done inc %ax check_a20.done: pop %si pop %es pop %di pop %ds popf ret </code></pre> <p><strong><code>src/bootloader/bootloader.ld</code></strong>:</p> <pre><code>OUTPUT_FORMAT("binary"); ENTRY(bootentry); SECTIONS { /* BIOS loads the boot sector to the memory address 0x7C00, * so the beginning of our code should be at this position. */ . = 0x7C00; /* The .text.bootentry section will be placed as the first * code of our bootloader. */ .text : SUBALIGN(0) { *(.text.bootentry); *(.text) } .data : SUBALIGN(0) { *(.data) } /* The special bootloader signature is required by some old * BIOS, so we have to place the special 0xAA55 word at the * end of the boot sector. */ .sig : AT(0x7DFE) { SHORT(0xAA55); } } </code></pre> <p><strong><code>src/kernel/kernel_entry.s</code></strong>:</p> <pre><code> .section .text.kernel_entry .code32 .global kernel_entry .extern kmain kernel_entry: jmp kmain </code></pre> <p><strong><code>src/kernel/kernel.c</code></strong>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdint.h&gt; #include &lt;stddef.h&gt; #define VGA_WIDTH 80 #define VGA_HEIGHT 25 #define VGA_COLOR(fg, bg) ((bg &lt;&lt; 4) | fg) #define VGA_CHAR(ch, fg, bg) ((uint16_t) ((VGA_COLOR(fg, bg) &lt;&lt; 8) | ch)) enum { VGA_COLOR_BLACK = 0, VGA_COLOR_BLUE = 1, VGA_COLOR_GREEN = 2, VGA_COLOR_CYAN = 3, VGA_COLOR_RED = 4, VGA_COLOR_MAGENTA = 5, VGA_COLOR_BROWN = 6, VGA_COLOR_LIGHT_GREY = 7, VGA_COLOR_DARK_GREY = 8, VGA_COLOR_LIGHT_BLUE = 9, VGA_COLOR_LIGHT_GREEN = 10, VGA_COLOR_LIGHT_CYAN = 11, VGA_COLOR_LIGHT_RED = 12, VGA_COLOR_LIGHT_MAGENTA = 13, VGA_COLOR_LIGHT_BROWN = 14, VGA_COLOR_WHITE = 15, }; volatile uint16_t * const VGA_VIDEO_MEMORY = (volatile uint16_t *) 0xB8000; static void clear_screen(void); void kmain(void) { clear_screen(); const char greeting[] = "Hello, World!"; for (size_t i = 0; i &lt; sizeof(greeting) - 1; ++i) VGA_VIDEO_MEMORY[i] = VGA_CHAR(greeting[i], VGA_COLOR_WHITE, VGA_COLOR_BLACK); } void clear_screen(void) { for (size_t i = 0; i &lt; VGA_WIDTH * VGA_HEIGHT; ++i) VGA_VIDEO_MEMORY[i] = VGA_CHAR(' ', VGA_COLOR_WHITE, VGA_COLOR_BLACK); } </code></pre> <p><strong><code>src/kernel/kernel.ld</code></strong>:</p> <pre><code>OUTPUT_FORMAT("binary"); ENTRY(kernel_entry); SECTIONS { /* Our kernel will be loaded by the bootloader into the * memory address 0x8000. */ . = 0x8000; .text : SUBALIGN(0) { *(.text.kernel_entry); *(.text) } .data : { *(.data) } .rodata : { *(.rodata) } .bss : { *(.bss) } } </code></pre> <p><strong><code>Makefile</code></strong>:</p> <pre><code>BUILDDIR = build $(BUILDDIR)/os.bin: $(BUILDDIR)/bootloader.bin $(BUILDDIR)/kernel.bin cat $^ &gt; $@ $(BUILDDIR)/kernel.bin: $(BUILDDIR)/kernel_entry.o $(BUILDDIR)/kernel.o ld -T src/kernel/kernel.ld -melf_i386 -o $@ $^ $(BUILDDIR)/kernel_entry.o: as --32 -o $@ src/kernel/kernel_entry.s $(BUILDDIR)/kernel.o: gcc -ffreestanding -c -m32 -fno-pie -fno-stack-protector -o $@ src/kernel/kernel.c $(BUILDDIR)/bootloader.bin: $(BUILDDIR)/bootloader.o ld -T src/bootloader/bootloader.ld -melf_i386 -o $@ $&lt; $(BUILDDIR)/bootloader.o: as --32 -o $@ src/bootloader/bootloader.s .PHONY = run clean run: $(BUILDDIR)/os.bin qemu-system-i386 -boot order=a -drive file=$&lt;,index=0,if=floppy,format=raw clean: rm -f $(BUILDDIR)/kernel.o $(BUILDDIR)/bootloader.o </code></pre>
[]
[ { "body": "<p>Review of the Makefile:</p>\n\n<ul>\n<li><p>There's no <code>.DELETE_ON_ERROR</code> target. I know of no good reason to write a Makefile without that.</p></li>\n<li><p>Put the makefile in the target directory (<code>build</code>) and find sources using <code>VPATH</code>. Then we don't need to hand-write rules.</p></li>\n<li><p>We can make better use of built-in rules: adding <code>ASFLAGS := --32</code> means we don't need to write rules for <code>bootloader.o</code> and <code>kernel_entry.o</code>. Similarly, add <code>CFLAGS += -ffreestanding -c -m32 -fno-pie -fno-stack-protector</code> to let us default <code>kernel.o</code>.</p></li>\n<li><p>With suitable <code>LDFLAGS</code>, we can write the <code>*.bin</code> commands as <code>$(LINK.c) $^ $(LDLIBS) -o $@</code>.</p></li>\n<li><p><code>rm -f</code> can be written more portably as <code>$(RM)</code></p></li>\n<li><p><code>clean</code> target leaves some <code>*.bin</code> files lying around.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:06:34.723", "Id": "467419", "Score": "0", "body": "Thank you very much for your answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T17:08:18.600", "Id": "238259", "ParentId": "238149", "Score": "3" } }, { "body": "<p><code>check_a20</code> has two bugs in it. First, you not comparing with the correct memory addresses. The physical address for the real mode <code>FFFF:0500</code> address is</p>\n\n<pre><code> FFFF0\n 0500\n -----\n1004F0\n</code></pre>\n\n<p>which, if A20 is off, will wrap around to 0000:04F0, not 0000:0510. The correct addresses to use are <code>0000:0500</code> and <code>FFFF:0510</code>.</p>\n\n<p>The second error is with how you get the result of the test back to the caller. You have a comparison instruction, <code>cmpb $0xBE, %es:(%si)</code>, which will set the Z flag (among others). You have several other instructions (pop, mov, pop, mov) then an <code>xor %ax, %ax</code>, which will set the Z flag. The <code>je</code> on the next line will then always jump, so your <code>check_a20</code> will always return 0.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T20:34:51.120", "Id": "238269", "ParentId": "238149", "Score": "4" } } ]
{ "AcceptedAnswerId": "238269", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T07:41:44.893", "Id": "238149", "Score": "5", "Tags": [ "c", "assembly", "makefile", "x86" ], "Title": "x86 Single Stage Bootloader" }
238149
<p>My today's idea was to create a <strong>POSIX shell function to <em>dump</em> all given arguments</strong>, typical use would be to call it from a fucntion, where you already know some arguments are not well set (empty; not integer) and this way you can inspect all given arguments in one go. It reminds me of a PHP <code>var_dump</code> function. :) Would anyone be able to find weak spots in there, all input is welcome.</p> <hr> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh dump_arguments () # string function - prints arguments (position and content) # indicates empty arguments and integer numbers { printf '%b' "dump_arguments()\\n----------------\\n$# arguments are being inspected" [ $# -gt 0 ] &amp;&amp; { printf ':\n'; i=1; } || printf '.\n' while [ $# -gt 0 ]; do printf '%s' "[$i]: '$1'" [ -z "$1" ] &amp;&amp; printf ' (empty)' [ "$1" -eq "$1" ] 2&gt; /dev/null &amp;&amp; printf ' (integer)' printf '\n' shift 1 i=$((i+1)) done } &gt;&amp;2 # inside some function you would call it like this dump_arguments "$@" # but to only try it out, you can call it directly dump_arguments '1' '' 5 </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>printf '%b' &quot;dump_arguments()\\\\n----------------\\\\n$# arguments are being inspected&quot;\n</code></pre>\n</blockquote>\n<p>We could make that easier to read by making each line a separate argument, and ending the line properly (rather than requiring a separate command):</p>\n<pre><code>punct=.\n${1+false} true || punct=:\nprintf '%s\\n' \\\n 'dump_arguments()' \\\n '----------------' \\\n &quot;$# arguments are being inspected$punct&quot;\n</code></pre>\n<p>It seems odd to use <code>%s</code> here:</p>\n<blockquote>\n<pre><code> printf '%s' &quot;[$i]: '$1'&quot;\n</code></pre>\n</blockquote>\n<p>Why not use the format string more clearly? And this allows us to modify to use <code>%q</code> if we have a suitable printf:</p>\n<pre><code> printf &quot;[%d]: '%s'&quot; &quot;$i&quot; &quot;$1&quot;\n</code></pre>\n<p>Perhaps even combine the type into a single print:</p>\n<pre><code> type=\n [ -z &quot;$1&quot; ] &amp;&amp; type=' (empty)'\n [ &quot;$1&quot; -eq &quot;$1&quot; ] 2&gt;/dev/null &amp;&amp; type=' (integer)'\n printf &quot;[%d]: '%s'%s\\n&quot; &quot;$i&quot; &quot;$1&quot; &quot;$type&quot;\n</code></pre>\n<p>Is it intentional that strings such as <code>' 5'</code> (with leading and/or trailing spaces) are counted as integers?</p>\n<blockquote>\n<pre><code> shift 1\n</code></pre>\n</blockquote>\n<p>Normally written simply as</p>\n<pre><code> shift\n</code></pre>\n<p>That said, I think it's more natural to iterate over arguments using a <code>for</code> loop instead.</p>\n<blockquote>\n<pre><code>} &gt;&amp;2\n</code></pre>\n</blockquote>\n<p>That's surprising, as the output isn't an error, but expected when calling the function. It should be up to the caller to choose where stream 1 goes.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#!/bin/sh\n\ndump_arguments()\n# string function - prints arguments (position and content)\n# indicates empty arguments and integer numbers\n{\n punct=${1+:}\n printf '%s\\n' \\\n 'dump_arguments()' \\\n '----------------' \\\n &quot;$# arguments are being inspected${punct:-.}&quot;\n i=1\n for v\n do\n if [ -z &quot;$v&quot; ]\n then type=' (empty)'\n elif [ &quot;$v&quot; -eq &quot;$v&quot; ] 2&gt;/dev/null\n then type=' (integer)'\n else type=\n fi\n printf &quot;[%d]: '%s'%s\\n&quot; \\\n &quot;$i&quot; &quot;$v&quot; &quot;$type&quot;\n i=$((i+1))\n done\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:04:22.047", "Id": "467300", "Score": "0", "body": "No, I just didn't show that line. There's no harm in defining it regardless, so I just wrote it before the loop. I'll edit to show my full modified version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T17:31:42.917", "Id": "238260", "ParentId": "238150", "Score": "1" } } ]
{ "AcceptedAnswerId": "238260", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T08:08:53.473", "Id": "238150", "Score": "2", "Tags": [ "posix", "sh" ], "Title": "POSIX shell function to \"dump\" all given arguments" }
238150
<p>I am a beginner android developer. I am working on one of my applications. For this application, I wrote an algorithm that is needed to obtain data that is used to build a diagram. I have a list of objects (value, date). For these objects, it is necessary to build a diagram either in the last month / two weeks / year. If there are several values ​​for 1 date, then we take the orithmetic mean. This code is written for my home project. I have a few requests:</p> <ol> <li>Could you evaluate the quality of the code and say what is good and what is bad </li> <li>I want to follow the principles of pure architecture. Therefore, I want to find out if I think that this code is a business logic. </li> <li>I called this class ChangeHistoryGraphManager. Is this name correct?</li> </ol> <p>I really want to learn how to write clean code, and so you are grateful to you for any criticism. Code: </p> <pre><code>public class ChangeHistoryGraphManager { public enum TimeInterval { LastWeek(1, 7), LastTwoMonth(7, 60), LastYear(45, 365); private int dayPointInterval; private int allDay; public int getDayPointInterval() { return dayPointInterval; } public int getAllDay() { return allDay; } TimeInterval(int dayPointInterval, int allDay) { this.dayPointInterval = dayPointInterval; this.allDay = allDay; } } public List&lt;Entry&gt; getGraphDataPoints(List&lt;ChangeHistoryModel&gt; inputModels, TimeInterval interval) { if (inputModels.size() &gt; 0) { ChangeHistoryUseCase.sortByDate(inputModels); return calculateGraphPoints(interval, inputModels); } else return new ArrayList&lt;&gt;(); } private List&lt;Entry&gt; calculateGraphPoints(TimeInterval interval, List&lt;ChangeHistoryModel&gt; models) { List&lt;TimeIntervalPoints&gt; points = getPoints(models, interval); List&lt;Entry&gt; graphsPoints = getGraphsPoints(points); ArrayList&lt;String&gt; dates = getPointDates(points); DateValueFormatter.setDate(dates); return graphsPoints; } private ArrayList&lt;TimeIntervalPoints&gt; getPoints(List&lt;ChangeHistoryModel&gt; changeHistoryModels, TimeInterval interval) { ArrayList&lt;TimeIntervalPoints&gt; points = new ArrayList&lt;&gt;(); int point = 0; Calendar startIntervalTime = getStartIntervalTime(interval); Calendar endIntervalTime = getEndIntervalTime(changeHistoryModels.get(point)); for (int i = 0; i &lt; changeHistoryModels.size(); i++) { if (addPoint(points, changeHistoryModels.get(i), interval, startIntervalTime, endIntervalTime, point)) { point++; } } return points; } private boolean addPoint(List&lt;TimeIntervalPoints&gt; points, ChangeHistoryModel model, TimeInterval interval, Calendar startIntervalTime, Calendar endIntervalTime, int point) { Calendar date = getCropDate(model.getDate()); long modelTime = date.getTimeInMillis(); long endTime = endIntervalTime.getTimeInMillis(); float weight = model.getWeight(); if (modelTime &gt;= endTime) { return addNewPoint(startIntervalTime, points, date, point, weight, endIntervalTime, interval); } else { points.get(point - 1).getWeights().add(model.getWeight()); } return false; } private boolean addNewPoint(Calendar startIntervalTime, List&lt;TimeIntervalPoints&gt; points, Calendar date, Integer pointCount, float weight, Calendar endIntervalTime, TimeInterval interval) { if (startIntervalTime.getTimeInMillis() &lt;= date.getTimeInMillis()) { points.add(new TimeIntervalPoints(new ArrayList&lt;&gt;(), date.getTime())); points.get(pointCount).getWeights().add(weight); endIntervalTime.set(Calendar.DAY_OF_YEAR, date.get(Calendar.DAY_OF_YEAR) + interval.getDayPointInterval()); return true; } return false; } private Calendar getStartIntervalTime(TimeInterval interval) { Calendar startIntervalTime = GregorianCalendar.getInstance(); setCropDate(startIntervalTime); startIntervalTime.add(Calendar.DAY_OF_YEAR, -interval.getAllDay()); return startIntervalTime; } private Calendar getEndIntervalTime(ChangeHistoryModel changeHistoryModels) { long date = changeHistoryModels.getDate(); Calendar endIntervalTime = new GregorianCalendar(); endIntervalTime.setTimeInMillis(date); setCropDate(endIntervalTime); return endIntervalTime; } private Calendar getCropDate(long time) { Calendar date = new GregorianCalendar(); date.setTime(new Date(time)); setCropDate(date); return date; } private void setCropDate(Calendar date) { date.set(Calendar.MILLISECOND, 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MINUTE, 0); date.set(Calendar.HOUR_OF_DAY, 0); } private List&lt;Entry&gt; getGraphsPoints(List&lt;TimeIntervalPoints&gt; points) { List&lt;Entry&gt; dataPoints = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; points.size(); i++) { dataPoints.add(new Entry(i, points.get(i).getPointWeight())); } return dataPoints; } private ArrayList&lt;String&gt; getPointDates(List&lt;TimeIntervalPoints&gt; points) { ArrayList&lt;String&gt; dates = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; points.size(); i++) { Calendar calendar = new GregorianCalendar(); calendar.setTime(points.get(i).getDate()); SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM"); String date = dateFormat.format(calendar.getTime()); dates.add(date); } return dates; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T15:40:20.063", "Id": "467086", "Score": "0", "body": "I'm not sure if I should review code that doesn't use [the new Java time API](https://developer.android.com/reference/java/time/package-summary)." } ]
[ { "body": "<p>Welcome to Code Review , as highlighted by @MaartenBodewes's comment, the main issue of your code is that there is no reason why you don't use <a href=\"https://developer.android.com/reference/java/time/package-summary\" rel=\"nofollow noreferrer\">Java time API</a>. My suggestions are about common things I saw repeated in your code:</p>\n\n<blockquote>\n<pre><code>ArrayList&lt;TimeIntervalPoints&gt; points = new ArrayList&lt;&gt;();\nArrayList&lt;String&gt; dates = getPointDates(points);\nArrayList&lt;String&gt; dates = new ArrayList&lt;&gt;();\n//methods returning ArrayList\nprivate ArrayList&lt;TimeIntervalPoints&gt; getPoints(List&lt;ChangeHistoryModel&gt; changeHistoryModels, TimeInterval interval) {}\nprivate ArrayList&lt;String&gt; getPointDates(List&lt;TimeIntervalPoints&gt; points) {}\n</code></pre>\n</blockquote>\n\n<p>Declare them as <code>List</code> :</p>\n\n<pre><code>List&lt;TimeIntervalPoints&gt; points = new ArrayList&lt;&gt;();\nList&lt;String&gt; dates = getPointDates(points);\nList&lt;String&gt; dates = new ArrayList&lt;&gt;();\nprivate List&lt;TimeIntervalPoints&gt; getPoints(List&lt;ChangeHistoryModel&gt; changeHistoryModels, TimeInterval interval) {}\nprivate List&lt;String&gt; getPointDates(List&lt;TimeIntervalPoints&gt; points) {}\n</code></pre>\n\n<p>If you have in a method a <code>if else</code> with one branch contain a <code>return</code> like this:</p>\n\n<blockquote>\n<pre><code>public List&lt;Entry&gt; getGraphDataPoints(List&lt;ChangeHistoryModel&gt; inputModels, TimeInterval interval) {\n if (inputModels.size() &gt; 0) {\n ChangeHistoryUseCase.sortByDate(inputModels);\n return calculateGraphPoints(interval, inputModels);\n } else\n return new ArrayList&lt;&gt;();\n}\n</code></pre>\n</blockquote>\n\n<p>Rewrite it deleting the else branch, in this case I use the <code>Collections.emptyList()</code>:</p>\n\n<pre><code>public List&lt;Entry&gt; getGraphDataPoints(List&lt;ChangeHistoryModel&gt; models, TimeInterval interval) {\n if (models.size() == 0) { return Collections.emptyList(); }\n ChangeHistoryUseCase.sortByDate(models);\n return calculateGraphPoints(models, interval);\n\n }\n</code></pre>\n\n<p>If you iterate without using the index inside the loop for calculations like this loop:</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i &lt; changeHistoryModels.size(); i++) {\n if (addPoint(points, changeHistoryModels.get(i), interval, startIntervalTime, endIntervalTime, point)) {\n point++;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Rewrite it deleting the index i:</p>\n\n<pre><code>for (ChangeHistoryModel model : models) {\n if (addPoint(points, model, interval, startIntervalTime, endIntervalTime, point)) {\n ++point;\n }\n}\n</code></pre>\n\n<p>I am sure that with <a href=\"https://developer.android.com/reference/java/time/package-summary\" rel=\"nofollow noreferrer\">Java time API</a> a lot of code would disappear including the enum <code>TimeInterval</code> and that would reduce significantly the number of lines of your code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T02:19:56.420", "Id": "467114", "Score": "0", "body": "Hello! Thanks for the answer . Java time API I can not use since it is available with api> 26 (Android 8). Could you answer 2 and 3 questions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T04:12:04.323", "Id": "467115", "Score": "0", "body": "It’s also not clear to me why in this fragment for (ChangeHistoryModel model : models) {\n if (addPoint(points, model, interval, startIntervalTime, endIntervalTime, point)) {\n ++point;\n }\n} you replaced point ++ with ++ point. What is the difference in this case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T06:57:17.390", "Id": "467119", "Score": "0", "body": "@Destroyer, Hello, the answer to both your questions 2 and 3 is yes, name of the class is explicative about the use of it and why it has been codified and separation in rules for managing data it is ok. For difference between preincrement and postincrement operator you can refer to [pre vs post in java](https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java) , lot of explanations and may other similar posts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T07:03:42.837", "Id": "467120", "Score": "0", "body": "I understand the difference between pre-increment and post-increment, but in this situation it seems to me there will be no difference because we just increase point by 1.I apologize in advance if I'm wrong" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T07:09:09.950", "Id": "467122", "Score": "0", "body": "You are correct, you can use the postincrement operator instead of preincrement operator and you obtain the same result." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T18:01:58.033", "Id": "238166", "ParentId": "238151", "Score": "3" } }, { "body": "<p>@dariosicily, Hi, I decided to rewrite the code using java time api. I am working with him for the first time, so I think there are problems in my code. Could you take a look at my new code?</p>\n\n<pre><code>public class ChangeHistoryGraphManager {\n\npublic enum TimeInterval {\n LastWeek(1, 7),\n LastTwoMonth(7, 60),\n LastYear(45, 365);\n\n private int dayPointInterval;\n private int allDay;\n\n public int getDayPointInterval() {\n return dayPointInterval;\n }\n\n public int getAllDay() {\n return allDay;\n }\n\n TimeInterval(int dayPointInterval, int allDay) {\n this.dayPointInterval = dayPointInterval;\n this.allDay = allDay;\n }\n}\n\npublic List&lt;Entry&gt; getGraphDataPoints(List&lt;ChangeHistoryModel&gt; inputModels, TimeInterval interval) {\n if (inputModels.size() == 0) {\n return Collections.emptyList();\n }\n ChangeHistoryUseCase.sortByDate(inputModels);\n return calculateGraphPoints(interval, inputModels);\n}\n\nprivate List&lt;Entry&gt; calculateGraphPoints(TimeInterval interval, List&lt;ChangeHistoryModel&gt; models) {\n List&lt;TimeIntervalPoints&gt; points = getPoints(models, interval);\n List&lt;Entry&gt; graphsPoints = getGraphsPoints(points);\n List&lt;String&gt; dates = getPointDates(points);\n DateValueFormatter.setDate(dates);\n\n return graphsPoints;\n}\n\nprivate List&lt;TimeIntervalPoints&gt; getPoints(List&lt;ChangeHistoryModel&gt; changeHistoryModels, TimeInterval interval) {\n List&lt;TimeIntervalPoints&gt; points = new ArrayList&lt;&gt;();\n int point = 0;\n\n LocalDate startGraphicsDate = getStartGraphicsDate(interval);\n LocalDate endIntervalTime = getEndIntervalTime(changeHistoryModels.get(point));\n\n for (ChangeHistoryModel model : changeHistoryModels) {\n if (addPoint(points, model, startGraphicsDate, endIntervalTime, point)) {\n point++;\n endIntervalTime = getEndIntervalTime(endIntervalTime, model, interval);\n }\n }\n\n return points;\n}\n\nprivate boolean addPoint(List&lt;TimeIntervalPoints&gt; points, ChangeHistoryModel model, LocalDate startGraphicsDate, LocalDate endIntervalTime, int point) {\n LocalDate pointDate = toLocalDateFromMilli(model.getDate());\n float pointWeight = model.getWeight();\n\n if (pointDate.isAfter(endIntervalTime) || pointDate.equals(endIntervalTime)) {\n return addNewPoint(startGraphicsDate, points, pointDate, point, pointWeight);\n } else {\n points.get(point - 1).getWeights().add(model.getWeight());\n }\n return false;\n}\n\nprivate boolean addNewPoint(LocalDate startGraphicsDate, List&lt;TimeIntervalPoints&gt; points,\n LocalDate date, Integer pointCount, float weight) {\n if (date.isAfter(startGraphicsDate)) {\n points.add(new TimeIntervalPoints(new ArrayList&lt;&gt;(), date));\n points.get(pointCount).getWeights().add(weight);\n return true;\n }\n return false;\n}\n\nprivate LocalDate getStartGraphicsDate(TimeInterval interval) {\n LocalDate startIntervalTime = LocalDate.now();\n startIntervalTime = startIntervalTime.minus(interval.getAllDay(), ChronoUnit.DAYS);\n return startIntervalTime;\n}\n\nprivate LocalDate getEndIntervalTime(ChangeHistoryModel changeHistoryModels) {\n LocalDate endIntervalTime = toLocalDateFromMilli(changeHistoryModels.getDate());\n return endIntervalTime;\n}\n\nprivate LocalDate getEndIntervalTime(LocalDate date, ChangeHistoryModel model, TimeInterval interval) {\n int currentDays = toLocalDateFromMilli(model.getDate()).getDayOfYear();\n int offsetDays = interval.getDayPointInterval();\n int days = currentDays + offsetDays;\n return date.with(ChronoField.DAY_OF_YEAR, days);\n}\n\nprivate List&lt;Entry&gt; getGraphsPoints(List&lt;TimeIntervalPoints&gt; points) {\n List&lt;Entry&gt; dataPoints = new ArrayList&lt;&gt;();\n\n for (int i = 0; i &lt; points.size(); i++) {\n dataPoints.add(new Entry(i, points.get(i).getPointWeight()));\n }\n\n return dataPoints;\n}\n\nprivate List&lt;String&gt; getPointDates(List&lt;TimeIntervalPoints&gt; points) {\n List&lt;String&gt; dates = new ArrayList&lt;&gt;();\n\n for (int i = 0; i &lt; points.size(); i++) {\n LocalDate pointDate = points.get(i).getDate();\n DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(\"dd.MM\");\n String date = pointDate.format(dateFormat);\n dates.add(date);\n }\n\n return dates;\n}\n\nprivate LocalDate toLocalDateFromMilli(long milli) {\n return Instant.ofEpochMilli(milli).atZone(ZoneId.systemDefault()).toLocalDate();\n}}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T16:38:37.913", "Id": "467259", "Score": "0", "body": "Looks much better. You could check methods like [minusDays](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#minusDays-long-) or similar methods with word days and you can reduce the number of lines." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:14:48.010", "Id": "238237", "ParentId": "238151", "Score": "0" } } ]
{ "AcceptedAnswerId": "238166", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T10:00:35.070", "Id": "238151", "Score": "2", "Tags": [ "java", "algorithm", "array", "android", "graphics" ], "Title": "Code for getting the coordinates of points on the chart" }
238151
<p>I'm trying to write something that can take a description and a date range and return all the dates that satisfy that description. </p> <p>Descriptions can be anything from the following... </p> <pre class="lang-py prettyprint-override"><code>parsed_tests_dict = [ {"Saturday": [5]}, {"Sunday": [6]}, {"Weekend": [5, 6]}, {"Weekday": [0, 1, 2, 3, 4]}, {"Monday-Saturday": [0, 1, 2, 3, 4, 5]}, {"Jan": "", "Feb": "", "Mar": "", "Nov": "", "Dec": ""}, {"Jan-Feb": "", "Jan-Mar": "", "Jan-Apr":"", "Mar-Oct": "Apr-Oct", "May-Oct": "", "Jul-Nov": "", "Nov-Feb": "", "Nov-Mar": "", "Nov-Dec": "", "Dec-Jun": ""} </code></pre> <p>So we could have a situation whereby Monday-Saturday appears, so the utility would bucket all the dates within the date range that fall between <code>Monday-Saturday</code> and then another bucket for all the dates that are <code>Sunday</code>. </p> <p>Now there can also be a situation whereby, we need to bucket <code>Jan-Mar</code>, <code>Apr-Oct</code>, <code>Nov-Dec</code> AND <code>Weekends</code> - in this scenario, we would go through say 1-year date range, bucket every weekday that is between <code>Jan-Mar</code>, <code>Apr-Oct</code> and <code>Nov-Dec</code> and finally, all the <code>Weekends</code> in between would be bucketed under <code>Weekends</code></p> <p>I want to try to be as efficient and fast as possible and have been trying a method of this structure: </p> <pre class="lang-py prettyprint-override"><code>STR2WKDAY = { 'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6, 'wkd': [0, 1, 2, 3, 4], 'wke': [5, 6], 'all': [0, 1, 2, 3, 4, 5, 6], } STR2MON = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, } </code></pre> <p>This is what I have so far, but I would be interested to see other solutions to this problem as mine feels a bit 'wrong' -</p> <pre><code>class DateRange(Database): parsed_dates = [] def __init__(self, days, weekdays, months): super().__init__() self.days = str(days) self.weekdays = frozenset(DateRange.flatn(weekdays)) # flat set of ints self.months = frozenset(DateRange.flatn(months)) # flat set of ints def __repr__(self): return self.days def accepts(self, dt): return any([ dt.weekday() in self.weekdays, dt.month in self.months, ]) @staticmethod def get_days(description): for days in description: wkdays = list() months = list() for item in days: item = item.strip().lower().replace('ee', '', 1) # weekend,weekday =&gt; wke,wkd if '-' not in item: if item[:3] in Constants.STR2WKDAY: wkdays.append(Constants.STR2WKDAY[item[:3]]) elif item[:3] in Constants.STR2MON: months.append(Constants.STR2MON[item[:3]]) else: f, t = item.split('-', 2) f = f.strip() t = t.strip() if f[:3] in Constants.STR2WKDAY: f = Constants.STR2WKDAY[f[:3]] t = Constants.STR2WKDAY[t[:3]] if f &gt; t: wkdays.append([i for i in range(t + 1)]) wkdays.append([i for i in range(f, 7)]) else: wkdays.append([i for i in range(f, t + 1)]) elif f[:3] in Constants.STR2MON and t[:3] in Constants.STR2MON: f = Constants.STR2MON[f[:3]] t = Constants.STR2MON[t[:3]] if f &gt; t: months.append([i for i in range(t + 1)]) months.append([i for i in range(f, 13)]) else: months.append([i for i in range(f, t + 1)]) DateRange.parsed_dates.append(DateRange(days[0], wkdays, months)) @staticmethod def flatn(array): if isinstance(array, list): for element in array: yield from DateRange.flatn(element) else: yield (array) @staticmethod def date_range(from_date, to_date): for n in range((to_date - from_date).days + 1): yield from_date + timedelta(n) </code></pre> <p>Then calling this I just pass a Numpy array of descriptions atm to <code>get_days()</code> - I.E: </p> <p><code>[['Saturdays'], ['Sundays'], ['Weekdays']]</code></p> <p>This will then bucket every date that falls into each description. - This is long, so thanks to anyone who has a go and I appreciate any advice as I'm fairly new to programming. </p> <h2>Example usage</h2> <pre><code>from datetime import timedelta, datetime from collections import defaultdict class Constants: STR2WKDAY = { 'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6, 'wkd': [0, 1, 2, 3, 4], 'wke': [5, 6], 'all': [0, 1, 2, 3, 4, 5, 6], } STR2MON = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, } def usage(start_date, end_date, description): active_dates_dict = defaultdict(list) # populate the list in DateRange with dates that match the description for given date range DateRange.active_days(description) for date in DateRange.parsed_dates: # iterate over the dates and organise them into buckets that match the description for dt in [dt for dt in DateRange.date_range(datetime.strptime(start_date, '%Y-%m-%d').date(), datetime.strptime(end_date, '%Y-%m-%d').date()) if date.accepts(dt)]: # add the datetime objects to a list of values with the description as the key active_dates_dict[str(date)].append(str(dt.isoformat())) return active_dates_dict if __name__ == '__main__': a = usage(start_date="2020-01-01", end_date="2020-01-04", description=[['Monday-Saturday']]) print(a) ''' Possible descriptions - it's worth noting that you can have more than one of these descriptions at the same time i.e we could have Nov-Dec AND Weekend so we would need to bucket all dates that are from Nov-Dec that are also no weekends and then the remaining dates would do in the Weekend bucket Saturday Sunday Weekend Weekday Monday-Saturday Jan Feb Mar Nov Dec Jan-Feb Jan-Mar Jan-Apr Mar-Oct Apr-Oct May-Oct Jul-Nov Nov-Feb Nov-Mar Nov-Dec Dec-Jun Not supported yet (Not sure how) - nice to have but not a Must have 3rd Nov - Dec 9th Mar - 2nd Nov Jan-8th Mar 3rd Nov-8th Mar ''' </code></pre> <p>Any improvements are appreciated </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T20:59:01.827", "Id": "467500", "Score": "2", "body": "What is the `Database` in `class DateRange(Database)`? Is it your custom class too, or provided by an external library? Can I get it from somewhere to run the code locally?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T14:51:45.447", "Id": "467722", "Score": "0", "body": "@Bob your recent edits (e.g. [today](https://codereview.stackexchange.com/review/suggested-edits/129046), [yesterday](https://codereview.stackexchange.com/review/suggested-edits/129017))have been rejected because we cannot assume you have the same identity as the OP. If that is the case please click the “contact [us]” link at the bottom of the page and use to form to request an account merge." } ]
[ { "body": "<p>The pandas library has various <a href=\"https://pandas.pydata.org/docs/user_guide/timeseries.html\" rel=\"nofollow noreferrer\">functions for creating, manipulating and selecting date ranges</a>. For example, <code>date_range(start, stop)</code> creates a range of dates. <code>bdate_range(start, stop, ...)</code> can take a mask to only create certain days of the week, and can skip holidays.</p>\n\n<p>One way to create your example date range:</p>\n\n<pre><code>import pandas as pd\n\na = pd.bdate_range(start=\"2020-01-01\", end=\"2020-01-04\", freq='C', weekmask='Mon Tue Wed Thu Fri Sat')\n</code></pre>\n\n<p>Another method might be to create the dates and then select the dates matching the description. Something like:</p>\n\n<pre><code># create a range of dates\na = pd.date_range(start=\"2020-01-01\", end=\"2020-12-31\")\n\n# select dates according to a description\nweekday = a.dayofweek &lt; 5\n\njan_to_mar = a.month.isin([0,1,2])\napr_to_oct = a.month.isin([3,4,5,6,7,8,9])\nnov_to_dec = a.month.isin([10,11])\n\nweekdays_in_jan_to_mar = a[weekday &amp; jan_to_mar]\nweekdays_in_apr_to_oct = a[weekday &amp; apr_to_oct]\nweekdays_in_nov_to_dec = a[weekday &amp; nov_to_dec]\n\nweekends = a[~weekday]\n</code></pre>\n\n<p>This later method could be generalized along the lines of <code>get_days()</code> to put the desired values in the call to <code>a.month.isin()</code> (or a.dayofweek.isin()).</p>\n\n<pre><code>DAYOFWEEK = dict(zip('mon tue wed thu fri sat sun'.split(), range(7)))\nMONTH = dict(zip(\"jan feb mar apr may jun jul aug sep oct nov dec\".split(), range(1, 13)))\n\ndef get_buckets(start, end, descriptions):\n dates = pd.date_range(start, end)\n buckets = []\n\n for description in descriptions:\n\n description = description.strip().lower().split('-')\n start = description[0][:3]\n end = start if len(description) == 1 else description[1][:3]\n\n if start in DAYOFWEEK:\n start = DAYOFWEEK[start]\n end = DAYOFWEEK[end]\n span = 0, len(DAYOFWEEK)\n selector = dates.dayofweek\n\n else:\n start = MONTH[start]\n end = MONTH[end]\n span = 1, len(MONTH) + 1\n selector = dates.month\n\n if start &lt;= end:\n rng = set(range(start, end + 1))\n else:\n rng = set(range(*span)) - set(range(start - 1, end, - 1))\n\n buckets.append(dates[selector.isin(rng)])\n\n return buckets\n</code></pre>\n\n<p>By the way, the description of the problem implies that the buckets are mutually exclusive, but the code does not behave that way. <code>get_dates()</code> and <code>usage()</code> will both put a date into multiple buckets</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T04:55:52.637", "Id": "238516", "ParentId": "238154", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T11:02:31.240", "Id": "238154", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "design-patterns" ], "Title": "Utility for Python date ranges" }
238154
<pre class="lang-py prettyprint-override"><code>import itertools import os import re from typing import List class Command: """Base command class which all commands inherit from. Command class implements all common functions and utilities between commands, like file and directories handling, and specific commands like arbitrary, text, or picture commands inherit it. """ def __init__(self, args): """Instantiate an object with the files/directory to work on.""" self.dir_path = args.dir_path self._extract_files(args) self._files_paths = None def _extract_files(self, args): """ Returns the files specified by the user, if any. Throws exception if no file matches user input. """ self.files_list = None if args.name is not None: self.files_list = self._file_from_name(args.name) elif args.names_file is not None: self.files_list = self._names_from_file(args.names_file) elif args.rgx is not None: self.files_list = self._files_from_rgx(args.rgx) elif args.rgx_file is not None: self.files_list = self._rgx_from_file(args.rgx_file) else: self.files_list = self._extract_all_files() if len(self.files_list) == 0: raise FileNotFoundError("No files match") def _files_from_rgx(self, rgx): """ Looks for files in the directory `self.dir_path` with names matched to the provided regex and returns those files names. """ f = [] for (dir_path, dirnames, filenames) in os.walk(self.dir_path): f.extend(filenames) break prog = re.compile(rgx) m = [] for file_name in f: matched = prog.match(file_name) # matched.span() =&gt; (match start index, match end index) # Check that the file name is matched as a whole if matched and matched.span()[1] == len(file_name): m.append(file_name) return m </code></pre> <pre class="lang-py prettyprint-override"><code>import collections import os import pytest from fipy.parser import parser from fipy.commands.command import Command class TestCommand: """Tests for the command class.""" def _populate_tmp_dir(self, tmpdir, dirs, files): dirs = [tmpdir.mkdir(x) for x in dirs] files = [tmpdir.join(x).write('') for x in files] def test_files_from_rgx_no_match(self, tmpdir): dirs = ['abc', '1abc', 'x1.txt'] files = ['x.txt', 'x.tsf', '1abc.png'] self._populate_tmp_dir(tmpdir, dirs, files) args = parser.parse_args( ['-p', str(tmpdir), '-r', 's[0-9]*.txt', 'any', 'rename', '-asc'] ) with pytest.raises(FileNotFoundError): command = Command(args) </code></pre> <p>First of all, is it a good practice to set <code>self.dir_path</code> and make the function use it, or pass it to the function as a parameter? (<code>_files_from_rgx</code> function)</p> <p>And if I want to write unit tests, should I test write a test for the function and another for the constructor, or write tests for the constructor, which implicitly will enter the function which I have done in the test above?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T12:31:46.447", "Id": "467071", "Score": "0", "body": "@Peilonrayz Thank you very much for this comment, I didn't realize I have to write actual code. I will put the actual code now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T13:37:49.143", "Id": "467078", "Score": "0", "body": "@Peilonrayz I am not very sure I understand exactly what you mean, but if you are saying that I have not written this code, this is actually a code I have written for a side project I am working on. Anyway, I will add the unit test" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T13:39:36.207", "Id": "467079", "Score": "1", "body": "To be clear I am not intending to say that. I am talking about the missing unit tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T13:41:17.800", "Id": "467080", "Score": "0", "body": "@Peilonrayz No offense taken :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T13:48:24.050", "Id": "467081", "Score": "1", "body": "Thank you for the edits :)" } ]
[ { "body": "<p>There's a couple of things to consider when designing a class -> test relationship.</p>\n\n<p>First, I'd try hard to avoid the situation you're setting up where a command class can crash in its own constructor. It's usually a better idea to make sure that constructors are exception-safe if possible, since you never know what calling code may want to do with them. So the first thing I'd consider is simply turning <code>_extract_files()</code> into a regular public method and not calling it in the constructor. Among other things, it simplifies the test code by allowing you to create test objects without pre-configuring things -- but it's also better in general.</p>\n\n<p>Which leads to number 2: it's better not to rely on the state of a local hard drive in tests. Ideally a test suite runs in a completely reproducible, zero-entropy environment which never changes -- not even if your build machine is low on hard drive space, the network connection goes down, a user doesn't actually have a writable tempdir, and so on. These kinds of conditions are often hard to work around, but thinking them through tends to make for better <em>testing</em> - and that, in turn, leads to better code.</p>\n\n<p>In your case, <code>_files_from_rgx</code> really wants to be operating on the state of a local directory. However the 'work' is really coming from the way the regex parses the file list. So, one way to get good coverage is to refactor <code>Command</code> so that the parsing logic works on a file list (or better yet, any iterable since that's more generous). In this case if you took the regex-filter function out you might get something like this for a start:</p>\n\n<pre><code>def _files_from_rgx(self, rgx):\n \"\"\"\n Looks for files in the directory `self.dir_path` with names \n matched to the provided regex and returns those files names.\n \"\"\"\n f = []\n # incidentally since you're not using the recursion here,\n # you could probably replace this with \n # f = os.listdir(self.dir_path)\n\n for (dir_path, dirnames, filenames) in os.walk(self.dir_path):\n f.extend(filenames)\n break\n\n return list(self._filter_by_regex(rgx, f))\n\n\ndef _filter_by_regex(self, rgx, inputs):\n \"\"\"\n loop over &lt;inputs&gt; yielding out values which are full-name\n matches for the regex &lt;rgx&gt;\n \"\"\"\n compiled_rgx = re.compile(rgx)\n\n for each_file in inputs:\n matched = compiled_rgx.match(each_file)\n if matched and matched.span()[1] == len(each_file):\n yield each_file\n</code></pre>\n\n<p>Now you can test the <code>_filter_by_regex</code> function in isolation :</p>\n\n<pre><code> def test_filter_by_regex(self):\n example = Command(some_test_args):\n known_regex = \".*\\.py\"\n sample_data = ['a.py', 'b.py', 'c.cpp', 'd.exe', 'e.py']\n results = list(example._test_filter_by_regex(known_regex, sample_data))\n self.assetListEqual(results, ['a.py', 'b.py', 'e.py']\n</code></pre>\n\n<p>This doesn't require you to actually create temp files and so on (note that you have to be a good citizen if you do create temp files, because if the tests are running on a build server you don't want to be leaking test files all over the place!).</p>\n\n<p>You didn't include source for <code>_file_from_name()</code> and <code>_names_from_file</code> but it would be a good idea to structure them and their tests so you can test them in the same way, without going to disk. You'll eventually have a function somewhere what will have to call <code>os.listdir()</code> or <code>os.walk</code> and feed those functions -- but at least the part of the logic that is all yours will be covered by tests.</p>\n\n<p>The test you wrote does one thing that's really great, which is guaranteeing the exception raised by an empty file list. That's a very good test, because it guarantees predictable behavior for users. You can make that functionality independently testable with a similar small refactor that moves that into a separate function:</p>\n\n<pre><code>def _validate_file_list(self, file_list):\n if not file_list:\n raise FileNotFoundError(\"No files match\")\n</code></pre>\n\n<p>And a matching test:</p>\n\n<pre><code>def test_validate_raises_on_empty_file(self):\n example = command(some_test_args)\n should_raise = lambda: example._validate_file_list([])\n self.assertRaises(FileNotFoundError, should_raise)\n</code></pre>\n\n<p>There's another approach you could take, but I would recommend learning how to do the \"old-fashioned\" way first. The <a href=\"https://docs.python.org/3/library/unittest.mock.html\" rel=\"nofollow noreferrer\"><code>mock module</code></a> would allow you to simulate the state of a disk by replacing calls to things like <code>os.walk</code> with a dummy function that return the same results every time without looking at the disk. It's a very powerful technique, but it can encourage code that's otherwise not easily testable. I'd figure out more ways to isolate and test key code paths without <code>mock</code> before adding it in as a final level of testing. </p>\n\n<p>For a good look at the philosophy of breaking out logic and IO, I highly recommend this talk by Python core dev Brandon Rhodes: <a href=\"https://youtu.be/PBQN62oUnN8\" rel=\"nofollow noreferrer\">https://youtu.be/PBQN62oUnN8</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T01:38:58.247", "Id": "467287", "Score": "1", "body": "Thank you so much for this answer. It has given me some insights, that will definitely change the way I design my projects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T05:07:09.077", "Id": "238218", "ParentId": "238156", "Score": "3" } } ]
{ "AcceptedAnswerId": "238218", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T11:40:00.823", "Id": "238156", "Score": "1", "Tags": [ "python", "unit-testing" ], "Title": "Unit testing a commands class" }
238156
<p>I am working in a system that does not have room for an STL (think something like an Arduino), however I do like the comfort of <code>std::function</code>. For now I am only using this to wrap lambdas, but some sort of <code>std::bind</code> replacement is also on the roadmap. Important to know is that exception handling is not advised on said platform either and by not advised I mean the flag <code>-fno-exceptions</code> is enforced.</p> <p>One of the things I would like to get some ideas about is how to do proper error handling in such a system. For example the <code>operator ()</code> currently just returns a default created instance of the return type, if no callback has been given to the function. I feel like this is a bit ugly, however I would also like to avoid resorting to returning an error code. Are there other nice options?</p> <p>Lets look at the usage first:</p> <pre class="lang-cpp prettyprint-override"><code> function&lt;void (bool)&gt; _click_callback; function&lt;void (ptrdiff_t)&gt; _value_callback; // ... rot.click_callback([](bool clicked) { }); rot.value_callback([](ptrdiff_t value) { }); </code></pre> <p>and the actual code with all the "dependencies" like <code>is_same</code>. I'd love to hear some suggestions :)</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T, typename R&gt; class is_same { public: static constexpr bool value = false; }; template&lt;typename T&gt; class is_same&lt;T, T&gt; { public: static constexpr bool value = true; }; template&lt;bool cond, typename type&gt; class enable_if { }; template&lt;typename type_name&gt; class enable_if&lt;true, type_name&gt; { public: using type = type_name; }; template&lt;typename R, typename... Args&gt; class invoker { public: virtual ~invoker() = default; virtual R invoke(Args... args) = 0; virtual invoker&lt;R, Args...&gt; *clone() = 0; }; template&lt;typename R, typename C, typename... Args&gt; class lambda_invoker : public invoker&lt;R, Args...&gt; { C _lambda; public: explicit lambda_invoker(C lambda) : _lambda{lambda} {} R invoke(Args... args) override { return _lambda(args...); } invoker&lt;R, Args...&gt; *clone() override { return new lambda_invoker(_lambda); } }; template&lt;typename T&gt; class function_decayer : public function_decayer&lt;decltype(&amp;T::operator())&gt; { }; template&lt;typename ClassType, typename ReturnType, typename... Args&gt; class function_decayer&lt;ReturnType(ClassType::*)(Args...) const&gt; { public: using invoker = lambda_invoker&lt;ReturnType, ClassType, Args...&gt;; }; template&lt;typename T&gt; class function { }; template&lt;typename R, typename... Args&gt; class function&lt;R(Args...)&gt; { public: using return_type = R; private: invoker&lt;R, Args...&gt; *_invoker = nullptr; public: function() = default; template&lt;typename T&gt; function(T invoker) { using decayer = function_decayer&lt;T&gt;; _invoker = new typename decayer::invoker(invoker); } function(const function &amp;other) { if (other._invoker) { _invoker = other._invoker-&gt;clone(); } else { _invoker = nullptr; } } function(function&amp;&amp; other) noexcept { _invoker = other._invoker; other._invoker = nullptr; } ~function() { delete _invoker; _invoker = nullptr; } function&amp; operator = (const function&amp; other) { if(this == &amp;other) { return *this; } _invoker = other._invoker ? other._invoker-&gt;clone() : nullptr; return *this; } function&amp; operator = (function&amp;&amp; other) noexcept { _invoker = other._invoker; other._invoker = nullptr; return *this; } template&lt;typename ret = R&gt; typename enable_if&lt;is_same&lt;ret, void&gt;::value, ret&gt;::type operator ()(Args... args) { if(!_invoker) { return; } _invoker-&gt;invoke(args...); } template&lt;typename ret = R&gt; typename enable_if&lt;!is_same&lt;ret, void&gt;::value, ret&gt;::type operator () (Args... args) { if(!_invoker) { return {}; } return _invoker-&gt;invoke(args...); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T14:57:27.800", "Id": "467084", "Score": "3", "body": "It might be good to add a few more details, such as is this an embedded system? There is a tag for that. Why the limitations? How do you handle memory allocation errors if exceptions are a bad idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T17:29:39.973", "Id": "467089", "Score": "0", "body": "Yea, for the sake of it, lets assume its an embedded system. A fact is, that the compiler for the system enforces `-fno-exceptions`. Error handling would be one of the main things I'd like to get some inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T17:37:52.267", "Id": "467090", "Score": "1", "body": "The fact is that someone not me, voted to close this question for lack of details so it would be good to add some details to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T17:39:41.247", "Id": "467091", "Score": "0", "body": "I have added that it should be considered something like an Arduino and that the no exceptions flag is mandatory by the compiler. What else could make sense to add?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T18:08:25.110", "Id": "467092", "Score": "0", "body": "Let's see what happens now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T09:52:01.333", "Id": "467212", "Score": "1", "body": "You're still beating around the bush a lot and it reads like this is still not your real code. Please take a look at the [FAQ on hypothetical code](https://codereview.meta.stackexchange.com/q/1709/52915) to understand why this is a problem. The deal is you give us a specific situation and we try to provide advice that fits the code. Generalizations lead to reviews that are not applicable to your actual situation and we have bad experiences with that. It's a waste of everyone's time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T10:11:49.287", "Id": "467215", "Score": "0", "body": "Except for the C++ file that includes that header file this is exactly the code I am using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T10:13:22.827", "Id": "467216", "Score": "0", "body": "The reason for the vagueness of the platform is that I do not want a review that focuses on said platform, because then the review would probably boil down to \"enable exceptions and use exceptions\", but that's not what I want." } ]
[ { "body": "<p>After using this for a while I have to say I did not improve anything, so I guess it is good enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T19:20:18.727", "Id": "248833", "ParentId": "238157", "Score": "0" } } ]
{ "AcceptedAnswerId": "248833", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T12:22:45.550", "Id": "238157", "Score": "2", "Tags": [ "c++", "embedded" ], "Title": "STL replacement for std::function" }
238157
<p>I am learning Rust. I have written a web crawler that would scrape all the pages from my own blog (which is running on Ghost) and would generate a static version of it. Because of this, I'm not interested in handling robots.txt or having rate limiting.</p> <pre><code>extern crate select; use std::io::Read; use select::document::Document; use select::predicate::Name; use select::predicate::Predicate; use std::collections::HashSet; use reqwest::Url; use std::path::Path; use std::time::Instant; use std::fs; use rayon::prelude::*; use std::sync::{Arc, Mutex}; fn get_links_from_html(html: &amp;String) -&gt; HashSet&lt;String&gt; { Document::from(html.as_str()) .find(Name("a").or(Name("link"))) .filter_map(|n| n.attr("href")) .filter(has_extension) .filter_map(normalize_url) .collect::&lt;HashSet&lt;String&gt;&gt;() } fn normalize_url(url: &amp;str) -&gt; Option&lt;String&gt; { let new_url = Url::parse(url); match new_url { Ok(new_url) =&gt; { if new_url.has_host() &amp;&amp; new_url.host_str().unwrap() == "rolisz.ro" { Some(url.to_string()) } else { None } }, Err(_e) =&gt; { // Relative urls are not parsed by Reqwest if url.starts_with('/') { Some(format!("https://rolisz.ro{}", url)) } else { None } } } } fn fetch_url(client: &amp;reqwest::blocking::Client, url: &amp;str) -&gt; String { let mut res = client.get(url).send().unwrap(); println!("Status for {}: {}", url, res.status()); let mut body = String::new(); res.read_to_string(&amp;mut body).unwrap(); return body } fn has_extension(url: &amp;&amp;str) -&gt; bool { Path::new(&amp;url).extension().is_none() } fn write_file(path: &amp;str, content: &amp;String) { let dir = fs::create_dir_all(format!("static{}", path)).unwrap(); fs::write(format!("static{}/index.html", path), content); } fn main() { let now = Instant::now(); let client = reqwest::blocking::Client::new(); let origin_url = "https://rolisz.ro/"; let body= fetch_url(&amp;client, origin_url); write_file("", &amp;body); let mut visited = Arc::new(Mutex::new(HashSet::new())); visited.lock().unwrap().insert(origin_url.to_string()); let found_urls = get_links_from_html(&amp;body); let mut new_urls = found_urls.difference(&amp;visited.lock().unwrap()).map(|x| x.to_string()).collect::&lt;HashSet&lt;String&gt;&gt;(); while new_urls.len() &gt; 0 { let mut found_urls = Arc::new(Mutex::new(HashSet::new())); new_urls.par_iter().for_each(|url| { let body = fetch_url(&amp;client, url); write_file(&amp;url[origin_url.len()-1..], &amp;body); let links = get_links_from_html(&amp;body); println!("Visited: {} found {} links", url, links.len()); found_urls.lock().unwrap().extend(links); visited.lock().unwrap().insert(url.to_string()); }); new_urls = found_urls.lock().unwrap() .difference(&amp;visited.lock().unwrap()).map(|x| x.to_string()) .collect::&lt;HashSet&lt;String&gt;&gt;(); println!("New urls: {}", new_urls.len()) } println!("URLs: {:#?}", found_urls); println!("{}", now.elapsed().as_secs()); } </code></pre> <p>I'm most familiar with Python, so I'm looking mostly for feedback on how to write more idiomatic Rust. One particular thing that stands out is the repetition of the <code>.lock().unwrap()</code> for the HashSets wrapped in Mutex and Arc. What's the most elegant way to handle that in Rust? </p> <p>Any other feedback is also welcome. </p>
[]
[ { "body": "<h1>Cargo Fmt</h1>\n<p>There's a very common tool accessible through <code>cargo</code> which can format all of the code in your project according to Rust's official style guide. Many major open source Rust libraries use this tool (and even enforce it through CI on pull requests), which you can access through <code>cargo fmt</code>. You can also customize its output using a <code>.rustfmt</code> config file. See the project's repo under the official rust-lang organization <a href=\"https://github.com/rust-lang/rustfmt\" rel=\"noreferrer\">here</a>.</p>\n<h1>Time to <code>try_</code> again?</h1>\n<p>The closure that starts here contains several <code>.unwrap()</code> because some locks you do might not yield anything.</p>\n<blockquote>\n<pre><code> new_urls.par_iter().for_each(|url| {\n // ...\n found_urls.lock().unwrap().extend(&amp;links);\n visited.lock().unwrap().insert(url.to_string());\n</code></pre>\n</blockquote>\n<p>Instead of <code>.unwrap()</code>ing whenever something goes wrong, which could poison all of your locked Mutexes, consider <a href=\"https://docs.rs/rayon/1.3.0/rayon/iter/trait.ParallelIterator.html#method.try_for_each\" rel=\"noreferrer\">try_for_each</a>.</p>\n<p>With <code>try_for_each</code>, your closure has to return a <code>Result&lt;T, E&gt;</code> or an <code>Option&lt;T&gt;</code> instead of <code>()</code> (nothing, unit). This allows you to use Rust's special <code>?</code> operator, which is like a shorter version of <code>.unwrap()</code> that's actually a bit nicer because instead of crashing your program, it returns the error to be handled somewhere else.</p>\n<pre class=\"lang-rust prettyprint-override\"><code> found_urls.lock().ok()?.extend(links);\n visited.lock().ok()?.insert(url.to_string());\n Some(())\n</code></pre>\n<p>Note that in this case, we do have to use <code>.ok()</code> because the <code>PoisonError</code> the Mutex returns also contains a reference to the Mutex, which isn't thread safe. A better practice here might be to use a custom Error enum. (more on that later)</p>\n<p>This practice can be propagated throughout the code base.</p>\n<h1>Compiler Warnings</h1>\n<p>The Rust compiler is your friend! When I compile your code on my machine, I get several warnings.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>warning: unused variable: `dir`\n --&gt; src\\main.rs:60:9\n |\n60 | let dir = fs::create_dir_all(format!(&quot;static{}&quot;, path)).unwrap();\n | ^^^ help: consider prefixing with an underscore: `_dir`\n |\n = note: `#[warn(unused_variables)]` on by default\n\nwarning: variable does not need to be mutable\n --&gt; src\\main.rs:73:9\n |\n73 | let mut visited = Arc::new(Mutex::new(HashSet::new()));\n | ----^^^^^^^\n | |\n | help: remove this `mut`\n |\n = note: `#[warn(unused_mut)]` on by default\n\nwarning: variable does not need to be mutable\n --&gt; src\\main.rs:82:13\n |\n82 | let mut found_urls = Arc::new(Mutex::new(HashSet::new()));\n | ----^^^^^^^^^^\n | |\n | help: remove this `mut`\n\nwarning: unused `std::result::Result` that must be used\n --&gt; src\\main.rs:61:5\n |\n61 | fs::write(format!(&quot;static{}/index.html&quot;, path), content);\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: `#[warn(unused_must_use)]` on by default\n = note: this `Result` may be an `Err` variant, which should be handled\n</code></pre>\n<p>These can all be handled in straightforward ways.</p>\n<blockquote>\n<pre><code>fn write_file(path: &amp;str, content: &amp;String) {\n let dir = fs::create_dir_all(format!(&quot;static{}&quot;, path)).unwrap();\n fs::write(format!(&quot;static{}/index.html&quot;, path), content);\n}\n</code></pre>\n</blockquote>\n<p>Here, for example, you create a <code>dir</code> variable that's never used, and <code>fs::write</code> could fail but you never handle the error.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn write_file(path: &amp;str, content: &amp;String) -&gt; Result&lt;(), ()&gt; {\n</code></pre>\n<p>Filling in unit <code>()</code> types will get the compiler to tell us what types should actually go there.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>PS C:\\Users\\cedhu\\reqtwest&gt; cargo check\n Checking reqtwest v0.1.0 (C:\\Users\\cedhu\\reqtwest)\nerror[E0308]: mismatched types\n --&gt; src\\main.rs:60:5\n |\n59 | fn write_file(path: &amp;str, content: &amp;String) -&gt; Result&lt;(), ()&gt; {\n | -------------- expected `std::result::Result&lt;(), ()&gt;` because of return type\n60 | fs::write(format!(&quot;static{}/index.html&quot;, path), content)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found struct `std::io::Error`\n |\n = note: expected enum `std::result::Result&lt;_, ()&gt;`\n found enum `std::result::Result&lt;_, std::io::Error&gt;`\n\nerror: aborting due to previous error\n</code></pre>\n<p>Now, thanks mostly due to the Rust compiler, we have</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn write_file(path: &amp;str, content: &amp;String) -&gt; Result&lt;(), std::io::Error&gt; {\n fs::create_dir_all(format!(&quot;static{}&quot;, path))?;\n fs::write(format!(&quot;static{}/index.html&quot;, path), content)\n}\n</code></pre>\n<p>And now the Rust compiler will continue by warning us about places where we don't handle the error that <code>write_file</code> now returns. Handling errors seems like a lot of typing, but it helps you make much more stable programs, and Rust's Result types really do force you to think about edge cases you would otherwise simply ignore.</p>\n<pre><code>write_file(&amp;url[origin_url.len() - 1..], &amp;body)\n .unwrap_or_else(|e| panic!(&quot;Couldn't write {:?} to file: {}&quot;, url, e));\n</code></pre>\n<h1>Custom Error Type</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>new_urls.par_iter().try_for_each(|url| {\n let body = fetch_url(&amp;client, url);\n write_file(&amp;url[origin_url.len() - 1..], &amp;body)\n .unwrap_or_else(|e| panic!(&quot;Couldn't write {:?} to file: {}&quot;, url, e));\n\n let links = get_links_from_html(&amp;body);\n println!(&quot;Visited: {} found {} links&quot;, url, links.len());\n found_urls.lock().ok()?.extend(links);\n visited.lock().ok()?.insert(url.to_string());\n Some(())\n}).unwrap();\n</code></pre>\n<p>Our <code>par_iter</code> looks like this now, but it's a bit ugly and inconsistent. For the file writing, we just panic if that creates an error, but for the <code>.lock()</code>s we return <code>None</code> through <code>?</code> to create an early return. Furthermore, that <code>None</code> won't contain any information that could be useful for debugging. We do have information to return from the <code>write_file</code>, so we could stop using <code>Option&lt;()&gt;</code> and maybe start using <code>Result&lt;(), String&gt;</code>, and get some information from the failed <code>.lock()</code>s and put that in a <code>String</code>, but <code>String</code>s are really big and messy, so let's try to avoid turning anything into a <code>String</code> until the last possible moment. To do that, we can use an enum to represent all of the possible failures our program might make.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>enum Error {\n // TODO: get useful information from the mutex\n // before dropping it and store it in this error.\n Lock,\n\n Write {\n url: String,\n e: IoErr\n }\n}\n</code></pre>\n<p>In this example, <code>Error::Lock</code> doesn't store any useful information quite yet, but <code>Error::Write</code> does. Let's start by doing two things that will make it very easy for us to change our <code>write_file</code> function to use our custom error type.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>type Result&lt;T&gt; = std::result::Result&lt;T, Error&gt;;\n</code></pre>\n<p>This little bit of code will allow us to just write <code>Result&lt;()&gt;</code> and have that turn into <code>Result&lt;(), Error&gt;</code>, since all of the errors used in our program will use be our Error type, we don't want to have to keep typing <code>Error</code> all of the time.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::io::Error as IoErr;\n\n// ...\n\nimpl&lt;S: AsRef&lt;str&gt;&gt; From&lt;(S, IoErr)&gt; for Error {\n fn from((url, e): (S, IoErr)) -&gt; Self {\n Error::Write {\n url: url.as_ref().to_string(), \n e\n }\n }\n}\n</code></pre>\n<p>This code will let us use <code>?</code> to create <code>Error</code>s from <code>std::io::Error</code>s like <code>fs::write_file</code> returns. This will make it very easy for us to make a <code>write_file</code> function that returns our custom error type.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn write_file(path: &amp;str, content: &amp;String) -&gt; Result&lt;()&gt; {\n let dir = format!(&quot;static{}&quot;, path);\n fs::create_dir_all(&amp;dir).map_err(|e| (&amp;dir, e))?;\n\n let index = format!(&quot;static{}/index.html&quot;, path);\n fs::write(&amp;index, content).map_err(|e| (&amp;index, e))?;\n\n Ok(())\n}\n</code></pre>\n<p>The errors will now contain lots of very useful information that will make debugging a breeze.</p>\n<p>Before we can clean up our <code>par_iter</code> call, now we need to take care of turning <code>.lock()</code> errors into our custom error type. For now, this will suffice.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl&lt;T&gt; From&lt;PoisonError&lt;T&gt;&gt; for Error {\n fn from(_: PoisonError&lt;T&gt;) -&gt; Self {\n //TODO: get useful information from the Mutex and store it in the Lock\n Error::Lock\n }\n}\n</code></pre>\n<p>Now our <code>par_iter</code> call can be just:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>new_urls.par_iter().try_for_each::&lt;_, Result&lt;()&gt;&gt;(|url| {\n let body = fetch_url(&amp;client, url);\n write_file(&amp;url[origin_url.len() - 1..], &amp;body)?;\n\n let links = get_links_from_html(&amp;body);\n println!(&quot;Visited: {} found {} links&quot;, url, links.len());\n found_urls.lock()?.extend(links);\n visited.lock()?.insert(url.to_string());\n Ok(())\n}).unwrap();\n</code></pre>\n<p>There are no more <code>.unwrap()</code>s or even <code>.ok()</code>s everywhere (except for at the very end), and we can easily store information for debugging without having to <code>panic!</code> and risk poisoning <code>Mutex</code>s.</p>\n<p>Before we go ahead and start getting useful information to put in our <code>Lock</code> errors, let's try to clean up <code>fn main</code> a bit, since it uses <code>.unwrap()</code> a lot as well.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() -&gt; Result&lt;()&gt; {\n</code></pre>\n<p>Let's have <code>main</code> return a result with one of our fancy custom errors.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>write_file(&quot;&quot;, &amp;body)?;\n// ...\nvisited.lock()?.insert(origin_url.to_string());\n// ...\nlet mut new_urls = found_urls\n .difference(&amp;*visited.lock()?)\n // ...\n</code></pre>\n<p>Notice that we need <code>&amp;*visited.lock()?</code> now to coerce our <code>MutexGuard&lt;HashMap&lt;_&gt;&gt;</code> into a <code>HashMap&lt;_&gt;</code>, because <code>?</code> is already converting it from a <code>Result&lt;MutexGuard&gt;</code> to a <code>MutexGuard</code>, so we need to do two derefs, one of which will have to be explicit since only one can be done implicitly.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>new_urls.par_iter().try_for_each::&lt;_, Result&lt;()&gt;&gt;(|url| {\n // ...\n})?;\n</code></pre>\n<p>Notice that the <code>par_iter</code> call can now end simply with <code>?</code> instead of <code>.unwrap()</code>, because our <code>fn main</code> returns a <code>Result&lt;_&gt;</code>.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>new_urls = found_urls\n .lock()\n .unwrap()\n .difference(&amp;visited.lock().unwrap())\n</code></pre>\n<p>becomes now just (two unwraps gone!)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>new_urls = found_urls\n .lock()?\n .difference(&amp;*visited.lock()?)\n</code></pre>\n<h1>Question every use of .unwrap()</h1>\n<p><code>.unwrap()</code> is a scaaaary thing. Like maggots sprinkled in your code, each of them represents a limitation on the domain of your program. Another situation in which your crawler collapses into the fetal position and cries for its mother. Another reminder that you really can't control much anything at all and you've only been lying to yourself this entire time.</p>\n<p>Take, for example, this code.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>if new_url.has_host() &amp;&amp; new_url.host_str().unwrap() == &quot;rolisz.ro&quot; {\n Some(url.to_string())\n} else {\n None\n}\n</code></pre>\n<p>Grab the URL you found, make sure it has a host, <em>crash the program if it doesn't</em> ... prosaic, indeed</p>\n<p>hold up! <em>crash the program!?</em> ... I don't like the sound of that! Granted, in this case, you're almost guaranteed not to crash because you just checked on the other side of the <code>&amp;&amp;</code> that you wouldn't, but then... why write code that at the first glance reads like it would crash? In this case, you either want to return the url if it has <code>&quot;rolisz.ro&quot;</code> as the host string, or you want to return <code>None</code> in any other situation. Let Rust express what you really mean.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>if let Some(&quot;rolisz.ro&quot;) = new_url.host_str() {\n Some(url.to_string())\n} else {\n None\n}\n</code></pre>\n<p>There are some people who use Rust who like Haskell. They might tell you to write</p>\n<pre class=\"lang-rust prettyprint-override\"><code>Ok(new_url) =&gt; new_url\n .host_str()\n .filter(|&amp;h| h == &quot;rolisz.ro&quot;)\n .map(|_| url.to_string()),\n</code></pre>\n<p>Before choosing this solution please keep in mind that these Haskell people are mean to other people who don't have PhDs.</p>\n<p>Also keep in mind that there are other places where <code>.unwrap()</code> and <code>.expect()</code> are used in your application. Adding to your error enum may be necessary, but in other cases like the one above it may be as simple as rethinking the problem you were trying to solve and finding a new way to express it using the tools Rust gives you. Only add to your error enum when you're sure you've found an edge case that's probably outside of the scope of your program.</p>\n<h1>Multiple Producer, Single Consumer</h1>\n<p><code>.unwrap()</code> is pretty evil, and <code>.lock()</code> is really just more of the same. Every <code>.lock()</code> you find in your codebase is an exclamation that reminds you that your program isn't truly asynchronous. Every <code>.lock()</code> is somewhere where your program has to wait on another thread. That's slow. Why wait when you could, like, <em>do things?</em>. In order to write fast programs, you want to avoid <code>.lock()</code> as much as you can.</p>\n<p>This program uses <code>.lock()</code> a lot. That's because it's using async badly. You slapped <code>par_iter</code> on there, but ... each of your threads has to keep begging for the mutex to get anything done. What if, instead of waiting for exclusive control of the mutex, your threads could just ship off what they have to another thread and get right back to work?</p>\n<p><a href=\"https://doc.rust-lang.org/nightly/std/sync/mpsc/index.html\" rel=\"noreferrer\">mpsc</a> is a channel you can use to send data across threads.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T15:07:30.650", "Id": "238160", "ParentId": "238158", "Score": "23" } }, { "body": "<h1><a href=\"https://github.com/rust-lang/rust-clippy#as-a-cargo-subcommand-cargo-clippy\" rel=\"noreferrer\">Clippy</a></h1>\n\n<p>Clippy helps automatically scan for common mistakes in code. Many of these are from its automatic review. Aside from the suggestions in other answers, consider:</p>\n\n<h2>Don't explicitly use return</h2>\n\n<p>in <code>fetch_url</code>, and just leave it as the one word <code>body</code>.</p>\n\n<h2>Don't use <code>&amp;String</code>: use <code>&amp;str</code></h2>\n\n<p>on lines 16 and 59. You should never (unless you're doing some weird stuff with <code>capacity</code>) pass a <code>&amp;String</code>. This is because anything you'd want to do with it can be done with a simple slice instead, i.e. <code>&amp;str</code>. If you take a <code>String</code> as a parameter, then you require your users to allocate memory on the heap, instead of using a slice that they already have.</p>\n\n<h2>Don't bind a variable to an empty type</h2>\n\n<p>on line 60. Aside from being unused entirely, its type is <code>()</code>, meaning that it contains no data anyways.</p>\n\n<h2>Don't use <code>extern crate</code></h2>\n\n<p>That was the old pre-2018 syntax, and you don't even use that syntax for other libraries anyways.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T01:41:34.160", "Id": "238178", "ParentId": "238158", "Score": "5" } } ]
{ "AcceptedAnswerId": "238160", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T13:44:54.300", "Id": "238158", "Score": "15", "Tags": [ "web-scraping", "rust" ], "Title": "Web crawler in Rust" }
238158
<p>I would like to execute two database queries concurrently for quicker response time. Since channels seemed to be too verbose, I came up with the solution below. However, I'm not very confident about it and wanted to head your opinion and ask if there is a better solution for this. Thank you.</p> <pre><code>go var persistedOrganization models.Organization var persistedProjects []models.Project var fetchOrganizationError error var fetchProjectsError error var wg sync.WaitGroup wg.Add(2) go func() { persistedOrganization, fetchOrganizationError = organization.FindOne(bson.M{"_id": persistedUser.OrganizationID}) wg.Done() }() go func() { persistedProjects, fetchProjectsError = project.Find(bson.M{"organizationId": persistedUser.OrganizationID}) wg.Done() }() wg.Wait() if fetchOrganizationError != nil || fetchProjectsError != nil { // Handle error } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T16:05:15.960", "Id": "238162", "Score": "1", "Tags": [ "go", "concurrency" ], "Title": "Executing two database queries concurrently in Go" }
238162
<p>I'm writing a translate extension for firefox just similar like google translate extension. I achieve that the listening mauseup and mousedown events to get selection text and popup a div that you can click. </p> <p>Due to i am new at javacript, i would like some feedback for above code. Can i do any improvement?</p> <pre><code>var bubbleDOM = document.createElement('div'); bubbleDOM.setAttribute('class', 'selection_bubble'); document.body.appendChild(bubbleDOM); var selection = ""; function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection &amp;&amp; document.selection.type != "Control"){ text = document.selection.createRange().text; } return text; } document.addEventListener("mousedown", checkSelectionText); document.addEventListener("mouseup", checkSelectionText); function checkSelectionText(event) { if (event.target == document.querySelector('.selection_bubble')) { return; } setTimeout(function() { selection = getSelectionText(); if (selection) { document.querySelector('.selection_bubble').style.top = (event.pageY+3) + "px"; document.querySelector('.selection_bubble').style.left = (event.pageX+3) + "px"; document.querySelector('.selection_bubble').style.visibility = 'visible'; } else { document.querySelector('.selection_bubble').style.visibility = 'hidden'; } }); } document.querySelector('.selection_bubble').addEventListener("click", openPopup); function openPopup(event) { chrome.runtime.sendMessage({action: 'openModal', selection: selection}); document.querySelector('.selection_bubble').style.visibility = 'hidden'; event.preventDefault(); event.stopPropagation(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T16:52:22.120", "Id": "238163", "Score": "1", "Tags": [ "javascript", "firefox-webextensions" ], "Title": "Extension content script multiple mouse events handling" }
238163
<p>After lot of research and couple of questions in <a href="https://stackoverflow.com/">https://stackoverflow.com/</a> i managed to create <em>Favorite System</em> in <code>PDO</code> <code>mysql</code> as database. Am not a developer so there may be security issue or better method with my below code.</p> <p><strong>config.php</strong></p> <pre><code>try { //create PDO connection $conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS); $conn-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;exec("SET CHARACTER SET utf8"); } catch (PDOException $e) { //show error echo '&lt;p class="bg-danger"&gt;' . $e-&gt;getMessage() . '&lt;/p&gt;'; exit; } </code></pre> <p><strong>SQL</strong></p> <pre><code>DROP TABLE IF EXISTS `allpostdata`; CREATE TABLE IF NOT EXISTS `allpostdata` ( `id` int(9) NOT NULL AUTO_INCREMENT, `pid` varchar(12) NOT NULL DEFAULT '', .... .... PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; DROP TABLE IF EXISTS `members`; CREATE TABLE IF NOT EXISTS `members` ( `memberID` int(11) NOT NULL AUTO_INCREMENT, `Oauth_pro` varchar(10) DEFAULT NULL, `username` varchar(255) NOT NULL, .... .... PRIMARY KEY (`memberID`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `favorite` ( `memberID` int(9) NOT NULL, `id` int(9) NOT NULL, PRIMARY KEY (`memberID`,`id`), KEY `fk_favorite_post1_idx` (`memberID`), CONSTRAINT `fk_favorite_user` FOREIGN KEY (`memberID`) REFERENCES `members` (`memberID`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_favorite_post1` FOREIGN KEY (`id`) REFERENCES `allpostdata` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p><strong>Post page</strong></p> <pre><code>&lt;?php $email = 'user@mail.com'; // Query to get the user_id $stmt = $conn-&gt;prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" '); $stmt-&gt;execute(array(':email' =&gt; $email)); $row = $stmt-&gt;fetch(); $mbid = $row['memberID']; $pid = '4'; // Query to Get the Director ID $stmt = $conn-&gt;prepare('SELECT * FROM allpostdata WHERE id =:id'); $stmt-&gt;execute(array(':id' =&gt; $pid)); $result = $stmt-&gt;fetchAll(); foreach ($result as $row) { echo "&lt;p&gt;Director: " . $row['tit'] . "&lt;/p&gt; "; $fav_image = checkFavorite($mbid, $pid, $conn); echo "Favorite? : " . $fav_image . ""; } function checkFavorite($mbid, $pid, $conn) { $stmt = $conn-&gt;prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id"); $stmt-&gt;execute(array(':mid' =&gt; $mbid, ':id' =&gt; $pid)); $count = $stmt-&gt;rowCount(); if ($count == 0) { echo "&lt;div class = 'button' method = 'Like' data-user = " . $mbid . " data-post = " . $pid . "&gt; &lt;i class='mi mi_sml' id=" . $pid . "&gt;favorite_border&lt;/i&gt;Add Favorite&lt;/div&gt;"; } else { echo "&lt;div class = 'button' method = 'Unlike' data-user = " . $mbid . " data-post = " . $pid . "&gt; &lt;i class='mi mi_sml text-danger txt_sha' id=" . $pid . "&gt;favorite&lt;/i&gt;Remove Favorite &lt;/div&gt;"; } } ?&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function ($) { $(".button").click(function (e) { e.preventDefault(); const user_id = $(this).attr('data-user'); // Get the parameter user_id from the button const director_id = $(this).attr('data-post'); // Get the parameter director_id from the button const method = $(this).attr('method'); // Get the parameter method from the button if (method === "Like") { $(this).attr('method', 'Unlike'); // Change the div method attribute to Unlike $(this).html('&lt;i class="mi mi_sml text-danger" id="' + director_id + '"&gt;favorite&lt;/i&gt;Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button } else { $(this).attr('method', 'Like'); $(this).html('&lt;i class="mi mi_sml" id="' + director_id + '"&gt;favorite_border&lt;/i&gt;Add Favorite').toggleClass('mybtn button'); } $.ajax({ url: 'favs.php', // Call favs.php to update the database type: 'GET', data: {user_id: user_id, director_id: director_id, method: method}, cache: false, success: function (data) { } }); }); }); &lt;/script&gt; </code></pre> <p><strong>Favs.php</strong></p> <pre><code>&lt;?php include("$_SERVER[DOCUMENT_ROOT]/include/config.php"); $method = clean_input($_GET['method']); $user_id = clean_input($_GET['user_id']); $director_id = clean_input($_GET['director_id']); if ($method == "Like") { $stmt = $conn-&gt;prepare('INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)'); $stmt-&gt;bindParam(':mID', $user_id, PDO::PARAM_INT, 12); $stmt-&gt;bindParam(':pID', $director_id, PDO::PARAM_INT, 12); $stmt-&gt;execute(); } elseif ($method == "Unlike") { $stmt = $conn-&gt;prepare('DELETE FROM favorite WHERE memberID=:mID and id=:pID'); $stmt-&gt;bindParam(':mID', $user_id, PDO::PARAM_INT, 12); $stmt-&gt;bindParam(':pID', $director_id, PDO::PARAM_INT, 12); $stmt-&gt;execute(); } else { //do nothing } function clean_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } </code></pre> <blockquote> <p>Correct me if there are any security flaw</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:37:34.397", "Id": "467421", "Score": "0", "body": "I noticed you don't use the `success` function when the AJAX request succeeds, nor does your `Favs.php` give any feedback. It's there, but it's empty. Normally you first call the AJAX function, and only when it returns successfully you would give the appropriate feedback to the user. This means you could also give the user feedback when the AJAX request fails." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:42:32.230", "Id": "467422", "Score": "0", "body": "But what about this `cache: false,\n success: function (data) {\n }` or how should i do ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T06:26:55.663", "Id": "467924", "Score": "1", "body": "checkFavorite definitely doesn't work as expected https://3v4l.org/0UebU" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T08:58:48.290", "Id": "467931", "Score": "0", "body": "@YourCommonSense it's strange, i didn't notice until you pointed it. what would be wrong ? any advise" } ]
[ { "body": "<p>I noticed you don't use the <code>success</code> function when the AJAX request succeeds, nor does your <code>Favs.php</code> give any feedback. It's there, but it's empty. Normally you first call the AJAX function, and only when it returns successfully you would give the appropriate feedback to the user. This means you could also give the user feedback when the AJAX request fails.</p>\n\n<p>Let me try and add that to your code. I'll start with the middle bit of <code>Favs.php</code>:</p>\n\n<pre><code>switch ($method) {\n case \"Like\" : \n $query = 'INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)';\n break;\n case \"Unlike\" :\n $query = 'DELETE FROM favorite WHERE memberID=:mID and id=:pID';\n break;\n}\n$feedback = 'Fail'; // start with pessimistic feedback\nif (isset($query)) {\n $stmt = $conn-&gt;prepare($query);\n $stmt-&gt;bindParam(':mID', $user_id, PDO::PARAM_INT, 12);\n $stmt-&gt;bindParam(':pID', $director_id, PDO::PARAM_INT, 12);\n if ($stmt-&gt;execute()) $feedback = $method; // feedback becomes method on success\n}\necho json_encode(['id' =&gt; $director_id,\n 'feedback' =&gt; $feedback]);\n</code></pre>\n\n<p>I got rid of duplicated code and I give <code>Like</code>, <code>Unlike</code> or <code>Fail</code> as the feedback to the AJAX call. This code now returns a JSON string containing the <code>director_id</code> and the feedback. This makes sense because it tells you which director was changed and how. You can leave the beginning, and the <code>clean_input()</code> function, in place.</p>\n\n<p>Now in your Javascript you need to respond to what the AJAX call returns.</p>\n\n<pre><code>$(document).ready(function () {\n $('.button').click(function (e) {\n e.preventDefault();\n $.getJSON('favs.php', \n {user_id: $(this).attr('data-user'), \n director_id: $(this).attr('data-post'), \n method: $(this).attr('method')}) \n .done(function(json) {\n switch (json.feedback) {\n case 'Like' :\n $(this).attr('method', 'Unlike'); \n $(this).html('&lt;i class=\"mi mi_sml text-danger\" id=\"' + json.id + '\"&gt;favorite&lt;/i&gt;Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button\n break;\n case 'Unlike' :\n $(this).html('&lt;i class=\"mi mi_sml\" id=\"' + json.id + '\"&gt;favorite_border&lt;/i&gt;Add Favorite').toggleClass('mybtn button');\n $(this).attr('method', 'Like');\n break;\n case 'Fail' : \n alert('The Favorite setting could not be changed.');\n break;\n }\n })\n .fail(function(jqXHR,textStatus,error) {\n alert(\"Error Changing Favorite: \" + error);\n }); \n });\n});\n</code></pre>\n\n<p>I changed your basic AJAX request to a JSON-encoded AJAX request with better fault detection. I moved the changes you make to the button inside the <code>.done()</code> method.</p>\n\n<p>To recap: </p>\n\n<ul>\n<li>Call the AJAX PHP script with all the parameters needed. </li>\n<li>The AJAX PHP script return a JSON string containing what it has done. </li>\n<li>Change the UI according to what was returned.</li>\n</ul>\n\n<p>This way your code is more fault tolerant. </p>\n\n<p>There is still a problem though. Suppose a user has opened two browser windows with exactly the same content. First the favorite button in one is used, and then the exact same button is used in the other window. If I am correct your database will now contain two identical rows in the <code>favorite</code> table. You can prevent this by making the <code>favorite.id</code> column unique. The query will then fail and the feedback in the second window should become: \"The Favorite setting could not be changed.\".</p>\n\n<p>Also note: Because you supply the <code>user_id</code> as a parameter to the AJAX call I can easily change the favorites of other users by changing this id. It is better to store the <code>user_id</code> in a session and use that in the AJAX PHP script.</p>\n\n<p>I hope this helps you. I haven't tested the code, so I don't exclude the possibility of some errors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T18:27:40.377", "Id": "468998", "Score": "0", "body": "**AJAX not changing UI** but i can see `{id: \"36\", feedback: \"Unlike\"}\nid: \"36\"\nfeedback: \"Unlike\"` in inspect->XHR->preview," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T07:20:27.910", "Id": "469031", "Score": "1", "body": "As I said: I haven't tested the code. Here we review your code and help you to improve it. The debugging is up to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T14:50:34.433", "Id": "469092", "Score": "0", "body": "any help would be appreciated. https://stackoverflow.com/questions/60759461/unable-to-change-button-ui-on-ajax-getjson-done" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T12:43:41.763", "Id": "238365", "ParentId": "238164", "Score": "3" } } ]
{ "AcceptedAnswerId": "238365", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T17:45:07.210", "Id": "238164", "Score": "3", "Tags": [ "php", "mysql", "security", "pdo" ], "Title": "Add post to favorite in PDO and mysql" }
238164
<p>I've started learning C++ using Microsoft Visual Studio. I'm decided to create a simple GUI program that creates a "snowflake" wherever the user clicks on the screen. Seeing as how this is my first C++ program, I would greatly appreciate feedback on any aspect of my code.</p> <p><strong>snowflakes.cpp</strong></p> <pre><code>// Includes // #include &lt;SFML/Graphics.hpp&gt; #include &lt;SFML/Window.hpp&gt; #include &lt;iostream&gt; // Declare function // void snowflakes(); /** * Creates a snowflake where the user clicks on the screen. **/ void snowflakes() { const int WIDTH = 1280; const int HEIGHT = 960; sf::RenderWindow render_window( sf::VideoMode(WIDTH, HEIGHT), "Snowflakes" ); sf::Event event; sf::Image image; sf::Mouse mouse; image.create(WIDTH, HEIGHT, sf::Color::Black); sf::Texture texture; while (render_window.isOpen()) { while (render_window.pollEvent(event)) { if (event.type == sf::Event::EventType::Closed) { render_window.close(); } else if (event.type == sf::Event::MouseButtonPressed) { int mouse_x = mouse.getPosition(render_window).x; int mouse_y = mouse.getPosition(render_window).y; std::cout &lt;&lt; mouse_x &lt;&lt; " " &lt;&lt; mouse_y &lt;&lt; std::endl; image.setPixel(mouse_x, mouse_y, sf::Color::White); // Get random size of snowflake // int size = (rand() % 20) + 10; for (int i = 1; i &lt; size; i++) { image.setPixel(mouse_x + i, mouse_y, sf::Color::White); image.setPixel(mouse_x - i, mouse_y, sf::Color::White); image.setPixel(mouse_x, mouse_y + i, sf::Color::White); image.setPixel(mouse_x, mouse_y - i, sf::Color::White); image.setPixel(mouse_x + i, mouse_y + i, sf::Color::White); image.setPixel(mouse_x - i, mouse_y - i, sf::Color::White); image.setPixel(mouse_x + i, mouse_y - i, sf::Color::White); image.setPixel(mouse_x - i, mouse_y + i, sf::Color::White); } } } texture.loadFromImage(image); sf::Sprite dots(texture); render_window.clear(); render_window.draw(dots); render_window.display(); } } int main() { // Start program // snowflakes(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T22:26:38.757", "Id": "467105", "Score": "0", "body": "Doesn't sfml need some initialization anymore?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T23:46:45.850", "Id": "467110", "Score": "0", "body": "Three loops deep is a bit much (+ a branch)... C++ devs may not like the Egyptian braces. I'd also like a `drawSnowflake` method in there. The how is clearly well done, but the **what** seems a bit missing in action." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T01:07:26.990", "Id": "467113", "Score": "0", "body": "@πάνταῥεῖ apparently, no. I was surprised as well :)" } ]
[ { "body": "<p>Welcome to C++. Nice and readable C++ code!</p>\n\n<p>I'm not familiar with SFML, but here are my suggestions about improving the code:</p>\n\n<ul>\n<li><p>When you get familiar with C++, comments like these can be deleted: <code>// Includes //</code> <code>// Declare function //</code> <code>// Start program //</code>.</p></li>\n<li><p>You don't need to declare a function first if you define it immediately after.</p></li>\n<li><p>These constants can be made <code>constexpr</code>:</p>\n\n<pre><code>const int WIDTH = 1280;\nconst int HEIGHT = 960;\n</code></pre>\n\n<p>Also, <code>ALL_CAPS</code> names are generally reserved for macros. Constants can use <code>lower_case</code> names instead.</p></li>\n<li><p>This <code>if</code> statement (note that <code>::EventType</code> is sometimes included but sometimes omitted):</p>\n\n<pre><code>if (event.type == sf::Event::EventType::Closed) {\n // ...\n} else if (event.type == sf::Event::MouseButtonPressed) {\n // ...\n}\n</code></pre>\n\n<p>can be replaced by a <code>switch</code> statement since <a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Event.php#af41fa9ed45c02449030699f671331d4a\" rel=\"nofollow noreferrer\"><code>event.type</code> happens to be an enum</a>. Also, since you are using <a href=\"/questions/tagged/c%2b%2b20\" class=\"post-tag\" title=\"show questions tagged &#39;c++20&#39;\" rel=\"tag\">c++20</a>, you can use the <code>using enum</code> feature to simplify your code if your compiler supports it:</p>\n\n<pre><code>switch (event.type) {\n using enum sf::Event::EventType;\ncase Closed:\n // ...\n break;\ncase MouseButtonPressed:\n // ...\n break;\n}\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>int mouse_x = mouse.getPosition(render_window).x;\nint mouse_y = mouse.getPosition(render_window).y;\nstd::cout &lt;&lt; mouse_x &lt;&lt; \" \" &lt;&lt; mouse_y &lt;&lt; std::endl;\n</code></pre>\n\n<p>can be simplified with structured bindings since <a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Vector2.php\" rel=\"nofollow noreferrer\"><code>Vector2i</code></a>, the return type of <code>getPosition</code>, seems to have public members. (I almost wrote \"don't use <code>std::endl</code>,\" but then I realized that flushing semantics is appropriate here!)</p>\n\n<pre><code>auto [x, y] = mouse.getPosition(render_window);\nstd::cout &lt;&lt; x &lt;&lt; ' ' &lt;&lt; y &lt;&lt; std::endl;\n</code></pre></li>\n<li><p>The rendering code deserves a separate function:</p>\n\n<pre><code>image.setPixel(mouse_x, mouse_y, sf::Color::White);\n\n// Get random size of snowflake //\n\nint size = (rand() % 20) + 10;\n\nfor (int i = 1; i &lt; size; i++) {\n image.setPixel(mouse_x + i, mouse_y, sf::Color::White);\n image.setPixel(mouse_x - i, mouse_y, sf::Color::White);\n image.setPixel(mouse_x, mouse_y + i, sf::Color::White);\n image.setPixel(mouse_x, mouse_y - i, sf::Color::White);\n image.setPixel(mouse_x + i, mouse_y + i, sf::Color::White);\n image.setPixel(mouse_x - i, mouse_y - i, sf::Color::White);\n image.setPixel(mouse_x + i, mouse_y - i, sf::Color::White);\n image.setPixel(mouse_x - i, mouse_y + i, sf::Color::White);\n}\n</code></pre>\n\n<p>Also, consider using the <code>&lt;random&gt;</code> library instead of <code>rand</code>:</p>\n\n<pre><code>std::mt19937_64 engine{std::random_device{}()}; // global or static\n</code></pre>\n\n<p>then</p>\n\n<pre><code>std::uniform_int_distribution&lt;int&gt; dist{10, 29}; // clearer than (rand() % 20) + 10\nint size = dist(eng);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T20:48:51.613", "Id": "467834", "Score": "0", "body": "Thanks, L. F.! Unfortunately my current compiler doesn't support `using enum`, but all your other suggestions are great. Thanks for the review!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T08:58:05.563", "Id": "238188", "ParentId": "238172", "Score": "2" } } ]
{ "AcceptedAnswerId": "238188", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T22:23:08.877", "Id": "238172", "Score": "4", "Tags": [ "c++", "beginner", "sfml", "c++20" ], "Title": "Snowflakes in C++" }
238172
<p>I have implemented Dijkstra's algorithm in C++, but it seems a bit complicated since I really tried to follow the process of the algorithm as much as I could. If there's any simplification you would suggest, I would really appreciate, because this task was only for me to get familiarized with this method before the A* algorithm. The whole class thing about the nodes might be unnecesary, but I really like to think of these objects and to treat them like real things.</p> <p>EDIT: I noticed I should've added a field that shows whether a node is open or not, in order to eliminate pushing the same node twice to the priority queue.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;queue&gt; #include &lt;climits&gt; using namespace std; class Node { int label; int d; // Overall distance from the start point bool processed; // Visited node indicator Node* parent; vector&lt;Node*&gt; neighbors; vector&lt;int&gt; dist; // Distance from each heighbor public: Node(int = 0); void addNeighbor(Node*); void addDist(int); void setLabel(int); void setD(int); void setProccessed(bool); void setParent(Node*); int getLabel(); int getD(); bool isProcessed(); Node* getParent(); vector&lt;Node *&gt; getNeighbors(); vector&lt;int&gt; getDist(); }; Node::Node(int label) { this-&gt;label = label; } void Node::addNeighbor(Node* neighbor) { neighbors.push_back(neighbor); } void Node::addDist(int d) { dist.push_back(d); } void Node::setLabel(int label) { this-&gt;label = label; } void Node::setD(int d) { this-&gt;d = d; } void Node::setParent(Node* node) { parent = node; } void Node::setProccessed(bool p) { processed = p; } int Node::getLabel() { return label; } int Node::getD() { return d; } Node* Node::getParent() { return parent; } bool Node::isProcessed() { return processed; } vector&lt;Node*&gt; Node::getNeighbors() { return neighbors; } vector&lt;int&gt; Node::getDist() { return dist; } void init(ifstream&amp; f, Node**&amp; nodes, int&amp; n) { f &gt;&gt; n; nodes = new Node*[n]; int** adj = new int*[n]; for (int i = 0; i &lt; n; i++) { adj[i] = new int[n]; } for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; n; j++) { adj[i][j] = 0; } } int label, start, end, weight; while(f &gt;&gt; start &gt;&gt; end &gt;&gt; weight) { adj[start - 1][end - 1] = weight; adj[end - 1][start - 1] = weight; } for (int i = 0; i &lt; n; i++) { nodes[i] = new Node(i + 1); } for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; n; j++) { if (adj[i][j] != 0) { nodes[i]-&gt;addNeighbor(nodes[j]); nodes[i]-&gt;addDist(adj[i][j]); } } } for (int i = 0; i &lt; n; i++) { delete[] adj[i]; } delete[] adj; } void initNodes(Node** nodes, int n) { for (int i = 0; i &lt; n; i++) { nodes[i]-&gt;setD(INT_MAX); nodes[i]-&gt;setParent(NULL); nodes[i]-&gt;setProccessed(false); } } class Compare { public: bool operator()(Node* n1, Node* n2) { return n1-&gt;getD() &gt; n2-&gt;getD(); } }; void writePath(Node* node) { if (node) { int label = node-&gt;getLabel(); node = node-&gt;getParent(); writePath(node); if(node) { cout &lt;&lt; " -&gt; "; } cout &lt;&lt; label; } } void dijkstra(Node** nodes, int n) { cout &lt;&lt; "Dijkstra algorithm" &lt;&lt; endl; int start = 1; int end = 7; initNodes(nodes, n); nodes[start - 1]-&gt;setD(0); priority_queue&lt;Node*, vector&lt;Node*&gt;, Compare&gt; queue; queue.push(nodes[start - 1]); Node* current; do { current = queue.top(); queue.pop(); current-&gt;setProccessed(true); vector&lt;Node *&gt; neighbors = current-&gt;getNeighbors(); for (unsigned int i = 0; i &lt; neighbors.size(); i++) { if((!neighbors.at(i)-&gt;isProcessed())) { if((neighbors.at(i)-&gt;getD() == INT_MAX || (current-&gt;getD() + current-&gt;getDist().at(i) &lt; neighbors.at(i)-&gt;getD()))) { neighbors.at(i)-&gt;setParent(current); neighbors.at(i)-&gt;setD(current-&gt;getD() + current-&gt;getDist().at(i)); } queue.push(neighbors.at(i)); } } } while(current-&gt;getLabel() != end); /* */ writePath(current); cout &lt;&lt; endl; } int main() { ifstream f("input.in"); int numOfNodes; Node** nodes; init(f, nodes, numOfNodes); for (int i = 0; i &lt; numOfNodes; i++) { vector&lt;Node *&gt; neighbors = nodes[i]-&gt;getNeighbors(); cout &lt;&lt; i + 1 &lt;&lt; ": "; for (int j = 0; j &lt; neighbors.size(); j++) { cout &lt;&lt; neighbors[j]-&gt;getLabel() &lt;&lt; " "; } cout &lt;&lt; endl; } cout &lt;&lt; endl; dijkstra(nodes, numOfNodes); for (int i = 0; i &lt; numOfNodes; i++) { delete nodes[i]; } delete[] nodes; return 0; } </code></pre> <p>INPUT:</p> <pre><code>8 1 3 2 1 4 4 2 3 3 2 5 4 2 6 5 3 4 1 5 7 6 5 8 3 6 7 5 7 8 1 </code></pre>
[]
[ { "body": "<h2>Avoid <code>using namespace std;</code></h2>\n\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n\n<h2>Missing Error Checking</h2>\n\n<p>There is no guarantee that the input file <code>input.io</code> exists, so a test after </p>\n\n<h2>Return Values From Functions</h2>\n\n<p>It is generally better to return values from functions rather than passing in references to variables. It is also better to use C++ container classes rather than old C style arrays in C++. An example of this is the init function. If a vector was used rather than an old C style array the vector could be returned, and the array and count would not need to be passed in by reference. In addition the number of nodes would be contained in the vector so the 2 variables wouldn't be necessary, only the vector is necessary.</p>\n\n<p>Doing this would also simplify the <code>init()</code> function.</p>\n\n<pre><code>std::vector&lt;Node *&gt; init(ifstream &amp;fileIO) {\n size_t n;\n fileIO &gt;&gt; n;\n\n std::vector&lt;Node *&gt; nodes;\n\n std::vector&lt;std::vector&lt;int&gt;&gt; adj;\n for (size_t i = 0; i &lt; n; i++) {\n std::vector&lt;int&gt; subAdj;\n for (size_t j = 0; j &lt; n; j++) {\n subAdj.push_back(0);\n }\n adj.push_back(subAdj);\n }\n\n int start;\n int end\n int weight;\n while (fileIO &gt;&gt; start &gt;&gt; end &gt;&gt; weight) {\n adj[start - 1][end - 1] = weight;\n adj[end - 1][start - 1] = weight;\n }\n\n for (size_t i = 0; i &lt; n; i++) {\n nodes.push_back(new Node(i + 1));\n }\n\n for (size_t i = 0; i &lt; n; i++)\n {\n for (size_t j = 0; j &lt; n; j++)\n {\n if (adj[i][j] != 0)\n {\n nodes[i]-&gt;addNeighbor(nodes[j]);\n nodes[i]-&gt;addDist(adj[i][j]);\n }\n }\n }\n\n return nodes;\n}\n</code></pre>\n\n<h2>Reducing the Need to Allocate and Delete Data Structures</h2>\n\n<p>Because the code is utilizing old style C arrays and pointers there is memory allocation and memory de-allocation involved. Using a C++ container class such as std::vector would reduce this. Defining the vector within the function as a local variable would allow the variable to be deleted automatically when the function ended as shown above. </p>\n\n<h2>Prefer size_t Over int</h2>\n\n<p>In C++ it is better to use the <code>size_t</code> type for indexing through arrays and vectors rather than using an int. Generally indexes should never go negative and <code>size_t</code> is unsigned rather than <code>signed</code>.</p>\n\n<h2>The <code>this</code> Pointer</h2>\n\n<p>Generally in C++ it isn't necessary to use the <code>this</code> pointer to access members of a class. In this code it was necessary because of name collisions between the input variable and the member variable. One way around this in the current code would be to make the member variable names clearer, this would also remove the necessity for comments in the class declaration:</p>\n\n<pre><code>class Node {\n int label;\n int distanceFromOrigin;\n bool processed; // Visited node indicator\n Node* parent;\n vector&lt;Node*&gt; neighbors;\n vector&lt;int&gt; dist; // Distance from each heighbor\n\npublic:\n Node(int = 0);\n void addNeighbor(Node*);\n void addDist(int);\n void setLabel(int);\n void setD(int);\n void setProccessed(bool);\n void setParent(Node*);\n int getLabel();\n int getD();\n bool isProcessed();\n Node* getParent();\n vector&lt;Node*&gt; getNeighbors();\n vector&lt;int&gt; getDist();\n};\n\nNode::Node(int Label) {\n label = Label;\n}\n\nvoid Node::setD(int Distance) {\n distanceFromOrigin = Distance;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T18:39:20.017", "Id": "238262", "ParentId": "238173", "Score": "2" } }, { "body": "<h2>Overview</h2>\n\n<p>Dijkstra Algorithm my favorite algorithm :-)</p>\n\n<p>I wrote an overview of how to do it <a href=\"https://stackoverflow.com/a/3448361/14065\">StackOverflow</a>: </p>\n\n<p>My main observation is that you have crammed three things together that I would separate into three district code reviews (and thus three independent pieces of code). As a result I think your code is very tightly coupled where I think a loose coupling would be better design</p>\n\n<ol>\n<li>I would separate the graph into its own class.<br>\nNodes/edges and their relationship should be completely independent to the algorithm.<br>\nYes there is a common shared interface but given a graph written by somebody else I could write a simple wrapper over the graph and still make it work with your algorithm.</li>\n<li>You store the intermediate information about the traversal inside you node structure.<br>\nI would separate this out into its own independent structure that is held separately to the graph.<br>\nThis can be customized what you want out of the algorithm (just best distance, or the route).</li>\n<li>The algorithm should be independent of the graph and depend on a small interface.</li>\n</ol>\n\n<h3>The simplest interface:</h3>\n\n<pre><code>NodeId Graph::getNodeFromName(Name);\nListOFEdge Graph::getOutputEdges(NodeId);\nEdge Is {Src(NodeId)/Dst(NodeId)/Cost(None negative value)}\n</code></pre>\n\n<p>This should be all you need.</p>\n\n<h2>Code Review</h2>\n\n<p>Please stop this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Read this article: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a>\nMy favorite answer is <a href=\"https://stackoverflow.com/a/1453605/14065\">the second</a>.</p>\n\n<p>This should explain why using this can cause unexpected errors in all sorts of situation where you would not expect it.</p>\n\n<hr>\n\n<p>In the class node:</p>\n\n<pre><code>class Node {\n</code></pre>\n\n<p>Data that is only relevant to a traversal algorithm. Its not relevant to the Node object and thus should not be here.</p>\n\n<pre><code> int d; // Overall distance from the start point\n bool processed; // Visited node indicator\n</code></pre>\n\n<p>A node in a graph has a parent?</p>\n\n<pre><code> Node* parent;\n // OK. Having read all the way down to the algorithm I finally found it.\n // You are recording the shortest path through the graph using this\n // member.\n // So I would add this to the members that belong to the algorithm\n // rather than the node/graph. So some of the following comments\n // about parents are out-dated by this final realization.\n //\n // Better name for this member is defiantly needed.\n</code></pre>\n\n<p>These two members seem to be about the same thing. We are these in two different members?</p>\n\n<pre><code> vector&lt;Node*&gt; neighbors; \n vector&lt;int&gt; dist; // Distance from each heighbor\n</code></pre>\n\n<p>I would have combined them into single structure so that they always move around together.</p>\n\n<pre><code> vector&lt;std::pair&lt;Node*, int&gt;&gt; edge; // destination and cost.\n</code></pre>\n\n<hr>\n\n<p>Wow this is an extensive interface for Node that does very little to help encapsulation. I would argue that this breaks encapsulation as you can simply modify anything without any control.</p>\n\n<hr>\n\n<p>There is a default ID of zero to node?</p>\n\n<pre><code> Node(int = 0);\n</code></pre>\n\n<p>So you can make lots of node's with ID of zero. I would definitely not make this a default value. I would go one step further and say that the user should not be setting the ID of the nodes (this is an internal property of the graph that is set internally).</p>\n\n<p>The user may look up the ID of a node using a name but the user should not be able to set or alter the ID of node. It must be unique and therefore setting it is part of the graphs responcability.</p>\n\n<hr>\n\n<p>Why can you add a neighbor and distance independently. This is just begging for bugs to happen. An edge has a destination and a cost.</p>\n\n<pre><code> void addNeighbor(Node*);\n void addDist(int);\n</code></pre>\n\n<p>Now some graphs edge are bidirectional (others they are not). But when you have bidirectional edges the graph should provide a simpler interface that internally adds all the appropriate internal structures.</p>\n\n<pre><code> // Adding a bi-directional edge.\n Graph::addEdge(Node&amp; src, Node&amp; dst, int cost) {\n src.addEdge(dst, cost);\n dst.addEdge(src, cost);\n }\n</code></pre>\n\n<hr>\n\n<p>Why are these modifiable externally?</p>\n\n<pre><code> void setLabel(int);\n void setD(int);\n</code></pre>\n\n<p>Are these not set as part of the constructor to the node?</p>\n\n<hr>\n\n<p>This is not part of a Node property but rather a property of the algorithm.</p>\n\n<pre><code> void setProccessed(bool);\n bool isProcessed();\n</code></pre>\n\n<hr>\n\n<p>Why does a node have a parent.</p>\n\n<pre><code> void setParent(Node*);\n Node* getParent();\n</code></pre>\n\n<hr>\n\n<p>Sure you can get the label/ID.</p>\n\n<pre><code> int getLabel();\n int getD();\n</code></pre>\n\n<p>But these should be const members (they don't change the state).</p>\n\n<hr>\n\n<p>Yes this is valid:</p>\n\n<pre><code> vector&lt;Node *&gt; getNeighbors();\n vector&lt;int&gt; getDist();\n</code></pre>\n\n<p>But like the internal structure I would return a list of edge information (destination and cost as one composite value).</p>\n\n<hr>\n\n<p>Don't use <code>this-&gt;</code>.</p>\n\n<pre><code>Node::Node(int label) {\n this-&gt;label = label;\n}\n</code></pre>\n\n<p>The only reason to use <code>this-&gt;</code> is to distinguish a local variable from a member variable. This means you have shadowed a member variable with a local. The compiler can not detect when you accidentally forget to use <code>this-&gt;</code> and thus can not generate any errors.</p>\n\n<p>It is better to use very distinct meaningful variable names. That way when you use the wrong name it is easy to spot in the code. Also the compiler can easily detect shadowed variables and warn you about them.</p>\n\n<p><strong>BUT</strong> in this case there is no need. You can use itializer lists to solve this issue.</p>\n\n<pre><code>Node::Node(int label) {\n this-&gt;label = label;\n}\n</code></pre>\n\n<p>In a constructor you should use initializer list.</p>\n\n<pre><code>Node::Node(int label)\n : label(label) // These are distinct and works as expected.\n{}\n</code></pre>\n\n<p>Also using initializer list makes sure you don't initialize then overwrite a variable.</p>\n\n<hr>\n\n<p>Put simple one liners in the class declaration:</p>\n\n<pre><code>class Node\n{\n void Node::addNeighbor(Node* neighbor) {neighbors.push_back(neighbor);}\n void Node::addDist(int d) {dist.push_back(d);}\n // etc\n}\n</code></pre>\n\n<hr>\n\n<p>I mentioned shadowed variables above:</p>\n\n<pre><code>void Node::setD(int d) {\n this-&gt;d = d;\n}\n\n// Easier to read understand and let the compiler check written like this:\n\nvoid Node::setD(int distance) {\n d = distance;\n}\n</code></pre>\n\n<hr>\n\n<p>I would write a graph like this:</p>\n\n<pre><code> class Graph\n {\n public:\n class Node\n {\n public:\n std:vector&lt;Edge&gt; const&amp; getEdges() const;\n };\n class Edge\n {\n public:\n Node&amp; getDst() const;\n int getCost() const;\n };\n Node&amp; addNode(std::string const&amp; name);\n void addEdge(Node&amp; src, Node&amp; dst, int cost);\n\n Node&amp; getNode(std::string const&amp; name);\n};\n</code></pre>\n\n<p>Notice: There are no pointers in the interface.</p>\n\n<hr>\n\n<p>This is fine.</p>\n\n<pre><code>void init(ifstream&amp; f, Node**&amp; nodes, int&amp; n) {\n</code></pre>\n\n<p>Though I would phrase the interface differently. In C++ we use the input operator <code>operator&gt;&gt;</code> to read a stream into an object. So I would define it like this:</p>\n\n<pre><code>std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Graph&amp; graph){\n{\n graph.load(stream); // So you need to add a load() method above.\n return stream;\n}\n</code></pre>\n\n<hr>\n\n<p>In modern C++ it is exceedingly rare to see new/delete.</p>\n\n<pre><code> nodes = new Node*[n];\n</code></pre>\n\n<p>Dynamic allocation is usually handled by structures designed to handle the allocation and correct destruction of the memory. In modern C++ this is either a smart pointer (std::unqiue_ptr or std::shared_ptr) or a container (std::vector / std::list / std::map etc)</p>\n\n<p>In this case I would have used <code>std::vector&lt;Node&gt;</code>.</p>\n\n<p>So all this code:</p>\n\n<pre><code> nodes = new Node*[n];\n int** adj = new int*[n];\n for (int i = 0; i &lt; n; i++) {\n adj[i] = new int[n];\n }\n</code></pre>\n\n<p>Can be replaced by:</p>\n\n<pre><code> std::vector&lt;Node&gt; nodes;\n nodes.reserve(n);\n</code></pre>\n\n<hr>\n\n<p>Just like not using new/delete above you should not in general be using pointers (yes overly broad). But if the objects can not be <code>nullptr</code> then you should be using references. As you get more advanced pointers creep back in but in general try and stick with references and passing by value.</p>\n\n<p>Here:</p>\n\n<pre><code>class Compare {\npublic:\n bool operator()(Node* n1, Node* n2) {\n return n1-&gt;getD() &gt; n2-&gt;getD();\n }\n};\n</code></pre>\n\n<p>I would write this to use references (as I don't need to check the value are <code>nullptr</code>.</p>\n\n<pre><code>class Compare {\npublic:\n bool operator()(Node const&amp; n1, Node const&amp; n2) {\n return n1.getD() &gt; n2.getD();\n }\n};\n</code></pre>\n\n<hr>\n\nDijkstra\n\n<pre><code>void dijkstra(Node** nodes, int n) {\n</code></pre>\n\n<p>Yes.</p>\n\n<pre><code> priority_queue&lt;Node*, vector&lt;Node*&gt;, Compare&gt; queue;\n</code></pre>\n\n<p>Normally for Dijkstra there are two structures. The ordered list you have. A list of already processed nodes. You seem to be missing the second (I suppose it is stored as part of your graph model).</p>\n\n<pre><code> do {\n current = queue.top();\n queue.pop();\n\n // You forgot to check if it has already been processed.\n // Ahhh. I see that you check that in the loop below.\n // The problem is that a node can still be added several times\n // to the priority queue before it is processed.\n //\n // Thus you should check here to see if it has been processed\n // and continue with the next loop if it was processed.\n current-&gt;setProccessed(true);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T23:51:05.717", "Id": "467387", "Score": "0", "body": "First of all big thank you for your time for adding such a detailed comment. The thing is, I didn't really think much when I started writing the code, making a graph interface like this is definitely nicer. I also remember last year that was the way I wrote my codes for my graph algorithm assignments. Also I'm not really used to use std containers, that's why I sometimes avoid them. We were thaught to use our own codes. The default constructor was only because of the new operator, so the need of the setter functions was necessary in this scenario." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:14:30.507", "Id": "467388", "Score": "0", "body": "You should definitely use the standard libraries. Writing your own memory management code is very tricky (even for experts). In production code you would not want anything to do with code that used new/delete as it is not generally exception safe. You need to wrap this stuff up in a class so the container can do the correct memory management with constructor/destructor even when exceptions are propagating. Once you start doing that you see this is all done for you using the standard." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T05:59:24.677", "Id": "238288", "ParentId": "238173", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T22:54:17.767", "Id": "238173", "Score": "4", "Tags": [ "c++", "algorithm", "pathfinding" ], "Title": "Dijkstra Algorithm implementation in C++" }
238173
<p>This is a popular question in machine coding rounds. The requirements are to build a URL shortener. There are certain registered users who have the capability to define a URL and an optional time to live. The system generates a shortened URL. The unregistered users can also generate a shortened URL with a predefined TTL. This is the URLshortener Class.</p> <pre><code>package urlshortener; import hashalgorithm.IHashStrategy; import java.util.*; public class UrlShortener { private IHashStrategy iHashStrategy; private Map&lt;String, List&lt;Url&gt;&gt; userToUrl; private List&lt;String&gt; registeredUser; static final int DEFAULT_TIME_TO_LIVE_IN_MILLIS = 500000; public UrlShortener(IHashStrategy instanceOfConcreteHashStrategy) { iHashStrategy = instanceOfConcreteHashStrategy; userToUrl = new HashMap&lt;&gt;(); registeredUser = new ArrayList&lt;&gt;(); registeredUser.add("abc"); registeredUser.add("bad"); registeredUser.add("bac"); registeredUser.add("lom"); registeredUser.add("DEFAULT"); } public List&lt;Url&gt; getListOfShortenedUrlForUser(String userId) { List&lt;Url&gt; urlList = getUrls(userId); userToUrl.put(userId,urlList); return urlList; } public void addNewEntryForUser(String url,String userId) { addNewEntryForUserWithTTL(url,userId,DEFAULT_TIME_TO_LIVE_IN_MILLIS); } private boolean checkExistenceForShortenedUrl(String shortenedUrl) { for(Map.Entry&lt;String,List&lt;Url&gt;&gt; entry : userToUrl.entrySet()) { List&lt;Url&gt; urlList = entry.getValue(); for(int i = 0 ; i &lt; urlList.size() ; i++) { if(urlList.get(i).getShortenedUrl().equalsIgnoreCase(shortenedUrl)) return true; } } return false; } public void addNewEntryForUserWithTTL(String url,String userId,int timeToLive) { if(!registeredUser.contains(userId)) { System.out.println("userId is not registered. Treated as default!"); userId = "DEFAULT"; } List&lt;Url&gt; urlList = userToUrl.get(userId); String shortenedUrl = iHashStrategy.getHashFromUrl(url); while(checkExistenceForShortenedUrl(shortenedUrl)) { shortenedUrl = iHashStrategy.getHashFromUrl(url); } System.out.println(shortenedUrl); Url urlToInsert = new Url(url,shortenedUrl,timeToLive,new Date()); if(urlList == null) urlList = new ArrayList&lt;&gt;(); urlList.add(urlToInsert); userToUrl.put(userId,urlList); } public String getShortenedUrlForUser(String url,String userId) { if(!registeredUser.contains(userId)) { System.out.println("userId is not registered. Treated as default!"); userId = "DEFAULT"; } List&lt;Url&gt; urlList = getUrls(userId); for(int i = 0 ; i &lt; urlList.size(); i++) { if(urlList.get(i).getOriginalUrl().equalsIgnoreCase(url)) return urlList.get(i).getShortenedUrl(); } return null; } private List&lt;Url&gt; getUrls(String userId) { List&lt;Url&gt; urlList = userToUrl.get(userId); for (int i = 0; i &lt; urlList.size(); i++) { Url currentUrl = urlList.get(i); if (!currentUrl.isValid()) { urlList.remove(i); } } return urlList; } public String getLongUrlForUser(String shortUrl,String userId) { List&lt;Url&gt; urlList = getUrls(userId); for(int i = 0 ; i &lt; urlList.size(); i++) { if(urlList.get(i).getShortenedUrl().equalsIgnoreCase(shortUrl)); return urlList.get(i).getOriginalUrl(); } return null; } } </code></pre> <p>And this is URL.java</p> <pre><code>package urlshortener; import java.util.Date; public class Url { private String originalUrl; private String shortenedUrl; private int timeToLive; private Date date; public Url(String originalUrl, String shortenedUrl, int timeToLive, Date date) { this.setShortenedUrl(shortenedUrl); this.setTimeToLive(timeToLive); this.setOriginalUrl(originalUrl); this.setDate(date); } public boolean isValid() { Date timeNow = new Date(); Date expireDate = new Date(this.getDate().getTime() + getTimeToLive()); return timeNow.before(expireDate); } public String getOriginalUrl() { return originalUrl; } public void setOriginalUrl(String originalUrl) { this.originalUrl = originalUrl; } public String getShortenedUrl() { return shortenedUrl; } public void setShortenedUrl(String shortenedUrl) { this.shortenedUrl = shortenedUrl; } public int getTimeToLive() { return timeToLive; } public void setTimeToLive(int timeToLive) { this.timeToLive = timeToLive; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } </code></pre> <p>For the rest of the code please refer to <a href="https://github.com/suryasis-hub/urlshortener/tree/master/src" rel="nofollow noreferrer">https://github.com/suryasis-hub/urlshortener/tree/master/src</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T07:04:45.597", "Id": "467121", "Score": "1", "body": "Welcome to Code Review. You are using `Date` class , some reason to not use [java time API](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) ?" } ]
[ { "body": "<h1>Usability</h1>\n<p>In your github mainclass, you're asking the user:</p>\n<blockquote>\n<pre><code>System.out.println(&quot;Enter command type&quot;);\n</code></pre>\n</blockquote>\n<p>Then expecting them to enter a number. Consider adding some kind of menu so that people that haven't used the application before know what number 3 does before selecting it and getting the message 'UnRegistered user wants to enter a website'.</p>\n<h1>Usage</h1>\n<p>You haven't specified how you're expecting your URL shortener to be used. To me, the current setup doesn't really make sense. The reason I shorten a URL is so that I can share it with other people, so I'm expecting two main uses:</p>\n<ol>\n<li>Create short URL from real URL, as a registered/unregistered user</li>\n<li>Get real URL from short URL</li>\n</ol>\n<p>The way you've coded it, it looks like as a registered user, only I can access my shortened URL mappings. This seems flawed in a practical usage sense.</p>\n<h1>Time To Live</h1>\n<p>You've got two public methods on the class</p>\n<blockquote>\n<pre><code>public void addNewEntryForUser(String url,String userId) {\n\npublic void addNewEntryForUserWithTTL(String url,String userId,int timeToLive) {\n</code></pre>\n</blockquote>\n<p>The first simply calls the second passing in the default TTL. According to your requirements, only registered users should be able to set a TTL, however the class supports anybody setting a TTL, as long as they call the method with the time to live parameter. This <em>might</em> be OK, but it really depends on who owns the logic to use a default TTL for certain users. At the moment that's not clear. I'd also consider overloading these methods as <code>addNewEntryForUser</code>, I don't think having the <code>WithTTL</code> in the method name really gives you anything over the extra parameter.</p>\n<h1>Time to Die</h1>\n<p>There doesn't appear to be any expiry logic - Not really true, but it's not obvious. Rather than calling the method <code>isValid</code>, something like <code>isExpired</code>, <code>isTTLExpired</code> would make it more obvious that the expiration is triggered by this method.</p>\n<h1>Responsibilities</h1>\n<p>It feels like your shortener is doing too much. It could just shorten URLs. However, it's also responsible for storing a list of registered users, the list of all shortened URLs by user, setting TTL. At a minimum, I'd extract the registered user list from the class and provide some way to get it via the classes constructor (either a repository, or even just a supplied list) to give some separation. Hard coded user Id's really shouldn't be in this class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T23:06:03.153", "Id": "238207", "ParentId": "238181", "Score": "4" } }, { "body": "<p>I'm concentrating on...</p>\n\n<p><strong>Naming</strong></p>\n\n<pre><code>private IHashStrategy iHashStrategy;\n</code></pre>\n\n<p>The name <code>iHashStrategy</code> tells nothing about the purpose of the field. It simply repeats the name of the type. The field is used for hashing the URLs so <code>urlHashStrategy</code> would be a more descriptive field name.</p>\n\n<p>Since the <code>IHashStrategy</code> class is in <code>hashalgorithm</code> package, nothing in their names suggest that the interface is specific to hashing URLs (I'm assuming this is the case because the interface contains a very specific <code>getHashFromUrl(String)</code> method). <code>UrlHashStrategy</code> would be a better name. I personally do not prefer the I-prefix in interfaces as it is not something that is done in the Java standard libraries. I would probably separate the hashing completely from the fabrication of shortened URLs. That way the domain (and possible URL path prefixes) could be configured separately from the hash algorithm. The ShortenedUrl class would then contain the original URL and the hash only.</p>\n\n<pre><code>public UrlShortener(IHashStrategy instanceOfConcreteHashStrategy) {\n</code></pre>\n\n<p>The parameter name <code>instanceOfConcreteHashStrategy</code> is incredibly long considering that it provides absolutely no additional information. :) An object that is passed around is always a pointer to an instance of a concrete class and the type can already be inferred from the parameter type. A plain <code>urlHashStrategy</code> would be a big improvement in the naming.</p>\n\n<pre><code>public List&lt;Url&gt; getListOfShortenedUrlForUser(String userId) {\n</code></pre>\n\n<p>I find repeating the return type in the method name redundant. If the <code>Url</code> class had a more descriptive name this could be <code>List&lt;ShortenedUrl&gt; getShortenedUrls(String userId)</code>. The plural implies that the method returns a collection.</p>\n\n<pre><code>public void addNewEntryForUser(String url,String userId) {\n</code></pre>\n\n<p>You're not adding a generic entry. This would be more descriptive as <code>shortenUrl(String url,String userId)</code>. Unless you're planning on adding anonymous URL shortening, there is no point in repeating the ForUser part. And even if you planned, the method can be overloaded with different parameters. This is also a method that probably would benefit from returning the shortened URL as a return value.</p>\n\n<pre><code>private boolean checkExistenceForShortenedUrl(String shortenedUrl) {\n...\nwhile(checkExistenceForShortenedUrl(shortenedUrl)) {\n</code></pre>\n\n<p>The <code>checkExistenceForShortenedUrl</code> name does not imply anything about the return value. It just states that something is checked. If renamed <code>isDuplicate</code> the name would signal a boolean return value and the code would be more fluent: <code>while (isDuplicate(shortenedUrl)) {</code>. But the whole concept of duplicate hashes is pretty novel. Most URL shorteners use the same hash for a given URL.</p>\n\n<p>Calling the operation of shortening a URL \"hashing\" is misleading, as hashing is a stable operation: the same input always produces the same output. So calling a hash algorithm in a loop with same input until it produces a different output would be a never-ending loop. If you're intent on providing different shortened URLs for the same long URL for different users, you're looking for a <strong>random number generator</strong>, not a hashing strategy.</p>\n\n<pre><code>public class Url {\n</code></pre>\n\n<p>This class does not represent a URL. Since a URL is a very specific concept (and Java already has a URL class) the name is very confusing. When your method returns a <code>Url</code> the reader expects it to be a URL, not a container for two URLs and a TTL. This should be renamed to <code>ShortenedUrl</code>. I would also offload the TTL to the registry class that keeps track of the URLs that have been shortened by different users. Once you separate these two responsibilities you can also easily reuse the hashes and use the same instance for all users who want to pass the latest meme around.</p>\n\n<p>Once you have removed the TTL from the ShortenedUrl class, the responsibility of storing return values for a given time starts to sound a lot like a cache. If the personalized TTL for a shortened URL is not an important feature, you could replace the TTL management with a ready made cache that covers your URL shortener.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:02:10.063", "Id": "238246", "ParentId": "238181", "Score": "1" } }, { "body": "<h2>Thread safety</h2>\n\n<p><code>getUrls()</code> is modifying a collection (<code>urlList.remove(i)</code>), without any locking on the list. This is a potential thread safety problem. if multiple threads will attempt to access the method (and consequently modify the list), it is possible that the result will be wrong.</p>\n\n<h2>Collection iteration</h2>\n\n<p>your collection processing uses the old int index mechanism. this is both inefficient (when it comes to large collections) and too verbose. you should convert all iterations to Java 8 collection streams.</p>\n\n<p>here is an example: </p>\n\n<pre><code>private boolean checkExistenceForShortenedUrl(String shortenedUrl) {\n return userToUrl.values().stream()\n .anyMatch(urlList -&gt; urlList.stream().anyMatch(\n url -&gt; url.getShortenedUrl().equalsIgnoreCase(shortenedUrl)\n ));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T08:03:56.643", "Id": "238348", "ParentId": "238181", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T03:55:01.193", "Id": "238181", "Score": "3", "Tags": [ "java", "object-oriented", "programming-challenge" ], "Title": "An in memory Url Shortener in Java" }
238181
<blockquote> <p>Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.</p> <pre><code>Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 </code></pre> <p>For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:</p> <p>I can be placed before V (5) and X (10) to make 4 and 9.<br> X can be placed before L (50) and C (100) to make 40 and 90.<br> C can be placed before D (500) and M (1000) to make 400 and 900.</p> <p>Given a Roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.</p> <p>Example 1:<br> Input: "III"<br> Output: 3 </p> <p>Example 2:<br> Input: "IV"<br> Output: 4</p> <p>Example 3:<br> Input: "IX"<br> Output: 9</p> <p>Example 4:<br> Input: "LVIII"<br> Output: 58<br> Explanation: L = 50, V= 5, III = 3.</p> <p>Example 5:<br> Input: "MCMXCIV"<br> Output: 1994<br> Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.</p> </blockquote> <p>My function in Python to accomplish this task:</p> <pre class="lang-py prettyprint-override"><code>def romanToInt(self, s: str) -&gt; int: checks = {"IV":-2,"IX":-2, "XL":-20, "XC":-20, "CD":-200, "CM":-200} values = {"I":1, "V":5,"X":10, "L":50,"C":100, "D":500,"M":1000} sum = 0 for i in s: sum += values[i] for i in range(len(s) - 1): combine = str(s[i] + s[i + 1]) if combine in checks: sum += checks[combine] return sum </code></pre> <p>I'd love to get some feedback. I'm not sure if I should change the variable name from <code>sum</code> to something else, as I'm overwriting a python function. However, I don't use that function inside of my function, so does it matter?</p> <p>Additionally, should I be converting the string to a list? Strings are immutable and I'm pulling apart and creating a new string with the <code>combine</code> variable, so I'm not sure if that's something I should be concerned about with regards to time complexity.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T04:14:17.207", "Id": "467195", "Score": "0", "body": "I don’t know whether it’s more efficient, but my instinct was to loop right to left, subtracting the value if the previous was bigger, otherwise adding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:29:24.120", "Id": "467238", "Score": "4", "body": "\"the numeral for four is not `IIII` - this is not actually true. `IV` is the normal way to write 4, but `IIII` is also seen - for example on the entrance gates to the Colliseum." } ]
[ { "body": "<p>Don't use <code>sum</code> as a variable. Especially because you want to use it with your approach!</p>\n\n<pre><code>sum = 0\nfor i in s:\n sum += values[i]\n</code></pre>\n\n<p>could become:</p>\n\n<pre><code>number = sum(values[i] for i in s)\n</code></pre>\n\n<hr>\n\n<p><code>s[i]</code> is a string. <code>s[i] + s[i+1]</code> is a string. There is no need to use <code>str()</code> to convert what is already a string to a string. But <code>s[i:i+2]</code> is easier still.</p>\n\n<hr>\n\n<p>With 3999 as the maximum, the longest Roman numeral string would be 15 characters (<code>\"MMMDCCCLXXXVIII\"</code>). Your last loop would iterate 14 times, taking two letter substrings. </p>\n\n<p>There are only 6 two letter negative combinations. You could instead search for those 6 patterns:</p>\n\n<pre><code>number += sum(value for key, value in checks.items() if key in s)\n</code></pre>\n\n<p>This is 6 <span class=\"math-container\">\\$O(N)\\$</span> substring searches, instead of N <span class=\"math-container\">\\$O(1)\\$</span> lookups. Time complexity is unchanged, but this latter approach may be faster for many strings. (It certainly will be slower for 1 character strings!)</p>\n\n<hr>\n\n<p><code>checks</code> and <code>values</code> are constants. You should not recreate them every time you call the function. Make them global, initialized once. </p>\n\n<hr>\n\n<p>PEP-8:</p>\n\n<p>Variables and functions should be <code>snake_case</code>, not <code>camelCase</code>, so <code>romanToInt</code> should be <code>roman_to_int</code>.</p>\n\n<p><code>s</code> is too short to be descriptive. <code>roman</code> might be better. </p>\n\n<hr>\n\n<p><code>self</code>? This should be a function, not a method in a class. If it is in a class, then use <code>@staticmethod</code>, since it doesn't use <code>self</code> (or <code>cls</code>) at all. </p>\n\n<hr>\n\n<p>Result:</p>\n\n<pre><code>SUBTRACTIVE = {\"IV\": 2, \"IX\": 2, \"XL\": 20, \"XC\": 20, \"CD\": 200, \"CM\": 200}\nVALUES = {\"I\": 1, \"V\": 5, \"X\":10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n\ndef roman_to_int(roman: str) -&gt; int:\n\n number = sum(VALUES[ch] for ch in roman)\n number -= sum(val for key, val in SUBTRACTIVE.items() if key in roman)\n\n return number\n</code></pre>\n\n<p><s>Although I'm not a fan of <code>CHECKS</code>, but a better concise name is escaping me.</s> Now using <code>SUBTRACTIVE</code> as suggested by JollyJoker.</p>\n\n<hr>\n\n<h1>Speed Tests</h1>\n\n<p>Execution time for parsing all Roman numerals from <code>I</code> to <code>MMMCMXCIX</code>, repeated 100 times, in seconds:</p>\n\n<pre><code>somya_agrawal 1.288\najneufeld 0.737\njg 1.521\njg2 1.324\nmaarten_bodewes 2.186\nmaarten_bodewes 1.653 (decode only)\n</code></pre>\n\n<p>It wasn't clear whether J.G. was using local variable or global variables for <code>checks</code> and <code>values</code> in their solution, so I coded it both ways.</p>\n\n<h2>Speed Test Code</h2>\n\n<pre><code>import time\n\ndef create_roman(value):\n roman = \"\"\n for letters, val in ((\"M\", 1000),\n (\"CM\", 900), (\"D\", 500), (\"CD\", 400), (\"C\", 100),\n (\"XC\", 90), (\"L\", 50), (\"XL\", 40), (\"X\", 10),\n (\"IX\", 9), (\"V\", 5), (\"IV\", 4), (\"I\", 1)):\n while value &gt;= val:\n roman += letters\n value -= val\n return roman\n\nROMAN_NUMERALS = [create_roman(value) for value in range(1, 4000)]\n\ndef somya_agrawal(s: str) -&gt; int:\n checks = {\"IV\":-2,\"IX\":-2, \"XL\":-20, \"XC\":-20, \"CD\":-200, \"CM\":-200}\n values = {\"I\":1, \"V\":5,\"X\":10, \"L\":50,\"C\":100, \"D\":500,\"M\":1000}\n sum = 0\n\n for i in s:\n sum += values[i]\n\n for i in range(len(s) - 1):\n combine = str(s[i] + s[i + 1])\n if combine in checks:\n sum += checks[combine]\n\n return sum\n\nCHECKS = {\"IV\": 2, \"IX\": 2, \"XL\": 20, \"XC\": 20, \"CD\": 200, \"CM\": 200}\nVALUES = {\"I\": 1, \"V\": 5, \"X\":10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n\ndef ajneufeld(roman: str) -&gt; int:\n number = sum(VALUES[ch] for ch in roman)\n number -= sum(val for key, val in CHECKS.items() if key in roman)\n\n return number\n\ndef jg(s: str) -&gt; int:\n checks = {\"IV\":-2,\"IX\":-2, \"XL\":-20, \"XC\":-20, \"CD\":-200, \"CM\":-200}\n values = {\"I\":1, \"V\":5,\"X\":10, \"L\":50,\"C\":100, \"D\":500,\"M\":1000}\n\n result = sum(values[i] for i in s)\n result += sum(checks.get(s[i : i + 2], 0) for i in range(len(s) - 1))\n\n return result\n\nchecks = {\"IV\":-2,\"IX\":-2, \"XL\":-20, \"XC\":-20, \"CD\":-200, \"CM\":-200}\nvalues = {\"I\":1, \"V\":5,\"X\":10, \"L\":50,\"C\":100, \"D\":500,\"M\":1000}\n\ndef jg2(s: str) -&gt; int:\n\n result = sum(values[i] for i in s)\n result += sum(checks.get(s[i : i + 2], 0) for i in range(len(s) - 1))\n\n return result\n\ndef time_test(f):\n start = time.perf_counter()\n for _ in range(100):\n for roman in ROMAN_NUMERALS:\n f(roman)\n end = time.perf_counter()\n print(f\"{f.__name__:15} {end-start:5.3f}\")\n\nif __name__ == '__main__':\n for f in (somya_agrawal, ajneufeld, jg, jg2):\n time_test(f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T18:27:43.923", "Id": "467182", "Score": "1", "body": "A name like `SPECIAL` might be a replacement for `CHECKS`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T09:06:36.477", "Id": "467208", "Score": "2", "body": "`CHECKS` is for what [Wikipedia](https://en.wikipedia.org/wiki/Roman_numerals) calls \"subtractive notation\". I'd suggest `SUBTRACTIVE`, especially as it describes what's done with the numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:20:21.063", "Id": "467389", "Score": "0", "body": "Care to test my answer too? I'm on a rather fast machine, not comparable." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T06:59:20.017", "Id": "238187", "ParentId": "238186", "Score": "16" } }, { "body": "<p>Try to use more <a href=\"https://en.wikibooks.org/wiki/Python_Programming/Idioms\" rel=\"noreferrer\">Python idioms</a>; in particular, make your code <a href=\"https://stackoverflow.com/questions/1784664/what-is-the-difference-between-declarative-and-imperative-programming\">more declarative rather than imperative</a>. You can rewrite everything after your dictionary definitions with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return sum(values[i] for i in s)+sum(checks.get(s[i:i+2], 0) for i in range(len(s)-1))\n</code></pre>\n\n<p>or, which is more PEP-8 friendly,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>result = sum(values[i] for i in s)\nresult += sum(checks.get(s[i : i + 2], 0) for i in range(len(s) - 1))\nreturn result\n</code></pre>\n\n<p>Let me explain:</p>\n\n<ul>\n<li>For each sum, I don't need <code>[]</code> around the argument, because without them I'm summing a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\">generator</a> instead of a list;</li>\n<li>If <code>d</code> is a dictionary, <a href=\"https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html#use-dict-get-key-default-to-assign-default-values\" rel=\"noreferrer\">it's considered best practice</a> to use <code>d.get(k, v)</code> to get <code>d[k]</code> if it exists, or <code>v</code> otherwise.</li>\n</ul>\n\n<p>Your function also shouldn't have a <code>self</code> argument. If it must exist in a class, delete this argument and place an <a href=\"https://stackabuse.com/pythons-classmethod-and-staticmethod-explained/\" rel=\"noreferrer\"><code>@staticmethod</code></a> <a href=\"https://wiki.python.org/moin/PythonDecorators#What_is_a_Python_Decorator\" rel=\"noreferrer\">Python decorator</a> above it. (Please don't confuse Python decorators with the <a href=\"https://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"noreferrer\">decorator pattern</a>.)</p>\n\n<p>Having said all that, your algorithm is very clever, well done. I've coded the same problem myself before, but it never occurred to me to calculate the result assuming no subtractions were needed, then make the subtractions accordingly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T15:47:15.257", "Id": "238200", "ParentId": "238186", "Score": "10" } }, { "body": "<p>What I am entirely missing from your implementation is any correctness checks on the input of roman numerals. This makes it possible to reverse Roman literals, for instance, without any indication that they are invalid. Even if there are bad characters or lowercase characters the program will just crash. That's not any way to behave.</p>\n\n<p>One little trick I used was to simply subtract any value if it was smaller than the next one. That will also ignore invalid Roman numerals. However, I did one neat trick afterwards: I simply generated the roman numerals back again from the number and validated that it matched with the original input. That way you have encoding / decoding and a fool proof validation. There is only one canonical encoding after all (unless you include things like IIII for 4 on clocks etc.).</p>\n\n<hr>\n\n<p>For instance:</p>\n\n<pre><code>nums = \"IVXLCDM\"\n\nclass RomanNumerals:\n\n def encode(this, value):\n if (value &lt; 1 or value &gt; 3999):\n raise ValueError(\"Value should be between 1 and 3999 inclusive\")\n\n roman = \"\"\n\n x = value\n numoff = 0\n while x &gt; 0:\n d = x % 10\n if d &lt; 4:\n roman = nums[numoff] * d + roman\n elif d == 4:\n roman = nums[numoff] + nums[numoff + 1] + roman\n elif d &lt; 9:\n roman = nums[numoff] * (d - 5) + roman\n roman = nums[numoff + 1] + roman\n else:\n roman = nums[numoff] + nums[numoff + 2] + roman\n x = x // 10\n numoff += 2\n return roman\n\n def decode(this, roman):\n if len(roman) == 0:\n raise ValueError(\"Roman encoded value is empty\")\n\n res = 0\n\n tail = False\n for c in roman:\n # raises ValueError if not found\n i = nums.index(c)\n\n # power of ten for each two, but multiply with 5 if we're in between\n cv = 10**(i // 2) * (1 if i % 2 == 0 else 5)\n\n if tail:\n # decrease if the next value is larger instead of smaller (e.g. IV instead of VI)\n if cv &gt; lv:\n res -= lv\n else:\n res += lv\n else:\n tail = True\n lv = cv\n res += lv\n\n # check for correctness the way the Roman numeral is formatted doing the reverse\n if roman != this.encode(res):\n raise ValueError(\"Roman encoding is not canonical\")\n\n return res\n</code></pre>\n\n<p>Note that this is for demonstrating the idea only (and for me to practice some Python).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T05:58:37.733", "Id": "467402", "Score": "0", "body": "I'm afraid your code came in the slowest at 2.186 seconds, but that is to be expected, since you are doing twice the work (decoding, then re-encoding for validation). Without the re-encoding validation, however, it still is the slowest at 1.653" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T01:06:41.430", "Id": "238214", "ParentId": "238186", "Score": "7" } } ]
{ "AcceptedAnswerId": "238187", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T06:31:52.370", "Id": "238186", "Score": "13", "Tags": [ "python", "python-3.x", "interview-questions", "roman-numerals" ], "Title": "Converting Roman numerals to integers" }
238186
<p>Someone asked about this question on the main StackOverflow. The full question is:</p> <blockquote> <p>Given a value N, find <code>p</code> such that all of <code>[p, p + 4, p + 6, p + 10, p + 12, p + 16]</code> are prime. </p> <ul> <li>The sum of <code>[p, p + 4, p + 6, p + 10, p + 12, p + 16]</code> should be at least N.</li> </ul> </blockquote> <p>My thinking is:</p> <ul> <li>Sieve all primes under N</li> <li>Ignore primes below <code>(N-48)/6</code></li> <li>Create consecutive slices of length 6 for the remaining primes.</li> <li>Check if the slice matches the pattern.</li> </ul> <p>Here's my solution. I'd appreciate some feedback. </p> <pre><code>from itertools import dropwhile, islice def get_solutions(n): grid = [None for _ in range(n+1)] i = 2 while i &lt; n+1: if grid[i] is None: grid[i] = True for p in range(2*i, n+1, i): grid[p] = False else: i += 1 sieve = (index for index, b in enumerate(grid) if b) min_value = (n - 48) / 6 reduced_sieve = dropwhile(lambda v: v &lt; min_value, sieve) reference_slice = list(islice(reduced_sieve, 6)) while True: try: ref = reference_slice[0] differences = [v - ref for v in reference_slice[1:]] if differences == [4, 6, 10, 12, 16]: yield reference_slice reference_slice = reference_slice[1:] + [next(reduced_sieve)] except StopIteration: break n = 2000000 print(next(get_solutions(n))) # or for all solutions for solution in get_solutions(n): print(solution) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T04:43:18.903", "Id": "467197", "Score": "0", "body": "(To state the obvious:) There is an *a* such that *a ≥ N* /6 and *a*±2,4,8 is prime. Cf. http://oeis.org/A022008" } ]
[ { "body": "<p>Overall, good first question!\nThe first obvious improvement is to factor out the code that generates the primes</p>\n\n<pre><code>def prime_sieve(n):\n grid = [None for _ in range(n+1)]\n i = 2\n while i &lt; n+1:\n if grid[i] is None:\n grid[i] = True\n for p in range(i*i, n+1, i):\n grid[p] = False\n else:\n i += 1\n return (index for index, b in enumerate(grid) if b)\n</code></pre>\n\n<p>Note that <code>for p in range(i*i, n+1, i):</code> starts later than the <code>for p in range(2*i, n+1, i):</code> which you used. This is safe because anything less than the current prime squared will have already been crossed out. This difference alone makes the code about 2x faster for <code>n = 4000000</code>.</p>\n\n<p>By separating the sieve, it makes things like profiling much easier, and you can see that most of the time this method takes is still in the sieve. Using some tricks from <a href=\"https://codereview.stackexchange.com/questions/194756/find-primes-using-sieve-of-eratosthenes-with-python\">Find primes using Sieve of Eratosthenes with Python</a>, we can focus our efforts on speeding this part up.</p>\n\n<pre><code>def prime_sieve(n):\n is_prime = [False] * 2 + [True] * (n - 1) \n for i in range(int(n**0.5 + 1.5)): # stop at ``sqrt(limit)``\n if is_prime[i]:\n is_prime[i*i::i] = [False] * ((n - i*i)//i + 1)\n return (i for i, prime in enumerate(is_prime) if prime)\n</code></pre>\n\n<p>This prime sieve works pretty similarly, but is shorter, and about 4x faster. If that isn't enough, numpy and <a href=\"https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188\">https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188</a> can come to the rescue with this beauty which is another 12x faster.</p>\n\n<pre><code>import numpy\ndef prime_sieve(n):\n \"\"\" Input n&gt;=6, Returns a array of primes, 2 &lt;= p &lt; n \"\"\"\n sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)\n for i in range(1,int(n**0.5)//3+1):\n if sieve[i]:\n k=3*i+1|1\n sieve[ k*k//3 ::2*k] = False\n sieve[k*(k-2*(i&amp;1)+4)//3::2*k] = False\n return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]\n</code></pre>\n\n<p>At this point, further speedup would need to come from fancy number theory, but I'll leave that for someone else.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T00:52:36.577", "Id": "238211", "ParentId": "238192", "Score": "5" } }, { "body": "<p>I agree with the tips given in the <a href=\"https://codereview.stackexchange.com/a/238211/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/100359/oscar-smith\">@OscarSmith</a> regarding the prime sieve. In addition, here are a few more comments on how to make the rest of your code slightly better.</p>\n\n<ul>\n<li><p>You can go one step further and create a <code>primes_in_range</code> function that does the dropping for you. This might actually become a bottleneck at some point, (if a is large and a >> b - a), but at that point you only need to change the implementation of one function.</p></li>\n<li><p>Your <code>reference_slice</code> is always the same length, but if you want to add the next element you need to resort to list slicing and list addition, both of which might create a copy. Instead, you can use <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a> with the optional argument <code>maxlen</code>. If you append another element, the first one will be automatically pushed out.</p></li>\n<li><p>Similarly, you can avoid the slice in the calculation of the differences by just including the first element. You just have to add a <code>0</code> as first element in the correct differences list. Alternatively you could just define a <code>diff</code> function and adjust the correct differences to be relative to the previous elements instead of the first.</p></li>\n<li><p>You should limit your <code>try</code> block as much as possible. This increases readability on one hand, and reduces unwanted exceptions being caught on the other (not such a big risk here, but true in general).</p></li>\n<li><p>But even better is to not need it at all. A <code>for</code> loop consumes all elements of an iterable, which is exactly what we need here. This way we don't even need to special case the first five elements, because if the list is too short, the pattern cannot match. Alternatively, you could implement a <code>windowed(it, n)</code> function, which is what I have done below.</p></li>\n<li><p>You should try to avoid magical values. In your code there are two. The first is the length of the pattern and the second is the pattern itself. Fortunately, the former is already given by the latter. I would make the pattern an argument of the function, which makes it also more general. At this point a less generic name might also be needed (although the name I propose below is maybe not ideal either).</p></li>\n<li><p>You should protect the code executing your functions with a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\";</code> guard</a> to allow importing from this script without it being run.</p></li>\n</ul>\n\n\n\n<p>All of these changes make your function doing the actual work a lot shorter and IMO more readable. The functions I defined below are also nice things to have in you toolkit, since they are generally applicable and not only for this specific usecase.</p>\n\n<pre><code>from collections import deque\nfrom itertools import dropwhile, islice\n\n\ndef prime_sieve(n):\n ...\n\ndef primes_in_range(a, b):\n yield from dropwhile(lambda x: x &lt; a, prime_sieve(b))\n\ndef diff(it):\n it = iter(it)\n previous = next(it)\n for x in it:\n yield x - previous\n previous = x\n\ndef windowed(it, n):\n d = deque(islice(it, n), maxlen=n)\n assert len(d) == n\n for x in it:\n yield tuple(d)\n d.append(x)\n\ndef find_primes_matching_pattern_below(diff_pattern, n):\n min_value = (n - 48) / 6 # A comment explaining this bound\n primes = primes_in_range(min_value, n)\n for candidate in windowed(primes, len(diff_pattern) + 1):\n if tuple(diff(candidate)) == diff_pattern:\n yield candidate\n\n\nif __name__ == \"__main__\":\n n = 2000000\n # from (4, 6, 10, 12, 16) relative to the first element\n diff_pattern = (4, 2, 4, 2, 4)\n print(next(find_primes_matching_pattern_below(diff_pattern, n)))\n</code></pre>\n\n<p>For the given testcase, your code takes 741 ms ± 34.3 ms, while this code takes 146 ms ± 3.77 ms (using the <code>numpy</code> prime sieve from the <a href=\"https://codereview.stackexchange.com/a/238211/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/100359/oscar-smith\">@OscarSmith</a>) on my machine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T20:39:07.837", "Id": "467274", "Score": "0", "body": "One thing that would be easier to add to your answer than mine: `primes_in_range` could be significantly sped up via the prime number theorem. Specifically, rather than starting at the beginning, start at `n/(6ln(n/6))`, since primes at that index is guaranteed less than `n/6`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T20:49:46.607", "Id": "467381", "Score": "0", "body": "Thanks. Using deque is very clever. Also for defining `windowed`. I don't like using `try...except` but I wasn't sure how to do it without a while loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:01:56.017", "Id": "238231", "ParentId": "238192", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T12:37:31.750", "Id": "238192", "Score": "6", "Tags": [ "python", "algorithm", "python-3.x", "primes" ], "Title": "Finding consecutive primes matching p, p + 4, p + 6, p + 10, p + 12, p + 16" }
238192
<p>I wrote an OCaml program that displays a scrolling marquee in the terminal:</p> <p><a href="https://i.stack.imgur.com/LdjbU.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LdjbU.gif" alt="Ocaml scrolling marquee"></a></p> <p>Code:</p> <pre class="lang-ml prettyprint-override"><code>(* Displays moving text in the terminal. * Uses VT100 escape sequences. * Usage: * ocaml &lt;this-file&gt; * *) #load "unix.cma" let rec loop max_col curr_col = print_string "\x1B[2J"; (* Clear screen. *) print_string ("\x1B[1;" ^ (string_of_int curr_col) ^ "H"); print_string "Hello world!"; flush stdout; Unix.sleepf 0.2; if curr_col &gt;= max_col then (* Start from the beginning. *) loop max_col 0 else loop max_col (curr_col + 1) let () = (* Raise Sys.Break on Ctrl-C (SIGINT). *) Sys.catch_break true; print_string "\x1B[?25l"; (* Hide cursor. *) try loop 20 0 with Sys.Break -&gt; print_string "\x1B[?25h"; (* Show cursor. *) </code></pre> <p>The code appears to work well, as you can see in the GIF above. I need some advice:</p> <ul> <li>Did I write the program correctly? I am targeting terminal emulators that support VT100 escape sequences, and I want to make sure that this is portable across terminal emulators.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T13:22:22.893", "Id": "238196", "Score": "2", "Tags": [ "ocaml" ], "Title": "Scrolling text (marquee) in terminal" }
238196
<p>I have written this code to use <code>TcpClient</code> both from a client program and a server program.</p> <p>Can you review this source code?</p> <ul> <li>Kindly, take a close look at <strong>Disposable</strong> pattern at the bottom of the source code. </li> </ul> <p>. </p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace ClientServerLib { public class ClientClass : IDisposable { private string Host { get; set; } private int Port { get; set; } private bool IsConnected = false; public string ID { get; private set; } public TcpClient Tcp { get; private set; } private System.Net.Sockets.NetworkStream stream; public ClientClass() { Random rnd = new Random(); ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd); } //constructor for server program. public ClientClass(TcpListener listener) { Tcp = listener.AcceptTcpClient(); Host = ((IPEndPoint)Tcp.Client.RemoteEndPoint).Address.ToString(); Port = ((IPEndPoint)Tcp.Client.LocalEndPoint).Port; IsConnected = true; stream = Tcp.GetStream(); ID = Read(); Console.WriteLine("Client [{0}] is now connected.", ID); } public bool Connect() { if (IsConnected == false) { Console.WriteLine("Client [{0}] is now connected.", ID); IsConnected = true; Tcp = new TcpClient(Host, Port); stream = Tcp.GetStream(); return true; } return false; } //constructor for client. public ClientClass(string host, int port) { Random rnd = new Random(); ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd); Host = host; Port = port; } public string Read() { if (IsConnected) { byte[] buffer = new byte[Tcp.ReceiveBufferSize];//create a byte array int bytesRead = stream.Read(buffer, 0, Tcp.ReceiveBufferSize);//read count string str = Encoding.ASCII.GetString(buffer, 0, bytesRead);//convert to string return str.TrimEnd(new char[] {'\r', '\n'});//remove CR and LF } else { throw new Exception("Client " + ID + " is not connected!"); } } public void Write(string str) { if (IsConnected) { str = str + Constants.CRLF;// add CR and LF byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(str); stream.Write(bytesToSend, 0, bytesToSend.Length); } else { throw new Exception("Client " + ID + " is not connected!"); } } public void PrintID() { Console.WriteLine("Client ID = {0}", ID); } public void SendIdToServer() { this.Write(ID); } public bool Disconnect() { if (IsConnected) { if (Tcp != null) { stream.Close(); Tcp.Close(); Console.WriteLine("\nClient [{0}] is now disconnected.", ID); return true; } } return false; } #region dispose pattern // Flag: Has Dispose already been called? bool disposed = false; // Public implementation of Dispose pattern callable by consumers. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { // Free any other managed objects here if (stream != null) { stream.Close(); stream.Dispose(); stream = null; } if (Tcp != null) { if (Tcp.Connected) { Tcp.Client.Disconnect(false); Tcp.Client.Close(); Tcp.Client.Dispose(); Tcp.Client = null; Tcp.GetStream().Close(); Tcp.Close(); Tcp = null; } } } // Free any unmanaged objects here. // ... disposed = true; } ~ClientClass() { Dispose(false); } #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T14:33:17.560", "Id": "467156", "Score": "2", "body": "Down and close voter: Please explain why you down vote and/or vote for closing this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T17:07:53.773", "Id": "467173", "Score": "8", "body": "I am not the down voter or the close voter, but it would be better if the question contained a little more information about what the code does." } ]
[ { "body": "<p>Few things, </p>\n\n<p>Your properties should be all set to <code>readonly</code> as you need to enforce your class requirements. You can make them public, but with a <code>private set;</code>. or simply <code>{ get; }</code>.</p>\n\n<p><code>TcpClient</code> is a main requirement in this class, and you didn't setup the class constructor correctly for that purpose. Because of that, you were constructing inside <code>Connect()</code>. For that, you need to setup your constructors something like this :</p>\n\n<pre><code>// should be private since Host and Port are Required\nprivate ClientClass()\n{\n Random rnd = new Random();\n ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd);\n}\n\n// you can make it public or private it's optional.\nprivate ClientClass(TcpClient tcp) : this()\n{\n Tcp = tcp;\n\n Host = ((IPEndPoint)tcp.Client.RemoteEndPoint).Address.ToString();\n\n Port = ((IPEndPoint)tcp.Client.LocalEndPoint).Port;\n\n stream = tcp.GetStream();\n}\n\n//constructor for client.\npublic ClientClass(string host, int port) : this(new TcpClient(host, port)) { }\n\n//constructor for server program.\npublic ClientClass(TcpListener listener) : this(listener.AcceptTcpClient())\n{\n ID = Read();\n}\n</code></pre>\n\n<p>the <code>Connect()</code> and <code>Disconnect()</code> methods are confusing, because you're returing a boolean, and also you have already <code>IsConnected</code> which you're making it true in different places, and before even initiating the <code>TcpClient</code> how come ? </p>\n\n<p>You should do something like this : </p>\n\n<pre><code>// there is no need to return a bool\n// if you need to return a value\n// use any other return type other than boolean\npublic void Connect()\n{\n if (!IsConnected)\n {\n //no need to intilize TcpClient, it's already initilized from the constroctur\n IsConnected = true;\n\n Console.WriteLine(\"Client [{0}] is now connected.\", ID);\n }\n else\n {\n Console.WriteLine(\"Client [{0}] is already connected.\", ID);\n }\n}\n\n// there is no need to return a bool\npublic void Disconnect()\n{\n if (IsConnected &amp;&amp; Tcp != null)\n {\n stream.Close();\n Tcp.Close();\n IsConnected = false;\n }\n\n Console.WriteLine(\"\\nClient [{0}] is disconnected.\", ID);\n}\n</code></pre>\n\n<p><code>IsConnected</code> property is covering the status. avoid redundancy. </p>\n\n<pre><code>public string Read()\n{\n if (IsConnected)\n {\n byte[] buffer = new byte[Tcp.ReceiveBufferSize];//create a byte array\n int bytesRead = stream.Read(buffer, 0, Tcp.ReceiveBufferSize);//read count\n string str = Encoding.ASCII.GetString(buffer, 0, bytesRead);//convert to string\n return str.TrimEnd(new char[] {'\\r', '\\n'});//remove CR and LF\n }\n else\n {\n throw new Exception(\"Client \" + ID + \" is not connected!\");\n }\n}\n</code></pre>\n\n<p>Validations and Exceptions always comes first, to make it readable, and clear to human eye, and also would give you a good understanding on what's coming next. So, Don't move them at the bottom of your code neither inside <code>else</code> clause. \nInstead do this : </p>\n\n<pre><code>public string Read()\n{\n if (!IsConnected)\n {\n throw new Exception(\"Client \" + ID + \" is not connected!\");\n }\n\n byte[] buffer = new byte[Tcp.ReceiveBufferSize];//create a byte array\n int bytesRead = stream.Read(buffer, 0, Tcp.ReceiveBufferSize);//read count\n string str = Encoding.ASCII.GetString(buffer, 0, bytesRead);//convert to string\n return str.TrimEnd(new char[] { '\\r', '\\n' });//remove CR and LF\n}\n</code></pre>\n\n<p>Lastly, disposable parts. You need to know when you call <code>Dispose()</code> or using <code>using</code> clause, the instance would be disposed, if there is a connection, it would be closed automatically, along with any inner disposable objects. At least, this would be mostly applied on .NET disposable objects. </p>\n\n<p>also, if you want a better code readability, try to minimize the use of <code>return;</code> like on this line : </p>\n\n<pre><code>if (disposed)\nreturn;\n</code></pre>\n\n<p>check this out :</p>\n\n<pre><code>#region dispose pattern\n\nprivate bool disposed = false;\n\npublic void Dispose()\n{\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n\nprotected virtual void Dispose(bool disposing)\n{\n if (!disposed)\n {\n if (disposing)\n {\n // Free any other managed objects here\n if (stream != null)\n {\n stream.Dispose();\n stream = null;\n }\n\n if (Tcp != null &amp;&amp; Tcp.Connected)\n {\n Tcp.Dispose();\n Tcp = null;\n }\n }\n\n disposed = true;\n }\n}\n\n~ClientClass()\n{\n Dispose(false);\n}\n\n#endregion\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:19:51.443", "Id": "467231", "Score": "0", "body": "Is it safe to use `NetworkStream` as a property? Or, should I rather keep it local?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:56:39.700", "Id": "467247", "Score": "0", "body": "@user366312 if you use `private readonly NetworkStream stream` this means, you only initialize it once by a constructor or inline assignment and it would be immutable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T04:32:15.877", "Id": "238217", "ParentId": "238197", "Score": "2" } } ]
{ "AcceptedAnswerId": "238217", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T13:46:22.240", "Id": "238197", "Score": "0", "Tags": [ "c#", "networking", "socket", "tcp" ], "Title": "A common class for Client and Server" }
238197
<p>The code below does not deal with any numerical-integration or anything related to it — just the basic rule in evaluating a definite integral of the form Ax^2 + Bx + C. I would love to hear from you guys since I'm relatively new and still learning. </p> <p>This coding exercise is meant to test what we learned for the past few weeks, so anything more sophisticated than the keywords below is probably discouraged, as well as other standard library functions. </p> <p>Also, under under <code>evaluateIntegral()</code> function, does the initialization value of <code>lower</code> and <code>upper</code> matter? I mean they do matter, but is it better to initialize it to 0 in this situation instead of 1? They give same result. Which is better?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; void inputDegree(int *deg) { printf("Enter the degree of the polynomial: "); scanf("%d", deg); } void inputCoeffs(int deg, double *coeffs) { printf("\nEnter the coefficients of the polynomial: \n\n"); for(int i = 0; i &lt;= deg; i++) { printf("Coefficient of degree %d: ", deg - i); scanf("%lf", &amp;coeffs[i]); } } void inputLimits(double *lowerL, double *upperL) { printf("\nEnter the lower limit of integration: "); scanf("%lf", lowerL); printf("\nEnter the upper limit of integration: "); scanf("%lf", upperL); } void computeIntegralCoeffs(int deg, double *coeffs, double *integCoeffs) { for(int i = 0; i &lt;= deg; i++) { integCoeffs[i] = coeffs[i] / (deg + 1 - i); } } double evaluateIntegral(int degree, double *integCoeffs, double lowerLimit, double upperLimit) { double lower = 0, upper = 0; for(int i = 0; i &lt;= degree; i++) { lower += integCoeffs[i] * pow(lowerLimit, (degree + 1 - i)); } for(int i = 0; i &lt;= degree; i++) { upper += integCoeffs[i] * pow(upperLimit, (degree + 1 - i)); } return upper - lower; } int main() { int degree; double lowerLimit; double upperLimit; double integral; double *coefficients = NULL; double *integralCoefficients = NULL; inputDegree(&amp;degree); coefficients = (double *)malloc((degree + 1) * sizeof(double)); integralCoefficients = (double *)malloc((degree + 1) * sizeof(double)); inputCoeffs(degree, coefficients); inputLimits(&amp;lowerLimit, &amp;upperLimit); computeIntegralCoeffs(degree, coefficients, integralCoefficients); integral = evaluateIntegral(degree, integralCoefficients, lowerLimit, upperLimit); printf("\n\nEvaluating the definite integral gives us the following area: \t%lf\n", integral); free(coefficients); free(integralCoefficients); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T14:31:42.150", "Id": "467155", "Score": "0", "body": "Someone told me to repost this post in this forum from stackoverflow, which I did but I don't know why I'm getting downvoted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T16:49:37.687", "Id": "467168", "Score": "0", "body": "Someone also voted to close, the close reason is that the question needs more details or clarity. I'm not sure why they did. This code is working correctly? What do you want specifically from this code review (performance as an example)? Perhaps this part of the question is what the down voter didn't like `Also, under under evaluateIntegral() function, does the initialization value of lower and upper matter? I mean they do matter, but is it better to initialize it to 0 in this situation instead of 1? They give same result. Which is better?`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T14:22:03.267", "Id": "238199", "Score": "0", "Tags": [ "c", "array", "pointers" ], "Title": "Evaluating a Definite Integral, kindly check" }
238199
<p>I'm struggling with some code that should be a very simple computation of a duration. The purpose of the code is to generate a random delay, constrained by an upper and lower limit. The reason I'm looking for advise here is that what should be a simple task, has turned into a behemoth of type conversions:</p> <pre><code>package main import ( "math/rand" "time" ) func main() { // parameters, hardcoded for illustration purposes only tMin := float32(1.2) tMax := float32(2.7) // intention is approximately this: // delay := tMin + rand.Float32() * (tMax - tMin) delay := time.Duration((tMin + rand.Float32() * (tMax - tMin)) * float32(time.Second)) time.Sleep(delay) } </code></pre> <p>Questions:</p> <ul> <li>Apart from rounding errors (which I'm happy to ignore here), does this code have any actual bugs that I missed?</li> <li>I know that elegance is in the eye of the beholder, but is there any way to write this more elegantly? In particular, I'd like to reduce the number of required casts, preferably down to zero.</li> </ul>
[]
[ { "body": "<p>Encapsulate implementation details and any ugliness in a function. Readability is paramount.</p>\n\n<p>For example, a more elegant solution,</p>\n\n<pre><code>package main\n\nimport (\n \"math/rand\"\n \"time\"\n)\n\n// delay returns a random delay, in nanoseconds,\n// between min and max seconds.\nfunc delay(min, max float64) time.Duration {\n // time doesn't go backwards\n if min &lt; 0 || min &gt; max {\n return 0\n }\n // delay in seconds\n d := min + rand.Float64()*(max-min)\n // delay in nanoseconds\n return time.Duration(d * float64(time.Second))\n}\n\nfunc main() {\n dMin, dMax := 1.2, 2.7\n\n time.Sleep(delay(dMin, dMax))\n}\n</code></pre>\n\n<p>By design, Go is type safe. Conversions between diffent types must be explicit.</p>\n\n<p>Unless you have a very large number of occurrences of a floating-point variable and you can tolerate the loss of precision, use type <code>float64</code>, not <code>float32</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>behemoth : something of monstrous size. Merriam-Webster</p>\n \n <p>a behemoth of type conversions. uli</p>\n</blockquote>\n\n<p>I only found a few type conversions in the code you posted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:44:14.887", "Id": "467371", "Score": "0", "body": "Thank you for the review. I agree that putting things into functions can be used to hide some ugliness from obscuring the view on the relevant code. Concerning my choice to name this a behemoth, it's the perceived relation between code that does something and code that's only necessary due to the circumstances. The latter includes two conversions and the `time.Second` constant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T21:40:30.480", "Id": "238205", "ParentId": "238202", "Score": "3" } }, { "body": "<p>Toying with this, I stumbled across another alternative. According to my own initial thought, it would have been cheating, but I'd present it here because I think that it's a compromise that should at least be considered. The idea is to simply use a different base duration, in this case milliseconds instead of seconds:</p>\n\n<pre><code>tMinMS := 1200\ntMaxMS := 2700\n\ndelayMS := tMin + rand.Intn(1 + tMax - tMin)\n\ntime.Sleep(time.Duration(delay) * time.Millisecond)\n</code></pre>\n\n<p>Notes here:</p>\n\n<ul>\n<li>This works with just one conversion and the <code>time.Milliseconds</code> constant, which is better. The trick is that the conversion, even though it discards fractions, only causes a rounding error of less than 1ms. Doing the same to the original code would impose rounding errors of 1000 times as much.</li>\n<li>Everyone used to calculating with units will notice and cringe from the fact that this multiplies a <code>time.Duration</code> with a <code>time.Duration</code>. Which is why I still don't like this solution.</li>\n<li>I've been looking at replicating the <code>time</code> module using <code>float64</code> representing seconds as alternative. I should check if anyone did that already before reinventing the wheel...</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T18:10:50.240", "Id": "238327", "ParentId": "238202", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T16:24:48.243", "Id": "238202", "Score": "3", "Tags": [ "go" ], "Title": "A not-so-simple time calculation" }
238202
<p>I have written a vimscript for learning purposes. The script displays the content of registers in a side bar by polling all registers periodically and redrawing the side bar when any changes happens. I want to get a review. </p> <p>My <strong>Vim</strong> version is <strong>8.0</strong>. </p> <p>I know about the latest version and some features, which can be useful in this script, like <a href="https://vi.stackexchange.com/a/22997/14024">deletebufline()</a>, but I decided to stick to a more common version.</p> <p>At this moment I use this script by such way:</p> <ol> <li>Open source file <code>show_regs.vim</code>.</li> <li>Do a <code>:so % | Showreg</code> command.</li> </ol> <p>Also, it can be converted to a plugin and placed into an autoload directory I think.</p> <p>The script is capable to execute three commands:</p> <ol> <li><code>Showreg</code> - creates the side bar</li> <li><code>Unshowreg</code> - removes the side bar</li> <li><code>Cleanregs</code> - cleans all numbered and lettered registers.</li> </ol> <hr> <pre><code>function! s:Update_reg_dict(timer) " If the register's bar was deleted manually, " stop update function's timer and remove all script's variables if !buflisted(s:buf_name) call s:Unshow_reg_bar() return endif let l:flag = 0 " The previous highlight dictionary should be discarded every time let s:highlght = {} " Comparison of current register values with stored in the dictionary for [l:key, l:val] in items(s:reg_dict) let l:new_val = strtrans(getreg(l:key)) if l:val !=# l:new_val let s:reg_dict[l:key] = l:new_val " Adds a changed register to the highlight dictionary let s:highlght[l:key] = '*' let l:flag = 1 endif endfor " if any register was changed, rewrite a bar if l:flag call s:Write_reg_dict_to_bar() endif endfunction function! s:Create_reg_bar() " if the register's bar doesn't exist if buflisted(s:buf_name) return endif execute 'rightbelow ' s:reg_bar_size.'vnew' s:buf_name set winfixwidth set nonu set nowrap " A changed registers highlight color highlight MyGroup ctermbg=green " Special characters colorizing highlight Escaped_chars ctermfg=blue call matchadd('MyGroup', '^\*".') call matchadd('Escaped_chars', '\^[\[ICWLPMV@H]') execute 'wincmd p' endfunction function! s:Write_reg_dict_to_bar() let l:num = 1 for l:key in split(s:reg_names, '\zs') let l:val = s:reg_dict[l:key] if l:val != '' " If a register was changed, then put a mark '*' to the beginning of line let l:mark = get(s:highlght, l:key, ' ') call setbufline(s:buf_name, l:num, printf('%s"%s| %s', l:mark, l:key, l:val)) let l:num += 1 endif endfor " Clean up all unneeded lines, which are left from the previous update " vim 8.1 has a special delete function 'deletebufline()', but I use vim 8.0 while l:num &lt; len(s:reg_dict) call setbufline(s:buf_name, l:num, '') let l:num += 1 endwhile endfunction function! s:Create_reg_dict() if exists('s:reg_dict') return endif let s:reg_dict = {} for l:char in split(s:reg_names[1:], '\zs') " 'strtrans' is used to make register content printable let s:reg_dict[l:char] = strtrans(getreg(l:char)) endfor " Unnamed register should be treated separately let s:reg_dict['"'] = strtrans(getreg('')) endfunction function! s:Unshow_reg_bar() if !exists('s:reg_dict') return endif if buflisted(s:buf_name) execute 'bdelete!' s:buf_name endif call s:Timer_stop() " Cleaning up of script's variables scope for l:variable in keys(s:) execute 'unlet s:'.l:variable endfor " Other way to clean " unlet s:buf_name " unlet s:reg_names " unlet s:reg_dict " unlet s:highlght " unlet s:timer " unlet s:reg_bar_size " unlet s:update_time endfunction function! s:Timer_start() let s:timer = timer_start(s:update_time, function('s:Update_reg_dict'), {'repeat': -1}) endfunction function! s:Timer_stop() call timer_stop(s:timer) endfunction function! s:Clean_regs() if !exists('s:reg_dict') return endif " Only numbered and lettered registers are cleaned for l:char in split(s:reg_names[1:-7], '\zs') call setreg(l:char, '') endfor endfunction " Main function function! s:Show_reg_bar(...) if exists('s:reg_dict') return endif let s:reg_bar_size = a:0 &gt;= 1 ? a:1 : 30 let s:update_time = 100 let s:buf_name = 'reg_bar' let s:reg_names = '"0123456789abcdefghijklmnopqrstuvwxyz-.:%#/=' let s:highlght = {} let s:timer = '' call s:Create_reg_bar() call s:Create_reg_dict() call s:Write_reg_dict_to_bar() call s:Timer_start() endfunction command! -nargs=* Showreg call s:Show_reg_bar(&lt;f-args&gt;) command! Unshowreg call s:Unshow_reg_bar() command! Cleanregs call s:Clean_regs() </code></pre> <p><strong>Demonstration</strong></p> <p><a href="https://i.stack.imgur.com/KfSWP.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KfSWP.gif" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T18:56:27.377", "Id": "238204", "Score": "2", "Tags": [ "vimscript" ], "Title": "Vim. Displaying register's content in a side bar" }
238204
<p>I am pretty new to competitive programming. It took me almost 3 hours to make this, initially I started with 4 for loops and then to make it scalable for sizes bigger than 4, I decided to turn this into a recursion which is when it took most of my time, even though I am proud of it, I am still worried that it took me an hour to actually come up with the solution and I have a feeling that it is neither efficient nor good, <em>(you could say I am basically doing combination rather than permutation)</em>, <strong>I would like a code review please</strong> and <strong>how would you make this more efficient</strong>?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; int counter = 0; int factorial(int n){ if(n==1) return 1; else return n*factorial(n-1); } int index_present_check(int* n_arr, int n, int depth){ for(int i = 0 ; i &lt; depth ; i++) if(n_arr[i]==n) return 1; return 0; } int present_in_array_check(char** store_arr,char* arr_to_print,int counter){ for(int i = 0; i &lt; counter; i++) if(strcmp(store_arr[i],arr_to_print)==0) return 1; return 0; } void permutation(int depth,int length,char* src_arr, char* arr_to_print,int* n_arr,char** store_arr){ for(int i = 0 ; i &lt; length ; i ++){ if(depth ==1){ arr_to_print[0] = src_arr[i]; n_arr[0] = i; permutation(depth+1,length,src_arr,arr_to_print,n_arr,store_arr); } else{ if(!index_present_check(n_arr,i,depth)){ arr_to_print[depth-1] = src_arr[i]; n_arr[depth-1] = i; permutation(depth+1,length,src_arr,arr_to_print,n_arr,store_arr); n_arr[depth-1] = -1; } } } if(depth==length){ if(!present_in_array_check(store_arr,arr_to_print,counter)){ printf("%s ",arr_to_print); strcpy(store_arr[counter],arr_to_print); counter++; if(counter%factorial(length-1)==0){ printf("\n"); } } } } int main() { char* src_arr = "ABCDE"; int length = 4; int depth = 1; int iteration_length = factorial(length); char* arr_to_print = malloc(length*sizeof(char)); int* n_arr = malloc(length*sizeof(int)); char** store_arr = (char**)malloc(sizeof(char*)*iteration_length); for(int i = 0 ; i&lt;iteration_length;i++) store_arr[i] = malloc(sizeof(char)*length); permutation(depth,length,src_arr,arr_to_print,n_arr,store_arr); return 0; } </code></pre> <p>I posted this in reddit too, but it was a bit off timing and didn't get much code review, however it was helpful nonetheless. </p>
[]
[ { "body": "<ol>\n<li><p>There are only two versions of the <code>main</code> function:</p>\n\n<pre><code>/* 1 */\nint main(int argc, char *argv[]) { ... }\n\n/* 2 */\nint main(void) { ... }\n</code></pre>\n\n<p>Note the <code>void</code> keyword in the second version. In C, if the function has no parameters it should be declared as</p>\n\n<pre><code> &lt;type&gt; f(void)\n</code></pre>\n\n<p>Please, take a look at <a href=\"https://stackoverflow.com/a/29326312/8086115\">this</a> SO answer for details.</p></li>\n<li><p>Do not write one-line code:</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i &lt; counter; i++) if(strcmp(store_arr[i],arr_to_print)==0) return 1;\n</code></pre>\n</blockquote>\n\n<p>I'd rewrite it this way:</p>\n\n<pre><code>for (int i = 0; i &lt; count; i++)\n if (strcmp(store_arr[i], arr_to_print) == 0)\n return 1;\n</code></pre></li>\n<li><p>Do not use <code>int</code> as type for array indexing. It is not guaranteed that <code>int</code> can hold any possible index value of an array object. The only type that can hold any index of an array object is <code>size_t</code>. See <a href=\"https://stackoverflow.com/a/2550799/8086115\">this</a> SO answer for details.</p></li>\n<li><p>I'd replace</p>\n\n<pre><code>printf(\"\\n\");\n</code></pre>\n\n<p>with</p>\n\n<pre><code>putchar('\\n');\n</code></pre></li>\n<li><p>Do not cast the result of <code>malloc</code> call. Really, you have to do it in C++, but not in C. See <a href=\"https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">this</a> SO question for details.</p></li>\n<li><p>Do not repeat yourself. Consider this line:</p>\n\n<blockquote>\n<pre><code>int* n_arr = malloc(length * sizeof(int));\n</code></pre>\n</blockquote>\n\n<p>You declare <code>n_arr</code> as a pointer to <code>int</code>. It would be better to rewrite this line in this way:</p>\n\n<pre><code>int *n_arr = malloc(length * sizeof *n_arr);\n</code></pre>\n\n<p>In this case you don't have to change the expression of the <code>sizeof</code> operator if you change <code>n_arr</code> type. It is very common C idiom.</p></li>\n<li><p>Do not computer factorial using recursion. It is <em>really slow</em>. Usually, you can just create the factorial table and hardcode it:</p>\n\n<pre><code>static const unsigned long long factorial_table[] = {\n 1,\n 2,\n 6,\n 24,\n 120,\n 720,\n ...\n};\n</code></pre></li>\n<li><p>In this line:</p>\n\n<blockquote>\n<pre><code>char* src_arr = \"ABCDE\";\n</code></pre>\n</blockquote>\n\n<p>you create a pointer to a string literal. It would be better to create just a <em>static array</em>:</p>\n\n<pre><code>static src_arr[] = \"ABCDE\";\n</code></pre></li>\n<li><p>And you can make it <code>const</code> since it never changes:</p>\n\n<pre><code>static const src_arr[] = \"ABCDE\";\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T00:36:59.620", "Id": "467284", "Score": "0", "body": "Amazing, the details of such feedback kind of makes me sad about whether my self learning practices are any good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T00:38:01.237", "Id": "467285", "Score": "0", "body": "The fact I did not hardcode the factorial was for the fact that I wanted it to be scalable for any length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T00:41:03.273", "Id": "467286", "Score": "0", "body": "BTW I ran this on hackerrank and out of 48 test cases, 29 of them passed, for the other ones it basically says timed out, so I was wondering is it possible to make this more time and memory efficient ( given that I hardcode the factorial) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:54:18.190", "Id": "467306", "Score": "1", "body": "@SonGohan, 1) well, you actually can not make factorial computing to be scalable for any length (as long as you are not using bignum arithmetic). 2) permutation is a quite hard topic and I am not very good at it :), so I'd recommend you read [the Wikipedia article](https://en.wikipedia.org/wiki/Permutation#Permutations_in_computing) about this topic and take a look at [StackOverflow Questions](https://stackoverflow.com/questions/tagged/permutation)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T07:25:12.080", "Id": "238222", "ParentId": "238206", "Score": "3" } } ]
{ "AcceptedAnswerId": "238222", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T22:03:51.260", "Id": "238206", "Score": "2", "Tags": [ "performance", "c", "programming-challenge", "memory-optimization" ], "Title": "Permutation code in C" }
238206
<p>This is the draft contents of a function intended to be run after a system crash in order to quickly review all of the recent vim swap files. They will be loaded up into and displayed in a vim instance, and then presumably if desired they will be saved using vim commands into actual files. Following this, rm will be run to offer user to delete the swap files. In theory, unless user gets distracted by something in between quitting the vim instance and responding to the rm -i prompt, there shouldn't be cases in which the swap file gets preserved, but better to be safe with these things I guess, and add additional 2 keystrokes to the workflow per file.</p> <pre><code>vim=gvim n=5 d=. days_back=3 echo Searching find "$1" -type f \( -name '.*.s??' -o -name '.s??' \) -exec ls -lta {} + | head -n "$2" find "$d" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -printf "%AY%Am%Ad%AH%AM%AS %p\0\n" | sort -n | head "$n" | sed -e 's/\d+ //' | sed -e 's/\n//g' | while read -r -d '' f; do $vim -r "$f" &amp;&amp; rm -iv "$f" || echo ERROR: vim recovery command returned failure status. done </code></pre> <p>2nd iteration:</p> <pre class="lang-bsh prettyprint-override"><code>function swap_sweep () { # Usage: swap_sweep [ DAYS_BACK ] # Sweeps the current working directory for swap files, sorted by the most recent order, # going DAYS_BACK days back if it is provided, or 3 days back if it is not. # [[ -d $1 ]] &amp;&amp; ( d="$1" &amp;&amp; n="$2" ) || n="$1" # [[ -z $d ]] &amp;&amp; d=. vim=gvim wd=. [[ -n $1 ]] &amp;&amp; days_back=$1 || days_back=3 # I wonder if these awk commands will accomodate filenames that contain whitespace... # I'm guessing not, and wonder how that could be done? find "$wd" -type f \ -mtime "$days_back" \ \( -name '.*.s??' -o -name '.s??' \) \ -exec ls -ltago {} + \ | awk '{ print $4, $5, $6, $7, }' \ \ | tee | awk '{ print $4 }' \ | while read -r f; do $vim -r "$f" &amp;&amp; rm -iv "$f" || echo ERROR: vim recovery command returned failure status. done } alias sws=swap_sweep </code></pre> <p>3rd iteration:</p> <pre class="lang-bsh prettyprint-override"><code> function swap_sweep () { days_back=3 vim=gvim n=5 wd=. echo Searching find "$wd" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -exec ls -ltago {} + | awk '{ print $4, $5, $6, $7 }' find "$wd" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -print0 | while read -r -d '' f; do $vim -r "$f" &amp;&amp; rm -iv "$f" || echo ERROR: vim recovery command returned failure status. done ## # Usage: swap_sweep [ DAYS_BACK ] ## # Sweeps the current working directory for swap files, sorted by the most recent order, ## # going DAYS_BACK days back if it is provided, or 3 days back if it is not. ## ## # [[ -d $1 ]] &amp;&amp; ( d="$1" &amp;&amp; n="$2" ) || n="$1" ## # [[ -z $d ]] &amp;&amp; d=. ## ## vim=gvim ## wd=. ## [[ -n $1 ]] &amp;&amp; days_back=$1 || days_back=3 ## # I wonder if these awk commands will accomodate filenames that contain whitespace... ## # I'm guessing not, and wonder how that could be done? ## find "$wd" -type f \ ## -mtime "$days_back" \ ## \( -name '.*.s??' -o -name '.s??' \) \ ## -exec ls -ltago {} + \ ## | awk '{ print $4, $5, $6, $7 }' \ ## \ ## | tee | awk '{ print $4 }' \ ## | while read -r f; do ## $vim -r "$f" &amp;&amp; ## echo -n "$(ls -lhgo "$f" | awk '{ print $7, "\t", $4, $5, $6 }') ==&gt; " &amp;&amp; ## rm -iv "$f" || ## echo ERROR: vim recovery command returned failure status. ## done } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T23:37:57.640", "Id": "238208", "Score": "2", "Tags": [ "bash" ], "Title": "Vim swap file sweep and recovery" }
238208
<p>if I have a string <code>AYUKB17053UI903TBC</code>. I want a function to return <code>ABKUY01357IU039BCT</code>. So every alphabetical part of the string is sorted, as well as the numerical part. But they retain their original orders in the string...</p> <p>We can assume that the input only contains number and English letters </p> <p>I came up with a solution but I don't think it is elegant.</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> const string1 = 'AYUKB17053UI903TBC' const string2 = `ABKUY01357IU039BCT` function fn1(string1) { let tempArray = [[]] for (const char of string1) { let lastCharIsNumber let currentCharIsNumber const lastArray = tempArray[tempArray.length - 1] if(!lastArray.length){ lastArray.push(char) continue } currentCharIsNumber = !Number.isNaN(Number(char)) lastCharIsNumber = !Number.isNaN(Number(lastArray[lastArray.length - 1])) if (currentCharIsNumber &amp;&amp; lastCharIsNumber) lastArray.push(char) else if (!currentCharIsNumber &amp;&amp; !lastCharIsNumber) lastArray.push(char) else tempArray.push([char]) } tempArray.forEach(item =&gt; item.sort()) return tempArray.map(array =&gt; array.join('')).join('') } console.log(fn1(string1) === string2); // true</code></pre> </div> </div> </p> <p>Can anyone help to improve my solution?</p>
[]
[ { "body": "<p>I'm not sure exactly what your metric is for being \"elegant\", but here's a bit of a different approach that I think is fairly \"clean\" and \"simple\" to follow:</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 string1 = 'AYUKB17053UI903TBC';\nconst string2 = 'ABKUY01357IU039BCT';\n\nfunction sortPieces(str) {\n const piecesArray = [];\n let lastPiece = [];\n let lastType;\n for (const char of str) {\n const nextType = (char &gt;= \"0\" &amp;&amp; char &lt;= \"9\") ? \"number\" : \"letter\";\n if (nextType === lastType || !lastType) {\n // either same type as previous char or first char in string\n lastPiece.push(char);\n } else {\n // different type of char than previous char, start a new piece\n piecesArray.push(lastPiece.sort());\n lastPiece = [char];\n }\n lastType = nextType;\n }\n piecesArray.push(lastPiece.sort());\n return piecesArray.flat().join(\"\"); \n}\n\nlet result = sortPieces(string1) \nconsole.log(result === string2, result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>This could also be done by just adding each sorted piece directly to a results array which then removes the need to use <code>.flat()</code> at the end. One could also use:</p>\n\n<pre><code>result = result.concat(lastPiece.sort())\n</code></pre>\n\n<p>too, but I don't generally like the fact that <code>.concat()</code> makes a whole new result array every time you call it (which seems less efficient to me if doing it a bunch of times) so that's why I used this:</p>\n\n<pre><code>result.push(...lastPiece.sort())\n</code></pre>\n\n<p>instead since you can add one array onto the other this way without making a whole new copy of the accumulated array every time (though it may be making a copy of <code>lastPiece</code> each time). Since <code>.flat()</code> could be implemented in native code, it may be plenty efficient (as used in the first implementation).</p>\n\n<p>Anyway, here's an implementation that uses <code>result.push(...lastPiece.sort());</code> to accumulate results as you go:</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 string1 = 'AYUKB17053UI903TBC';\nconst string2 = 'ABKUY01357IU039BCT';\n\nfunction sortPieces(str) {\n const result = [];\n let lastPiece = [];\n let lastType;\n for (const char of str) {\n const nextType = (char &gt;= \"0\" &amp;&amp; char &lt;= \"9\") ? \"number\" : \"letter\";\n if (nextType === lastType || !lastType) {\n // either same type as previous char or first char in string\n lastPiece.push(char);\n } else {\n // different type of char than previous char, start a new piece\n result.push(...lastPiece.sort());\n lastPiece = [char];\n }\n lastType = nextType;\n }\n result.push(...lastPiece.sort());\n return result.join(\"\"); \n}\n\nlet result = sortPieces(string1) \nconsole.log(result === string2, result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>FYI, in a <a href=\"https://jsperf.com/sort-pieces/1\" rel=\"nofollow noreferrer\">little performance benchmarking</a>, the first option here is faster in Firefox and the second option here is faster in Chrome. Apparently Chrome is more efficient with <code>result.push(...lastPiece.sort());</code> or worse with <code>.flat()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T01:01:00.433", "Id": "238213", "ParentId": "238209", "Score": "3" } }, { "body": "<p>You can use RegEx to extract the sequence of alphabets or numbers.\nTo match alphabets/number, use character class in Regular expression as below</p>\n\n<pre><code>/[A-Z]+|[0-9]+/\n</code></pre>\n\n<p>to match all occurrences, use <code>g</code>(global) flag.</p>\n\n<p>After extracting sequences, use <code>Array#reduce</code> with <code>Array#sort</code> &amp; <code>Array#join</code> to get the sorted string.</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 str1 = 'AYUKB17053UI903TBC';\nconst str2 = 'ABKUY01357IU039BCT';\n\nconsole.log(str1\n .match(/[A-Z]+|[0-9]+/g)\n .reduce((a, c) =&gt; a + [...c].sort().join(''), '')\n === str2\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:12:25.343", "Id": "238233", "ParentId": "238209", "Score": "4" } } ]
{ "AcceptedAnswerId": "238213", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T00:42:40.273", "Id": "238209", "Score": "4", "Tags": [ "javascript", "ecmascript-6" ], "Title": "A function to split an string of alphabets and numbers into arrays and sort them respectively" }
238209
<p>I've came up with the following implementation of a very simple cache:</p> <pre class="lang-rust prettyprint-override"><code>use std::cmp::Eq; use std::collections::HashMap; use std::hash::Hash; pub struct Cache&lt;I, R, F&gt; where I: Copy + Eq + Hash, F: Fn(I) -&gt; R { calculation: F, values: HashMap&lt;I, R&gt;, } impl&lt;I, R, F&gt; Cache&lt;I, R, F&gt; where I: Copy + Eq + Hash, F: Fn(I) -&gt; R { pub fn new(calculation: F) -&gt; Cache&lt;I, R, F&gt; { Cache { calculation, values: HashMap::new() } } pub fn value(&amp;mut self, arg: I) -&gt; &amp;R { // Pop or calculate new value let result = match self.values.remove(&amp;arg) { Some(v) =&gt; v, None =&gt; (self.calculation)(arg) }; // Store value self.values.insert(arg, result); // Return a reference to it self.values.get(&amp;arg).unwrap() } } </code></pre> <p>A simple usage example would be:</p> <pre class="lang-rust prettyprint-override"><code>fn to_lowercase(value: &amp;str) -&gt; String { println!("Calculating \"{}\".to_lowercase()", value); value.to_lowercase() } fn main() { let mut cache = Cache::new(to_lowercase); println!("Calculated: {}", cache.value("ABC")); println!("Calculated: {}", cache.value("ABC")); } </code></pre> <p>Which prints:</p> <pre><code>Calculating "ABC".to_lowercase() Calculated: abc Calculated: abc </code></pre> <p>However, I feel like my code is much more complicated than it needs to be (specially around the <code>Cache.value</code> implementation), what can be improved here?</p>
[]
[ { "body": "<p>The biggest change you can do is to the value function. Because most of what you are building is actually provided via <code>HashMap</code>'s<a href=\"https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry\" rel=\"nofollow noreferrer\"><code>entry</code></a> API. This could reduce the body of your value function to simply this:</p>\n\n<pre><code>match self.values.entry(arg) {\n Entry::Occupied(val) =&gt; val.into_mut(),\n Entry::Vacant(slot) =&gt; slot.insert((self.calculation)(arg)),\n}\n</code></pre>\n\n<p>You could also mess with <code>Entry</code>'s <a href=\"https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.or_insert_with\" rel=\"nofollow noreferrer\"><code>or_insert_with</code></a> function, but I personally prefer the approach above.</p>\n\n<p>You may also consider using <a href=\"https://doc.rust-lang.org/std/clone/trait.Clone.html\" rel=\"nofollow noreferrer\"><code>Clone</code></a> instead of <a href=\"https://doc.rust-lang.org/std/marker/trait.Copy.html\" rel=\"nofollow noreferrer\"><code>Copy</code></a>. The advantage of <code>Clone</code> are that it is more explicit and that it should support more types. The disadvantage obviously is that <code>clone</code> can be arbitrarily expensive. In general I'd say you want <code>Clone</code> for a generic interface such as this.</p>\n\n<p>Finally, I understand it's an exercise, but the names are a bit plain:</p>\n\n<ul>\n<li><code>Cache</code> is very generic: what do you actually cache? Call it something like <code>FunctionResultCache</code> or <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\"><code>Memoizer</code></a></li>\n<li><code>value</code> is also a bit weird. What you're doing in essence is wrapping a function, so I'd name this <code>call</code> or <code>invoke</code> or something similar. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:34:16.250", "Id": "238311", "ParentId": "238210", "Score": "2" } } ]
{ "AcceptedAnswerId": "238311", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T00:44:44.643", "Id": "238210", "Score": "3", "Tags": [ "rust" ], "Title": "Generic Cache struct" }
238210
<p>So I am new to Databases.Recently I was asked this question in an interview where they expected me to come with a schema for storing and retrieving categories for an E-commerce website in an RDBMS. Each category could have many sub-categories. But each sub-category could have just one parent category. So this is the idea that I gave them: First I created the table like so:</p> <pre><code>create table category(category_id TEXT PRIMARY KEY, category_name TEXT,parent_id TEXT); </code></pre> <p>Then I created an index on the parent_id, like so:</p> <pre><code> Create index idx_category_table on category(parent_id); </code></pre> <p>Then I used the following queries to get the parent and child queries:</p> <pre><code>Select B.category_name as CategoryName from category A, category B where A.category_id='3' and A.parent_id = B.category_id; Select B.category_name as CategoryName from category A, category B where A.category_id='1' and A.category_id = B.parent_id; </code></pre> <p>I was rejected from the interview. However, I am curious to know how to better this.</p>
[]
[ { "body": "<p>I have a small concern about your approach that I think you should have addressed during the interview because it could raise potential issues in your design.</p>\n\n<p>Do you want/need nested product categories?</p>\n\n<p>As it currently stands you're allowing nested categories and even allowing loops of categories where a category can reference itself or one of it's own subcategories.</p>\n\n<p>If you don't want nested categories then one of your restrictions will have to be that category with a parent should check it's parent doesn't also have a parent. The easiest way to do this is with two extra virtual columns(not stored), the first will simply say if a table has a parent(<code>parent_id IS NOT NULL</code>) and the second defines the value we need to create said relationship(namely that the value should be 0).</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE category(\n category_id TEXT PRIMARY KEY,\n category_name TEXT,\n parent_id TEXT,\n is_subcategory INT GENERATED ALWAYS AS (parent_id IS NOT NULL) VIRTUAL,\n can_be_child_of_subcategory INT GENERATED ALWAYS AS (0) VIRTUAL,\n FOREIGN KEY (parent_id, can_be_child_of_subcategory) REFERENCES category(category_id, is_subcategory) ON UPDATE RESTRICT\n);\n</code></pre>\n\n<p>And now without changing the definition of the virtual columns we can't add a subcategory to a subcategory.</p>\n\n<hr>\n\n<p>That said there's a few less major issues that might be worth considering in a bit more detail:</p>\n\n<p>You should be using a foreign key, not an index:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>FOREIGN KEY(parent_id) REFERENCES category(category_id)\n</code></pre>\n\n<p>You appear to be using TEXT as the field type, but accessing it with integers. If you're using a text type it's worth making it clear it's a GUID, either way you should use the right type for the field.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>category_id INT\ncategory_id = :sub_category_id\n-- OR\ncategory_id CHARACTER(32)\ncategory_id = :sub_category_guid\n</code></pre>\n\n<p>It's ANSISQL standards to write keywords in upper case, obviously you don't need to keep to that standard as every SQL language supports lower or mixed case, but almost every documentation will have keywords in all caps so it's worth keeping to the convention:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE category(category_id CHARACTER(32) PRIMARY KEY,\ncategory_name TEXT,parent_id CHARACTER(32));\n</code></pre>\n\n<p>I also suggest making things not null</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE category(category_id CHARACTER(32) NOT NULL PRIMARY KEY,\ncategory_name TEXT,parent_id CHARACTER(32));\n</code></pre>\n\n<p>I'd also suggest adding a bit more whitespace and at least for an interview document choices</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE category(\n category_id CHARACTER(32) NOT NULL PRIMARY KEY,\n category_name TEXT,\n parent_id CHARACTER(32),\n FOREIGN KEY (parent_id)\n REFERENCES category(category_id) ON UPDATE RESTRICT\n);\n</code></pre>\n\n<p>Finally I'm really not a fan of your naming on the aliases for the table. Much nicer to use a descriptive name to make it easier to understand:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>-- Fetch all child subcategories for a given category\nSELECT\n SubCategory.category_name AS CategoryName\nFROM category ParentCategory,\n category SubCategory\nWHERE\n ParentCategory.category_id = :parent_category_guid\n AND\n ParentCategory.parent_id = SubCategory.category_id\n;\n\n-- Fetch the parent category for the child\nSELECT\n ParentCategory.category_name AS CategoryName\nFROM category ParentCategory,\n category SubCategory\nWHERE\n SubCategory.category_id = :sub_category_guid\n AND\n ParentCategory.category_id = SubCategory.parent_id\n;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:25:17.017", "Id": "467232", "Score": "0", "body": "Nesting of categories must be allowed. We are trying to represent a directory like structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T12:31:05.117", "Id": "483796", "Score": "0", "body": "`NOT NULL PRIMARY KEY` is redundant; the latter implies the former. See for instance https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-PRIMARY-KEYS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T13:06:19.480", "Id": "483942", "Score": "0", "body": "@Reinderien He tagged SQLite, not postgress. In SQLite primary keys allow null unless otherwise stated for compatibility reasons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T13:24:51.820", "Id": "483952", "Score": "0", "body": "That's a terrible idea, but it's good to know." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:46:56.000", "Id": "238235", "ParentId": "238216", "Score": "1" } }, { "body": "<p>I'll echo @scragar's recommendation that your ID types be integers and not text. This is a significant misrepresentation of types.</p>\n<p>Otherwise: you're using the old, implicit join style. The new, explicit join is recommended; this would turn:</p>\n<pre><code>Select B.category_name as CategoryName from category A,\ncategory B where A.category_id='3' and \nA.parent_id = B.category_id;\n</code></pre>\n<p>into</p>\n<pre><code>select parent.category_name\nfrom category child\njoin category parent on parent.id = child.parent_id\nwhere child.id = 3;\n</code></pre>\n<p>The schema is also open to integrity failures. You need to add a <code>references</code> clause in your table definition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T12:44:11.873", "Id": "246245", "ParentId": "238216", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T02:39:34.117", "Id": "238216", "Score": "3", "Tags": [ "sql", "database", "sqlite" ], "Title": "Database Design for representing category relationships" }
238216
<p>I am creating an API in .net core and I just could not figure out how to put the following Linq expression into a single call:</p> <pre><code>public async Task&lt;ActionResult&lt;IEnumerable&lt;MyClass&gt;&gt;&gt; GetByReference(string reference) { var myClassPkColumn = _context.MyClass .Where(myClass =&gt; myClass.PkColumn.Equals(reference)) .Take(1) .ToList(); if (myClassPkColumn.Count &gt; 0) { return myClassPkColumn; } else { var myClassDescription = _context.MyClass .Where(myClass =&gt; myClass.Description.Contains(reference)) .Take(8) .ToListAsync(); return await myClassDescription; } } </code></pre> <p>In my front-end I am creating an autocomplete function and this now serves my intended purpose but I am curious if I could have made this into a single call (I guess for performance purposes).</p> <p>If not possible then could I have written this in a cleaner way?</p> <p>I hope that it is understandable that both columns are of type string and the first one I am querying is the primary key column (with 2-3 characters) while the second one is a non unique one with up to 50 characters.</p> <p>The issue I had with the first approach:</p> <pre><code>var myClassResult = _context.MyClass .Where(myClass =&gt; myClass.PkColumn.Equals(reference) || myClass.Description.Contains(reference)) .Take(8) .ToListAsync(); </code></pre> <p>was that the result was always prioritizing the Description column over the PkColumn intead of my desired expectation which is the other way around. Even after I added <code>orderBy</code> I couldnt get it to show me the pkColumn result when I know there was one.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:18:08.103", "Id": "467241", "Score": "2", "body": "Can you show your orderby code? Something like this .OrderByDescending(myClass => myClass.PkColumn.Equals(reference)) before your take should give you what you are looking for" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:35:47.090", "Id": "467253", "Score": "1", "body": "Generally we like to see whole classes to review, there is not quite enough code here to do a good review." } ]
[ { "body": "<p>I believe there is not much to improve in here.</p>\n\n<p>If you really want to make a one call to sql server, then you can move this logic to sql procedure.</p>\n\n<p>You can visually improve first query and use FirstOrDefault:</p>\n\n<pre><code>var myClassPkColumn = _context.MyClass.FirstOrDefault(x =&gt; x.PkColumn == reference);\n\nif (myClassPkColumn != null)\n{\n return new MyClass[] { myClassPkColumn };\n}\n</code></pre>\n\n<p>If you know that your PkColumn is always less or equal 3 characters, then you can add if statement and skip first query completely in case your reference has bigger length.</p>\n\n<pre><code>if (reference?.Length &lt;= 3)\n{\n // query by PkColumn column\n}\n</code></pre>\n\n<p>If you want to combine two queries into one you can add this OrderBy:</p>\n\n<pre><code>var myClassResult = _context.MyClass\n .Where(myClass =&gt; myClass.PkColumn.Equals(reference) ||\n myClass.Description.Contains(reference))\n .OrderBy(x =&gt; x.PkColumn == reference ? 0 : 1)\n .Take(8)\n .ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:19:29.417", "Id": "467338", "Score": "0", "body": "It works but without the ternary conditional operator however, so basically what @charlesNRice said. I dont know what I messed up on my first attempt with orderBy but im glad I got it working now. Thanks to all who contributed!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T09:59:23.490", "Id": "238295", "ParentId": "238224", "Score": "1" } } ]
{ "AcceptedAnswerId": "238295", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T08:28:32.000", "Id": "238224", "Score": "0", "Tags": [ "c#", ".net-core" ], "Title": "Prioritizing one column over the other column of the same table" }
238224
<p>I'm completed the Reddit challenge #380 (<a href="https://www.reddit.com/r/dailyprogrammer/comments/cmd1hb/20190805_challenge_380_easy_smooshed_morse_code_1/" rel="nofollow noreferrer">source</a>).</p> <p>Here is an abbreviated description:</p> <blockquote> <p>Normally [in Morse code], you would indicate where one letter ends and the next begins, for instance with a space between the letters' codes, but for this challenge, just smoosh all the coded letters together into a single string consisting of only dashes and dots.</p> <p>An obvious problem with this system is that decoding is ambiguous. For instance, both <code>bits</code> and <code>three</code> encode to the same string, so you can't tell which one you would decode to without more information.</p> </blockquote> <p>I've done the best I can, but wanted a few insights to what I could do that would be better.</p> <p><strong>Code</strong></p> <p>The code is the solution to the Reddit challenge. In the main method, the class is initialised then prints each of the solutions out. Please note that the main challenge and optional challenges 1-4 are included. I did not include optional challenge 5. The class on initialisation converts and groups the words from a file 'wordlist.txt' that was sourced in the reddit post. I will not include the file here as it is pretty long but here is the <a href="https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt" rel="nofollow noreferrer">source</a>. Please ensure you rename the file to 'wordlist.txt'.</p> <p><strong>Unorthodox choices</strong></p> <ol> <li><p><code>morse_alphabet</code> variable</p> <p>PyLint highlighted it as a 'line-too-long' exception. I disabled it since shorting the variable name would not have helped but I'm unsure if I should have split up the line. I kept it there as it was easier than typing it out for each individual letter but maybe it was best to split up the letters?</p> </li> <li><p>count_longest_dash_run function</p> <p>It seems like it was an unorthodox solution, maybe there was a way to do this without the comparison?</p> </li> <li><p>The line repeated in the optional challenges <code>print(key+&quot;:&quot;+str(value))</code></p> <p>Should I have separated it into a function or would it have been overkill?</p> </li> <li><p>Documentation</p> <p>I'm unsure if the documentation, usually people put in return type or parameter information but i'm unsure what it should look like or if what i'm doing is correct.</p> </li> <li><p>Static methods and class methods</p> <p>Should I include <code>@typemethod</code> for all the functions or is this specific to certain situations such as the static method?</p> </li> </ol> <p><strong>Python Code</strong></p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; This module is a solution the the programming exercise found on reddit. Exercise: https://www.reddit.com/r/dailyprogrammer/comments/cmd1hb/20190805_challenge_380_easy_smooshed_morse_code_1/ This solution is not posted in the reddit thread. This solution completes the challenge and the optional challenges 1-4. On running this script, you should see the results with the console. Each set of results will be labeled with which challenge they refer to. &quot;&quot;&quot; class Morsecoder: &quot;&quot;&quot; This class handles generating the morse code for all of the words listed in the wordlist.txt and storing them. It also handles generating the result for each challenge. &quot;&quot;&quot; def __init__(self): &quot;&quot;&quot; Create a list of words and its morse code. Also creates a dict compiling the words with the same more code together. &quot;&quot;&quot; # pylint: disable=line-too-long morse_alphabet = &quot;.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..&quot; self.morse_characters = morse_alphabet.split(&quot; &quot;) self.words = [] self.encoded_words = {} self.encode_word_list() self.find_matching_codes() def get_morse_character(self, char): &quot;&quot;&quot; Retrieves the morse character of the character. Return none is the character int is not int the lower case range. &quot;&quot;&quot; char_int = ord(char)-97 if char_int &gt;= len(self.morse_characters) or char_int &lt; 0: return None return self.morse_characters[char_int] def encode_string(self, string): &quot;&quot;&quot; Encodes the entire string into the morse code. Raises an Exception if the string is not a lowercase alphabet only string. &quot;&quot;&quot; if string.islower() and string.isalpha(): morsecode = '' for char in string: morsecode += self.get_morse_character(char) return morsecode ex = &quot;'&quot;+string+&quot;' could not be converted.&quot; ex += &quot;The string must only contain lowercase alphabet characters&quot; raise Exception(ex) def encode_word_list(self): &quot;&quot;&quot; Reads the wordlist.txt file and encodes each line into morse code. The original word and the morse code is stored within the words variables. &quot;&quot;&quot; with open(&quot;wordlist.txt&quot;, 'r') as file: content = file.readlines() content = [x.strip() for x in content] for word in content: encoded = self.encode_string(word) self.words.append([word, encoded]) def find_matching_codes(self): &quot;&quot;&quot; Find morse codes that are the same and groups the words under the morse code. &quot;&quot;&quot; for word, encoded in self.words: if encoded in self.encoded_words: self.encoded_words[encoded].append(word) else: self.encoded_words[encoded] = [word] @staticmethod def count_longest_dash_run(string): &quot;&quot;&quot; static method that count the number of '-' in a row and retrieved the number of the longest '-' in a row within the string. &quot;&quot;&quot; dashruns = string.split('.') longest_dash_run = 0 for dashrun in dashruns: length = len(dashrun) if length &gt; longest_dash_run: longest_dash_run = length return longest_dash_run @staticmethod def is_palindrome(word): &quot;&quot;&quot; static method that checks if the word is a palindrome. &quot;&quot;&quot; return word == word[::-1] def challenge(self): &quot;&quot;&quot; prints out the result of the challenge. &quot;&quot;&quot; print(&quot;Challenge Result:&quot;) print(self.encode_string(&quot;sos&quot;)) print(self.encode_string(&quot;daily&quot;)) print(self.encode_string(&quot;programmer&quot;)) print(self.encode_string(&quot;bits&quot;)) print(self.encode_string(&quot;three&quot;)) def optional_challenge_one(self): &quot;&quot;&quot; prints out the result of the first optional challenge. &quot;&quot;&quot; print(&quot;Optional Challenge One Result:&quot;) for key in self.encoded_words: value = self.encoded_words[key] if len(value) &gt;= 13: print(key+&quot;:&quot;+str(value)) def optional_challenge_two(self): &quot;&quot;&quot; prints out the result of the second optional challenge. &quot;&quot;&quot; print(&quot;Optional Challenge Two Result:&quot;) for key in self.encoded_words: value = self.encoded_words[key] if self.count_longest_dash_run(key) == 15: print(key+&quot;:&quot;+str(value)) def optional_challenge_three(self): &quot;&quot;&quot; prints out the result of the third optional challenge. &quot;&quot;&quot; print(&quot;Optional Challenge Three Result:&quot;) selected = {} for pair in self.words: word = pair[0] encoded = pair[1] if len(word) == 21: selected[encoded] = word for key in selected: if key.count('.') == key.count('-'): value = selected[key] print(key+&quot;:&quot;+str(value)) def optional_challenge_four(self): &quot;&quot;&quot; prints out the result of the fourth optional challenge. &quot;&quot;&quot; print(&quot;Optional Challenge Four Result:&quot;) for pair in self.words: key = pair[0] value = pair[1] if len(key) == 13: if self.is_palindrome(value): print(str(value)+&quot;:&quot;+key) if __name__ == &quot;__main__&quot;: CODER = Morsecoder() CODER.challenge() CODER.optional_challenge_one() CODER.optional_challenge_two() CODER.optional_challenge_three() CODER.optional_challenge_four() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:18:30.667", "Id": "467229", "Score": "2", "body": "Please always include an abbreviated description of the programming challenge in your question in case external links become invalid. I've done so for this post, just keep in mind to include for future questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:05:33.023", "Id": "467236", "Score": "0", "body": "@AlexV Thank you. I will do so in future posts." } ]
[ { "body": "<ol>\n<li><p>The line-too-long can be fixed by wrapping the long string. There are at least two obvious ways to do it. First, use a triple quoted string. This lets the string include span multiple lines. A possible problem is that the string now includes the extra spaces at the beginning of the second and third lines. However, those will get removed by the call to <code>split()</code>.</p>\n\n<pre><code>morse_alphabet = \"\"\".- -... -.-. -.. . ..-. --. .... .. .---\n -.- .-.. -- -. --- .--. --.- .-. ... -\n ..- ...- .-- -..- -.-- --..\"\"\"\n</code></pre>\n\n<p>A second possibility is to take advantage of the interpreter concatenating adjacent strings.</p>\n\n<pre><code>morse_alphabet = (\".- -... -.-. -.. . ..-. --. .... .. .---\"\n \" -.- .-.. -- -. --- .--. --.- .-. ... -\"\n \" ..- ...- .-- -..- -.-- --..\")\n</code></pre>\n\n<p>In both cases, <code>morse_alphabet = morse_alphabet.split()</code> will split the string on whitespace characters and return a list of the morse codes.</p></li>\n<li><p>A comparison is needed somewhere, to find the longest length of '-'s. It can be explicit, as in your code. Or implicit, as in the built in <code>max()</code> function. The code can be simplified by using a generator expression to calculate the lengths of the dash runs.</p>\n\n<pre><code>def count_longest_dash_run(code):\n return max(len(dashrun) for dashrun in code.split('.'))\n</code></pre></li>\n<li><p>For a small program like this, pulling out the <code>print(...)</code> into a separate function is probably overkill. But using either an f-string or <code>str.format()</code> or would be better than concatenating strings using '+'.</p>\n\n<pre><code>print(f\"{key}: {value}\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>print(\"{}: {}\".format(key, value))\n</code></pre></li>\n<li><p>About documentation. </p>\n\n<p>I find type hints to needlessly clutter the code for small programs like this. For larger projects they can help document expected types.</p>\n\n<p>Docstrings should tell someone how to use the thing being documented (class, function, module, method, etc.). They should be complete and correct. Here, the docstring for <code>encode_string()</code> says \"Encodes the entire string into the morse code.\", which is not correct. It encodes the string into morse code, <strong>without spaces between the letters</strong>.</p>\n\n<p>The docstring for <code>challenge()</code> says \"prints out the result of the challenge.\" But no one will remember what the challenge was next week/month/year. Similarly for the optional challenges.</p></li>\n<li><p>I'm not sure what your asking here. </p></li>\n</ol>\n\n<p>Other things.</p>\n\n<p>You can iterate over a list of 2-tuples like so:</p>\n\n<pre><code>for key, value in self.words:\n ...\n</code></pre>\n\n<p>The encoding could be done using <code>str.maktrans()</code> and <code>str.translate()</code>.</p>\n\n<p>Using <code>collections.defaultdict</code> lets you skip doing a special case for when a key isn't in the dictionary. For example, if <code>__init__</code> had <code>self.encoded_words = defaultdict(list)</code>, then</p>\n\n<pre><code>def find_matching_codes(self):\n for word, encoded in self.words:\n self.encoded_words[encoded].append(word)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:15:14.680", "Id": "467473", "Score": "0", "body": "Thank you for your help!. Regarding 5, I've seen '@Classmethod' and similar thing to the '@staticmethod', i'm just wondering if I should have included them or not or if they are even necessary to the code at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:50:33.210", "Id": "467493", "Score": "1", "body": "@Meerfallthedewott, `@classmethod` is mostly useful for things like alternate constructors (e.g., SomeClass.from_string() or SomeClass.from_json()) that provide a way to create a class instance other than `__init__()`. The [answers to this question](https://stackoverflow.com/questions/2438473/what-is-the-advantage-of-using-static-methods-in-python) discuss the \"why\" of staticmethods." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T23:20:53.133", "Id": "238337", "ParentId": "238227", "Score": "3" } } ]
{ "AcceptedAnswerId": "238337", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T09:38:36.357", "Id": "238227", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge", "reddit", "morse-code" ], "Title": "Reddit Challenge #380 Python" }
238227
<p>I am looping through pdf files, using regex search and findall to append list type data into a dataframe. I export to excel for end user to easily search info. Below is method breakdown of this script:</p> <ul> <li>Find pdf files in folder and delete duplicate files</li> <li>Define regex compile objects outside of loop.</li> <li>Growinglist() generator as workaround for pandas dataframe</li> <li>Use for loop to iterate through pdf files and create dataframe of equal length lists.</li> <li>Append to DataFrame df1.</li> <li>export to xlsx excel file for end user</li> </ul> <p>Below are some sample strings after being joined:</p> <pre><code>output1 = '''ROAD OCCUPANCY LICENCELICENCE NO : 1314824TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :LFR001-WB-CONTRA-Cecil to Justin ATS-WCX-3B 005LOCATIONSubject Road:LILYFIELD RDFrom:GORDON ST, ROZELLETo:GROVE ST, LILYFIELDCouncil:INNER WESTLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Contra Flow; Standard Lane MergeClosure Type:All lanes one directionClosure Lane(s):ShoulderDirection(s):Eastbound and WestboundLICENCE DURATIONFrom:01-Dec-2019To:31-Jan-2020LICENCE CONDITIONS1YOU MUST USE SHIFT ACTIVATION WEB ADDRESShttps://myrol.transport.nsw.gov.au TO ACTIVATE AND DEACTIVATE YOURAPPROVED ROAD OCCUPANCY LICENCE(S). (TO CHANGE TRAFFICCONTROL SIGNALS TO FLASHING YELLOW OR TO ACTIVATEPERMANENT VARIABLE MESSAGE SIGNS DIAL 1800 679 782)2THIS LICENCE IS NOT AN APPROVAL OF THE PROPONENT'S TRAFFICCONTROL PLAN. PLEASE NOTE WORKCOVER REQUIRES THATTRAFFIC CONTROL PLANS COMPLY WITH AS1742.33ALL MATTERS RELATING TO NOISE GENERATION OR OTHERENVIRONMENTAL FACTORS ON SITE ARE UNDER THE JURISDRICTIONOF THE LOCAL COUNCIL AND/OR THE ENVIRONMENTAL PROTECTIONAUTHORITY.4SHOULD THE PROPOSED WORKS INVOLVE UNDERBORING OREXCAVATION OF STATE ROAD ASSETS OR THE REMOVAL OF KERBAND GUTTER, DETAILS OF WORKS MUST BE APPROVED BY THERMS'S ASSEST MANAGEMENT BRANCH.5NOTIFICATION TO AFFECTED BUSINESSES, RESIDENTS AND OTHERSTAKEHOLDERS MUST BE UNDERTAKEN AT LEAST 5 BUSINESS DAYSPRIOR TO WORKS COMMENCING6ROAD OCCUPANCY OFFICE AT TMC WILL BE CLOSED DURING THECHRISTMAS/NEW YEAR PERIOD FROM MONDAY 23 DECEMBER 2019TO FRIDAY 3 JANUARY 2020 (INCLUSIVE).I. THE MINIMUM 10 BUSINESS DAYS PROCESSING PERIOD WILL APPLYFROM 6 JANUARY 2020 FOR ALL NEW AND EXTENSION ROADOCCUPANCY LICENCE APPLICATIONS RECEIVED DURING THESHUTDOWN PERIOD.II. ALL EXISTING ROLS THAT EXPIRE DURING THE SHUTDOWN PERIODREQUIRING EXTENSIONS MUST BE SUBMITTED TO THIS OFFICE VIAOPLINC NO LATER THAN FRIDAY 13 DECEMBER 2019.7FOR ALL WORKS IMPACTING BUS ROUTES OR STOPS, SYDNEYCOORDINATION OFFICE, TRANSPORT INTEGRATION ARE TO BECONSULTED. PLEASE CONTACT -- FRANKIE.PASSARELLI@TMC.TRANSPORT.NSW.GOV.AU8ENSURE THE APPROPRIATE HOLD POINT IS RELEASED FOR THE TCPUSED AS PART OF THIS ROL9NO WORK 23 DEC - 03 JAN DUE TO CHRISTMAS EMBARGO10ADEQUATE ADVANCE WARNING MUST BE PROVIDED TOAPPROACHING MOTORISTS.11TRAFFIC FLOW MUST BE MAINTAINED IN BOTH DIRECTIONS AT ALLTIMES.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeSun01Dec07:00 -Sun01Dec18:00Mon02Dec07:00 -Mon02Dec18:00Tue03Dec07:00 -Tue03Dec18:00Wed04Dec07:00 -Wed04Dec18:00Thu05Dec07:00 -Thu05Dec18:00Fri06Dec07:00 -Fri06Dec18:00Sat07Dec07:00 -Sat07Dec18:00Sun08Dec07:00 -Sun08Dec18:00Mon09Dec07:00 -Mon09Dec18:00Tue10Dec07:00 -Tue10Dec18:00Wed11Dec07:00 -Wed11Dec18:00Thu12Dec07:00 -Thu12Dec18:00Fri13Dec07:00 -Fri13Dec18:00Sat14Dec07:00 -Sat14Dec18:00Sun15Dec07:00 -Sun15Dec18:00Mon16Dec07:00 -Mon16Dec18:00Tue17Dec07:00 -Tue17Dec18:00Wed18Dec07:00 -Wed18Dec18:00Thu19Dec07:00 -Thu19Dec18:00Fri20Dec07:00 -Fri20Dec18:00Sat21Dec07:00 -Sat21Dec18:00Sun22Dec07:00 -Sun22Dec18:00Thu02Jan07:00 -Thu02Jan18:00Sat04Jan07:00 -Sat04Jan18:00Sun05Jan07:00 -Sun05Jan18:00Mon06Jan07:00 -Mon06Jan18:00Tue07Jan07:00 -Tue07Jan18:00Wed08Jan07:00 -Wed08Jan18:00Thu09Jan07:00 -Thu09Jan18:00Fri10Jan07:00 -Fri10Jan18:00Sat11Jan07:00 -Sat11Jan18:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 1 of 4,ROAD OCCUPANCY LICENCELICENCE NO : 1314824TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :LFR001-WB-CONTRA-Cecil to Justin ATS-WCX-3B 005LOCATIONSubject Road:LILYFIELD RDFrom:GORDON ST, ROZELLETo:GROVE ST, LILYFIELDCouncil:INNER WESTLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Contra Flow; Standard Lane MergeClosure Type:All lanes one directionClosure Lane(s):ShoulderDirection(s):Eastbound and WestboundLICENCE DURATIONFrom:01-Dec-2019To:31-Jan-2020LICENCE CONDITIONS12QUEUING FROM THE WORKS MUST BE MONITORED AT ALL TIMES.IF QUEUING EXTEND BEYOND 100 METRES, OR IF DELAYS EXCEED 2MINUTES ALL TRAVEL LANES MUST BE RE-OPENED UNTIL TRAFFICQUEUES ARE CLEAR AND TRAFFIC IS FREE FLOWING BEFORERESUMING THE CLOSURE.13PEDESTRIAN ACCESS MUST BE MAINTAINED AROUND THE WORKAREA IN A SAFE MANNER, COMPLYING WITH COUNCILREQUIREMENTS.14PARKING MUST BE RESTRICTED IN THE AREA SURROUNDING WORKSTO ALLOW FOR LANE OPERATION.15THIS LICENCE OPERATES IN CONJUNCTION WITH A SPEED LIMITREDUCTION TO 40 KM/H. REFER TO SZA 1314824/001APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeSun12Jan07:00 -Sun12Jan18:00Mon13Jan07:00 -Mon13Jan18:00Tue14Jan07:00 -Tue14Jan18:00Wed15Jan07:00 -Wed15Jan18:00Thu16Jan07:00 -Thu16Jan18:00Fri17Jan07:00 -Fri17Jan18:00Sat18Jan07:00 -Sat18Jan18:00Sun19Jan07:00 -Sun19Jan18:00Mon20Jan07:00 -Mon20Jan18:00Tue21Jan07:00 -Tue21Jan18:00Wed22Jan07:00 -Wed22Jan18:00Thu23Jan07:00 -Thu23Jan18:00Fri24Jan07:00 -Fri24Jan18:00Sat25Jan07:00 -Sat25Jan18:00Sun26Jan07:00 -Sun26Jan18:00Mon27Jan07:00 -Mon27Jan18:00Tue28Jan07:00 -Tue28Jan18:00Wed29Jan07:00 -Wed29Jan18:00Thu30Jan07:00 -Thu30Jan18:00Fri31Jan07:00 -Fri31Jan18:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 2 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 3 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 4 of 4''' output2 = '''ROAD OCCUPANCY LICENCELICENCE NO : 1314782TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR011-E-2of4-S-Iron Cove to Wellington ATS-WCX3B 056 CombinedLOCATIONSubject Road:VICTORIA RDFrom:HENLEY MARINE DR, DRUMMOYNETo:WELLINGTON ST, ROZELLECouncil:CANADA BAYLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Standard Lane MergeClosure Type:2 lanes of 3Closure Lane(s):Lane 1 (kerb lane/s); Lane 2 (next after kerb lane)Direction(s):SouthboundLICENCE DURATIONFrom:01-Dec-2019To:01-Feb-2020LICENCE CONDITIONS1YOU MUST USE SHIFT ACTIVATION WEB ADDRESShttps://myrol.transport.nsw.gov.au TO ACTIVATE AND DEACTIVATE YOURAPPROVED ROAD OCCUPANCY LICENCE(S). (TO CHANGE TRAFFICCONTROL SIGNALS TO FLASHING YELLOW OR TO ACTIVATEPERMANENT VARIABLE MESSAGE SIGNS DIAL 1800 679 782)2THIS LICENCE IS NOT AN APPROVAL OF THE PROPONENT'S TRAFFICCONTROL PLAN. PLEASE NOTE WORKCOVER REQUIRES THATTRAFFIC CONTROL PLANS COMPLY WITH AS1742.33ALL MATTERS RELATING TO NOISE GENERATION OR OTHERENVIRONMENTAL FACTORS ON SITE ARE UNDER THE JURISDRICTIONOF THE LOCAL COUNCIL AND/OR THE ENVIRONMENTAL PROTECTIONAUTHORITY.4SHOULD THE PROPOSED WORKS INVOLVE UNDERBORING OREXCAVATION OF STATE ROAD ASSETS OR THE REMOVAL OF KERBAND GUTTER, DETAILS OF WORKS MUST BE APPROVED BY THERMS'S ASSEST MANAGEMENT BRANCH.5NOTIFICATION TO AFFECTED BUSINESSES, RESIDENTS AND OTHERSTAKEHOLDERS MUST BE UNDERTAKEN AT LEAST 5 BUSINESS DAYSPRIOR TO WORKS COMMENCING6ROAD OCCUPANCY OFFICE AT TMC WILL BE CLOSED DURING THECHRISTMAS/NEW YEAR PERIOD FROM MONDAY 23 DECEMBER 2019TO FRIDAY 3 JANUARY 2020 (INCLUSIVE).I. THE MINIMUM 10 BUSINESS DAYS PROCESSING PERIOD WILL APPLYFROM 6 JANUARY 2020 FOR ALL NEW AND EXTENSION ROADOCCUPANCY LICENCE APPLICATIONS RECEIVED DURING THESHUTDOWN PERIOD.II. ALL EXISTING ROLS THAT EXPIRE DURING THE SHUTDOWN PERIODREQUIRING EXTENSIONS MUST BE SUBMITTED TO THIS OFFICE VIAOPLINC NO LATER THAN FRIDAY 13 DECEMBER 2019.7FOR ALL WORKS IMPACTING BUS ROUTES OR STOPS, SYDNEYCOORDINATION OFFICE, TRANSPORT INTEGRATION ARE TO BECONSULTED. PLEASE CONTACT -- FRANKIE.PASSARELLI@TMC.TRANSPORT.NSW.GOV.AU8ENSURE THE APPROPRIATE HOLD POINT IS RELEASED FOR THE TCPUSED AS PART OF THIS ROL9NO WORK 23 DEC - 03 JAN DUE TO CHRISTMAS EMBARGO10WORKSITE MUST BE SETUP TO ENSURE ONE (1) TRAFFICABLE LANEREMAINS OPEN TO TRAFFIC AT ALL TIMES IN EACH DIRECTION. LANEWIDTHS MUST BE SUFFICIENT TO PERMIT HEAVY VEHICLES ACCESS.11ADEQUATE ADVANCE WARNING MUST BE PROVIDED TOAPPROACHING MOTORISTS.12EXISTING BUS STOPS IN WORK AREA MUST BE MAINTAINED INCONSULTATION WITH ALL BUS COMPANIES USING THESE STOPS.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeSun01Dec21:00 -Mon02Dec05:00Mon02Dec21:00 -Tue03Dec05:00Tue03Dec22:00 -Wed04Dec05:00Wed04Dec22:00 -Thu05Dec05:00Thu05Dec22:00 -Fri06Dec05:00Fri06Dec22:00 -Sat07Dec06:00Sat07Dec22:00 -Sun08Dec06:00Sun08Dec21:00 -Mon09Dec05:00Mon09Dec21:00 -Tue10Dec05:00Tue10Dec22:00 -Wed11Dec05:00Wed11Dec22:00 -Thu12Dec05:00Thu12Dec22:00 -Fri13Dec05:00Fri13Dec22:00 -Sat14Dec06:00Sat14Dec22:00 -Sun15Dec06:00Sun15Dec21:00 -Mon16Dec05:00Mon16Dec21:00 -Tue17Dec05:00Tue17Dec22:00 -Wed18Dec05:00Wed18Dec22:00 -Thu19Dec05:00Thu19Dec22:00 -Fri20Dec05:00Fri20Dec22:00 -Sat21Dec06:00Sat21Dec22:00 -Sun22Dec06:00Sun22Dec21:00 -Mon23Dec05:00Sat04Jan22:00 -Sun05Jan06:00Sun05Jan21:00 -Mon06Jan05:00Mon06Jan21:00 -Tue07Jan05:00Tue07Jan22:00 -Wed08Jan05:00Wed08Jan22:00 -Thu09Jan05:00Thu09Jan22:00 -Fri10Jan05:00Fri10Jan22:00 -Sat11Jan06:00Sat11Jan22:00 -Sun12Jan06:00Sun12Jan21:00 -Mon13Jan05:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 1 of 4,ROAD OCCUPANCY LICENCELICENCE NO : 1314782TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR011-E-2of4-S-Iron Cove to Wellington ATS-WCX3B 056 CombinedLOCATIONSubject Road:VICTORIA RDFrom:HENLEY MARINE DR, DRUMMOYNETo:WELLINGTON ST, ROZELLECouncil:CANADA BAYLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Standard Lane MergeClosure Type:2 lanes of 3Closure Lane(s):Lane 1 (kerb lane/s); Lane 2 (next after kerb lane)Direction(s):SouthboundLICENCE DURATIONFrom:01-Dec-2019To:01-Feb-2020LICENCE CONDITIONS13QUEUING FROM THE WORKS MUST BE MONITORED AT ALL TIMES.IF QUEUING EXTEND BEYOND 100 METRES, OR IF DELAYS EXCEED 2MINUTES ALL TRAVEL LANES MUST BE RE-OPENED UNTIL TRAFFICQUEUES ARE CLEAR AND TRAFFIC IS FREE FLOWING BEFORERESUMING THE CLOSURE.14PEDESTRIAN ACCESS MUST BE MAINTAINED AROUND THE WORKAREA IN A SAFE MANNER, COMPLYING WITH COUNCILREQUIREMENTS.15SIGNAL OPERATIONS MUST BE DISCUSSED WITH TMC PRIOR TOUNDERTAKING CLOSURE.16THIS LICENCE OPERATES IN CONJUNCTION WITH A SPEED LIMITREDUCTION TO 40 KM/H. REFER TO SZA 1314782/00117CLOSE CONTACT MUST BE MAINTAINED WITH TRANSPORTMANAGEMENT CENTRE ON 1300 725 886 DURING THE WORKS.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeMon13Jan21:00 -Tue14Jan05:00Tue14Jan22:00 -Wed15Jan05:00Wed15Jan22:00 -Thu16Jan05:00Thu16Jan22:00 -Fri17Jan05:00Fri17Jan22:00 -Sat18Jan06:00Sat18Jan22:00 -Sun19Jan06:00Sun19Jan21:00 -Mon20Jan05:00Mon20Jan21:00 -Tue21Jan05:00Tue21Jan22:00 -Wed22Jan05:00Wed22Jan22:00 -Thu23Jan05:00Thu23Jan22:00 -Fri24Jan05:00Fri24Jan22:00 -Sat25Jan06:00Sat25Jan22:00 -Sun26Jan06:00Sun26Jan21:00 -Mon27Jan05:00Mon27Jan21:00 -Tue28Jan05:00Tue28Jan22:00 -Wed29Jan05:00Wed29Jan22:00 -Thu30Jan05:00Thu30Jan22:00 -Fri31Jan05:00Fri31Jan22:00 -Sat01Feb06:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 2 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 3 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 4 of 4''' output3 = '''ROAD OCCUPANCY LICENCELICENCE NO : 1314796TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR011-E-2of4-S-Iron Cove to Wellington ATS-WCX3B 054 CombinedLOCATIONSubject Road:VICTORIA RDFrom:HENLEY MARINE DR, DRUMMOYNETo:WELLINGTON ST, ROZELLECouncil:CANADA BAYLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Standard Lane MergeClosure Type:1 lane of 3Closure Lane(s):Lane 1 (kerb lane/s); Lane 3Direction(s):SouthboundLICENCE DURATIONFrom:01-Dec-2019To:31-Jan-2020LICENCE CONDITIONS1YOU MUST USE SHIFT ACTIVATION WEB ADDRESShttps://myrol.transport.nsw.gov.au TO ACTIVATE AND DEACTIVATE YOURAPPROVED ROAD OCCUPANCY LICENCE(S). (TO CHANGE TRAFFICCONTROL SIGNALS TO FLASHING YELLOW OR TO ACTIVATEPERMANENT VARIABLE MESSAGE SIGNS DIAL 1800 679 782)2THIS LICENCE IS NOT AN APPROVAL OF THE PROPONENT'S TRAFFICCONTROL PLAN. PLEASE NOTE WORKCOVER REQUIRES THATTRAFFIC CONTROL PLANS COMPLY WITH AS1742.33ALL MATTERS RELATING TO NOISE GENERATION OR OTHERENVIRONMENTAL FACTORS ON SITE ARE UNDER THE JURISDRICTIONOF THE LOCAL COUNCIL AND/OR THE ENVIRONMENTAL PROTECTIONAUTHORITY.4SHOULD THE PROPOSED WORKS INVOLVE UNDERBORING OREXCAVATION OF STATE ROAD ASSETS OR THE REMOVAL OF KERBAND GUTTER, DETAILS OF WORKS MUST BE APPROVED BY THERMS'S ASSEST MANAGEMENT BRANCH.5NOTIFICATION TO AFFECTED BUSINESSES, RESIDENTS AND OTHERSTAKEHOLDERS MUST BE UNDERTAKEN AT LEAST 5 BUSINESS DAYSPRIOR TO WORKS COMMENCING6ROAD OCCUPANCY OFFICE AT TMC WILL BE CLOSED DURING THECHRISTMAS/NEW YEAR PERIOD FROM MONDAY 23 DECEMBER 2019TO FRIDAY 3 JANUARY 2020 (INCLUSIVE).I. THE MINIMUM 10 BUSINESS DAYS PROCESSING PERIOD WILL APPLYFROM 6 JANUARY 2020 FOR ALL NEW AND EXTENSION ROADOCCUPANCY LICENCE APPLICATIONS RECEIVED DURING THESHUTDOWN PERIOD.II. ALL EXISTING ROLS THAT EXPIRE DURING THE SHUTDOWN PERIODREQUIRING EXTENSIONS MUST BE SUBMITTED TO THIS OFFICE VIAOPLINC NO LATER THAN FRIDAY 13 DECEMBER 2019.7FOR ALL WORKS IMPACTING BUS ROUTES OR STOPS, SYDNEYCOORDINATION OFFICE, TRANSPORT INTEGRATION ARE TO BECONSULTED. PLEASE CONTACT -- FRANKIE.PASSARELLI@TMC.TRANSPORT.NSW.GOV.AU8NO WORK 23 DEC - 03 JAN DUE TO CHRISTMAS EMBARGO9ENSURE THE APPROPRIATE HOLD POINT IS RELEASED FOR THE TCPUSED AS PART OF THIS ROL10TWO (2) TRAFFICABLE LANES MUST REMAIN OPEN TO TRAFFIC ATALL TIMES. LANE WIDTHS MUST BE SUFFICIENT TO PERMIT HEAVYVEHICLES ACCESS.11ADEQUATE ADVANCE WARNING MUST BE PROVIDED TOAPPROACHING MOTORISTS.12EXISTING BUS STOPS IN WORK AREA MUST BE MAINTAINED INCONSULTATION WITH ALL BUS COMPANIES USING THESE STOPS.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeSun01Dec07:00 -Sun01Dec17:00Mon02Dec10:00 -Mon02Dec15:00Tue03Dec10:00 -Tue03Dec15:00Wed04Dec10:00 -Wed04Dec15:00Thu05Dec10:00 -Thu05Dec15:00Fri06Dec10:00 -Fri06Dec15:00Sat07Dec07:00 -Sat07Dec17:00Sun08Dec07:00 -Sun08Dec17:00Mon09Dec10:00 -Mon09Dec15:00Tue10Dec10:00 -Tue10Dec15:00Wed11Dec10:00 -Wed11Dec15:00Thu12Dec10:00 -Thu12Dec15:00Fri13Dec10:00 -Fri13Dec15:00Sat14Dec07:00 -Sat14Dec17:00Sun15Dec07:00 -Sun15Dec17:00Mon16Dec10:00 -Mon16Dec15:00Tue17Dec10:00 -Tue17Dec15:00Wed18Dec10:00 -Wed18Dec15:00Thu19Dec10:00 -Thu19Dec15:00Fri20Dec10:00 -Fri20Dec15:00Sat21Dec07:00 -Sat21Dec17:00Sun22Dec07:00 -Sun22Dec17:00Sat04Jan07:00 -Sat04Jan17:00Sun05Jan07:00 -Sun05Jan17:00Mon06Jan10:00 -Mon06Jan15:00Tue07Jan10:00 -Tue07Jan15:00Wed08Jan10:00 -Wed08Jan15:00Thu09Jan10:00 -Thu09Jan15:00Fri10Jan10:00 -Fri10Jan15:00Sat11Jan07:00 -Sat11Jan17:00Sun12Jan07:00 -Sun12Jan17:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 1 of 4,ROAD OCCUPANCY LICENCELICENCE NO : 1314796TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR011-E-2of4-S-Iron Cove to Wellington ATS-WCX3B 054 CombinedLOCATIONSubject Road:VICTORIA RDFrom:HENLEY MARINE DR, DRUMMOYNETo:WELLINGTON ST, ROZELLECouncil:CANADA BAYLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Standard Lane MergeClosure Type:1 lane of 3Closure Lane(s):Lane 1 (kerb lane/s); Lane 3Direction(s):SouthboundLICENCE DURATIONFrom:01-Dec-2019To:31-Jan-2020LICENCE CONDITIONS13QUEUING FROM THE WORKS MUST BE MONITORED AT ALL TIMES.IF QUEUING EXTEND BEYOND 100 METRES, OR IF DELAYS EXCEED 2MINUTES ALL TRAVEL LANES MUST BE RE-OPENED UNTIL TRAFFICQUEUES ARE CLEAR AND TRAFFIC IS FREE FLOWING BEFORERESUMING THE CLOSURE.14PEDESTRIAN ACCESS MUST BE MAINTAINED AROUND THE WORKAREA IN A SAFE MANNER, COMPLYING WITH COUNCILREQUIREMENTS.15THIS LICENCE OPERATES IN CONJUNCTION WITH A SPEED LIMITREDUCTION TO 40 KM/H. REFER TO SZA 1314796/00116CLOSE CONTACT MUST BE MAINTAINED WITH TRANSPORTMANAGEMENT CENTRE ON 1300 725 886 DURING THE WORKS.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeMon13Jan10:00 -Mon13Jan15:00Tue14Jan10:00 -Tue14Jan15:00Wed15Jan10:00 -Wed15Jan15:00Thu16Jan10:00 -Thu16Jan15:00Fri17Jan10:00 -Fri17Jan15:00Sat18Jan07:00 -Sat18Jan17:00Sun19Jan07:00 -Sun19Jan17:00Mon20Jan10:00 -Mon20Jan15:00Tue21Jan10:00 -Tue21Jan15:00Wed22Jan10:00 -Wed22Jan15:00Thu23Jan10:00 -Thu23Jan15:00Fri24Jan10:00 -Fri24Jan15:00Sat25Jan07:00 -Sat25Jan17:00Sun26Jan07:00 -Sun26Jan17:00Mon27Jan10:00 -Mon27Jan15:00Tue28Jan10:00 -Tue28Jan15:00Wed29Jan10:00 -Wed29Jan15:00Thu30Jan10:00 -Thu30Jan15:00Fri31Jan10:00 -Fri31Jan15:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 2 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 3 of 4,All pages of this Speed Zone Authorisation(s) must be available on site at all times and must be produced for inspection when requested byrepresentatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and other Government Agencies.Page 4 of 4''' output4 = '''ROAD OCCUPANCY LICENCELICENCE NO : 1314814TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR022-WB-1 of 3 S-Hornsey to Quirk + EBHornsey Lane Closure-ATS-WCX-3B-134CombinedLOCATIONSubject Road:QUIRK STFrom:VICTORIA RD, ROZELLETo:GRAHAM ST, ROZELLECouncil:INNER WESTLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Detour (other roads)Closure Type:All lanes one directionClosure Lane(s):Shoulder; Median ShoulderDirection(s):WestboundLICENCE DURATIONFrom:01-Dec-2019To:01-Feb-2020LICENCE CONDITIONS1YOU MUST USE SHIFT ACTIVATION WEB ADDRESShttps://myrol.transport.nsw.gov.au TO ACTIVATE AND DEACTIVATE YOURAPPROVED ROAD OCCUPANCY LICENCE(S). (TO CHANGE TRAFFICCONTROL SIGNALS TO FLASHING YELLOW OR TO ACTIVATEPERMANENT VARIABLE MESSAGE SIGNS DIAL 1800 679 782)2THIS LICENCE IS NOT AN APPROVAL OF THE PROPONENT'S TRAFFICCONTROL PLAN. PLEASE NOTE WORKCOVER REQUIRES THATTRAFFIC CONTROL PLANS COMPLY WITH AS1742.33ALL MATTERS RELATING TO NOISE GENERATION OR OTHERENVIRONMENTAL FACTORS ON SITE ARE UNDER THE JURISDRICTIONOF THE LOCAL COUNCIL AND/OR THE ENVIRONMENTAL PROTECTIONAUTHORITY.4SHOULD THE PROPOSED WORKS INVOLVE UNDERBORING OREXCAVATION OF STATE ROAD ASSETS OR THE REMOVAL OF KERBAND GUTTER, DETAILS OF WORKS MUST BE APPROVED BY THERMS'S ASSEST MANAGEMENT BRANCH.5NOTIFICATION TO AFFECTED BUSINESSES, RESIDENTS AND OTHERSTAKEHOLDERS MUST BE UNDERTAKEN AT LEAST 5 BUSINESS DAYSPRIOR TO WORKS COMMENCING6ROAD OCCUPANCY OFFICE AT TMC WILL BE CLOSED DURING THECHRISTMAS/NEW YEAR PERIOD FROM MONDAY 23 DECEMBER 2019TO FRIDAY 3 JANUARY 2020 (INCLUSIVE).I. THE MINIMUM 10 BUSINESS DAYS PROCESSING PERIOD WILL APPLYFROM 6 JANUARY 2020 FOR ALL NEW AND EXTENSION ROADOCCUPANCY LICENCE APPLICATIONS RECEIVED DURING THESHUTDOWN PERIOD.II. ALL EXISTING ROLS THAT EXPIRE DURING THE SHUTDOWN PERIODREQUIRING EXTENSIONS MUST BE SUBMITTED TO THIS OFFICE VIAOPLINC NO LATER THAN FRIDAY 13 DECEMBER 2019.7FOR ALL WORKS IMPACTING BUS ROUTES OR STOPS, SYDNEYCOORDINATION OFFICE, TRANSPORT INTEGRATION ARE TO BECONSULTED. PLEASE CONTACT -- FRANKIE.PASSARELLI@TMC.TRANSPORT.NSW.GOV.AU8ENSURE THE APPROPRIATE HOLD POINT IS RELEASED FOR THE TCPUSED AS PART OF THIS ROL9NO WORK 23 DEC - 03 JAN DUE TO CHRISTMAS EMBARGO10ADEQUATE ADVANCE WARNING MUST BE PROVIDED TOAPPROACHING MOTORISTS.11DETOUR ROUTE MUST BE CLEARLY SIGNPOSTED.12PEDESTRIAN ACCESS MUST BE MAINTAINED AROUND THE WORKAREA IN A SAFE MANNER, COMPLYING WITH COUNCILREQUIREMENTS.13LOCAL RESIDENT ACCESS MUST BE MAINTAINED AT ALL TIMES.APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeSun01Dec20:00 -Mon02Dec04:30Mon02Dec20:00 -Tue03Dec04:30Tue03Dec22:00 -Wed04Dec04:30Wed04Dec22:00 -Thu05Dec04:30Thu05Dec22:00 -Fri06Dec04:30Fri06Dec23:00 -Sat07Dec06:00Sat07Dec23:30 -Sun08Dec07:00Sun08Dec20:00 -Mon09Dec04:30Mon09Dec20:00 -Tue10Dec04:30Tue10Dec22:00 -Wed11Dec04:30Wed11Dec22:00 -Thu12Dec04:30Thu12Dec22:00 -Fri13Dec04:30Fri13Dec23:00 -Sat14Dec06:00Sat14Dec23:30 -Sun15Dec07:00Sun15Dec20:00 -Mon16Dec04:30Mon16Dec20:00 -Tue17Dec04:30Tue17Dec22:00 -Wed18Dec04:30Wed18Dec22:00 -Thu19Dec04:30Thu19Dec22:00 -Fri20Dec04:30Fri20Dec23:00 -Sat21Dec06:00Sat21Dec23:30 -Sun22Dec07:00Sun22Dec20:00 -Mon23Dec04:30Sat04Jan23:30 -Sun05Jan07:00Sun05Jan20:00 -Mon06Jan04:30Mon06Jan20:00 -Tue07Jan04:30Tue07Jan22:00 -Wed08Jan04:30Wed08Jan22:00 -Thu09Jan04:30Thu09Jan22:00 -Fri10Jan04:30Fri10Jan23:00 -Sat11Jan06:00Sat11Jan23:30 -Sun12Jan07:00Sun12Jan20:00 -Mon13Jan04:30All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 1 of 2,ROAD OCCUPANCY LICENCELICENCE NO : 1314814TRANSPORT MANAGEMENT CENTRE (TMC)Phone: Monday To Friday 8.30 AM - 4.30 PMTo activate and deactivate your approved work shift(s) on your Road Occupancy Licence, please visit: myrol.transport.nsw.gov.au. This licenceis for the occupation of the road space only. If you are unable to access myrol.transport.nsw.gov.au, please call TMC on 1800 679 782. Forfurther assistance, please refer to the proponent's user manual here: myrol.transport.nsw.gov.au/help.pdfNON DEVELOPMENT - NOT KNOWNProject:WestConnex 3BThis Activity :VR022-WB-1 of 3 S-Hornsey to Quirk + EBHornsey Lane Closure-ATS-WCX-3B-134CombinedLOCATIONSubject Road:QUIRK STFrom:VICTORIA RD, ROZELLETo:GRAHAM ST, ROZELLECouncil:INNER WESTLICENSEEOrganisation:John HollandRef No:Name:Ismat ZahraPhone:0419919046ONSITE CONTACTName:Mitchell EversonPhone:0428877584TRAFFIC MANAGEMENTFlow Management:Detour (other roads)Closure Type:All lanes one directionClosure Lane(s):Shoulder; Median ShoulderDirection(s):WestboundLICENCE DURATIONFrom:01-Dec-2019To:01-Feb-2020APPROVED DATES &amp; TIMESFrom ShiftTo ShiftFromDMTime -ToDMTimeMon13Jan20:00 -Tue14Jan04:30Tue14Jan22:00 -Wed15Jan04:30Wed15Jan22:00 -Thu16Jan04:30Thu16Jan22:00 -Fri17Jan04:30Fri17Jan23:00 -Sat18Jan06:00Sat18Jan23:30 -Sun19Jan07:00Sun19Jan20:00 -Mon20Jan04:30Mon20Jan20:00 -Tue21Jan04:30Tue21Jan22:00 -Wed22Jan04:30Wed22Jan22:00 -Thu23Jan04:30Thu23Jan22:00 -Fri24Jan04:30Fri24Jan23:00 -Sat25Jan06:00Sat25Jan23:30 -Sun26Jan07:00Sun26Jan20:00 -Mon27Jan04:30Mon27Jan20:00 -Tue28Jan04:30Tue28Jan22:00 -Wed29Jan04:30Wed29Jan22:00 -Thu30Jan04:30Thu30Jan22:00 -Fri31Jan04:30Fri31Jan23:00 -Sat01Feb06:00All pages of this Road Occupancy Licence and associated Speed Zone Authorisation(s) must be available on site at all times and must beproduced for inspection when requested by representatives of NSW Police, Roads &amp; Maritimes Services, Transport for NSW and otherGovernment Agencies.Page 2 of 2''' </code></pre> <p>See below for whole code:</p> <pre><code>import os import glob import pandas as pd import re import numpy as np import PyPDF2 import sys import logging from datetime import datetime from openpyxl import Workbook logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') '''Purge duplicates by finding copies and download duplicates''' file_path = 'C:/Users/ipeter/Desktop/Webdriverdownloads' dupfiles = glob.glob(os.path.join(file_path,'*(1).pdf')) copfiles = glob.glob(os.path.join(file_path,'*Copy.pdf')) copfiles.extend(dupfiles) for file in copfiles: os.remove(file) '''ROLS only''' read_files = glob.glob(os.path.join(file_path,'ROL_*.pdf')) '''Regex Compile objects for looping through string''' REGEXstart = re.compile(r'DURATIONFrom:(\d\d-\w\w\w-\d\d\d\d)To:') REGEXfinish = re.compile(r'To:(\d\d-\w\w\w-\d\d\d\d)LICENCE') REGEXrolnum = re.compile(r'LICENCELICENCE NO : (\d{7})') REGEXroad = re.compile(r'Subject Road:([ -~]*?)From') REGEXfrom = re.compile(r'From:([ -~]*?)To:') REGEXTo = re.compile(r'To:([ -~]*?)Council:') REGEXFlow = re.compile(r'Flow Management:([ -~]*?)Closure Type:') REGEXdirection = re.compile(r'Direction\(s\):(\w+[ \w+]*?)LICENCE') REGEXyear = re.compile(r'DURATIONFrom:\d\d-\w\w\w-(\d\d\d\d)To:') REGEXclosureT = re.compile(r'Closure Type:([ -~]*?)Closure Lane') REGEXclosureL = re.compile(r'Closure Lane\(s\):([ -~]*?)Direction') '''ROL Shift times''' REGEXshiftstartday = re.compile(r'(\w{3})\d{2}\w{3}\d{2}:\d{2}\s-') REGEXshiftfinishday = re.compile(r'\s-(\w{3})\d{2}\w{3}\d{2}:\d{2}') REGEXshiftstartdate = re.compile(r'\w{3}(\d{2}\w{3})\d{2}:\d{2}\s-') REGEXshiftfinishdate = re.compile(r'\s-\w{3}(\d{2}\w{3})\d{2}:\d{2}') REGEXshiftstarttime = re.compile(r'\w{3}\d{2}\w{3}(\d{2}:\d{2})\s-') REGEXshiftfinishtime = re.compile(r'\s-\w{3}\d{2}\w{3}(\d{2}:\d{2})') '''This generator is workaround for pandas dataframe of equal length columns''' def Growinglist(selection, longlength): while len(selection)&lt;longlength: selection.append(selection[0]) df1 = pd.DataFrame() '''NESTED LOOP = Read all pdf files in folder. Then read all pages. Return list''' #How to create generator for these loops using re.compile objects define above? for files in read_files: pdfReader = PyPDF2.PdfFileReader(files) count = pdfReader.numPages logging.debug(read_files.index(files)) output = [] for i in range(count): page = pdfReader.getPage(i) output.append(page.extractText()) output = ','.join(output)#joins each element into single string rolnum = [REGEXrolnum.search(output)[1]] start = [REGEXstart.search(output)[1]]#LICENCE START DATE finish = [REGEXfinish.search(output)[1]]#LICENCE FINISH DATE road = [REGEXroad.search(output)[1]]#SUBJECT ROAD From = [REGEXfrom.search(output)[1]]#FROM ROAD To = [REGEXTo.search(output)[1]]#TO ROAD Flow = [REGEXFlow.search(output)[1]] direction = [REGEXdirection.search(output)[1]] closureT = [REGEXclosureT.search(output)[1]] closureL = [REGEXclosureL.search(output)[1]] year = REGEXyear.search(output)[1] shiftstartday = REGEXshiftstartday.findall(output)#SHIFT START DAY shiftfinishday = REGEXshiftfinishday.findall(output)#SHIFT FINISH DAY shiftstartdate = REGEXshiftstartdate.findall(output)#SHIFT START DATE shiftfinishdate = REGEXshiftfinishdate.findall(output)#SHIFT FINISH DATE shiftstarttime = REGEXshiftstarttime.findall(output)#SHIFT START TIME shiftfinishtime = REGEXshiftfinishtime.findall(output)#SHIFT FINISH TIME shiftstartdate = [item + year for item in shiftstartdate] shiftfinishdate = [item + year for item in shiftfinishdate] '''Create list to compare lengths of each. Find longest and match length with others''' ##I know this is very inefficient. How to improve? lists = [rolnum,start,finish,road,From,To,direction,shiftstartday,shiftfinishday,shiftstartdate,shiftfinishdate,shiftstarttime,shiftfinishtime] longlength = len(max(lists, key=len)) Growinglist(rolnum,longlength) Growinglist(start,longlength) Growinglist(finish,longlength) Growinglist(road,longlength) Growinglist(From,longlength) Growinglist(To,longlength) Growinglist(Flow,longlength) Growinglist(closureT,longlength) Growinglist(closureL,longlength) Growinglist(direction,longlength) print('\n\n', 'Stripped pdf from ROL: ' + rolnum[0]) '''Append each pdf scraped data onto existing dataframe df1''' d = {'ROL #' : rolnum, 'SUBJECT RD' : road,'FROM RD' : From,'TO RD' : To,'FLOW MANAGEMENT':Flow,'CLOSURE TYPE' : closureT,'CLOSURE LANE': closureL, 'LICENCE START DATE' : start, 'LICENCE FINISH DATE' : finish, 'SHIFT START DATE' : shiftstartdate, 'SHIFT FINISH DATE' : shiftfinishdate, 'SHIFT START DAY' : shiftstartday, 'SHIFT FINISH DAY' : shiftfinishday,'SHIFT START TIME' : shiftstarttime, 'SHIFT FINISH TIME' : shiftfinishtime,'DIRECTION' : direction} df = pd.DataFrame(data = d) df1 = df1.append(df, ignore_index=True) df1.to_excel('C:/Users/ipeter/Desktop/Webdriverdownloads/ROL data (NEMO).xlsx', sheet_name='APPROVED ROL') print('\n', 'NEMO program was executed: ' + str(datetime.now())) </code></pre> <h2>Problems</h2> <ul> <li>All lists must be of equal length. I'm not familiar with tuples so have grouped regex objects as lists. This makes easier to input to Dataframe using <code>Growing()</code> generator too. </li> <li>Can I iterate regex objects over pdf files using a generator? Current for loop is clunky.</li> <li>These regex search methods are positional i.e they are based on pdf format not changing and for each <code>output</code> string and position of elements within the string. I know this isn't recommended but works for my situation.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:33:57.123", "Id": "467220", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T10:22:21.457", "Id": "238229", "Score": "1", "Tags": [ "python", "generator" ], "Title": "Scraping pdf files with PyPDF2 and appending regex lists into Dataframe" }
238229
<p>I made the following regular expression for parsing ngnix log</p> <pre><code>log_1 = "1.169.137.128 - - [29/jun/2017:07:10:50 +0300] "GET /api/v2/banner/1717161 http/1.1" 200 2116 "-" "Slotovod" "-" "1498709450-2118016444-4709-10027411" "712e90144abee9" 0.199" </code></pre> <p>My test cases (<a href="https://regex101.com/r/Eyhxod/1" rel="nofollow noreferrer">https://regex101.com/r/Eyhxod/1</a>)</p> <pre><code>lineformat = re.compile(r"""(?P&lt;ipaddress&gt;\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(?P&lt;dateandtime&gt;\d{2}\/[a-z]{3}\/\d{4}:\d{2}:\d{2}:\d{2} (\+|\-)\d{4})\] \"GET (?P&lt;url&gt;.+?(?=\ http\/1.1")) http\/1.1" \d{3} \d+ "-" (?P&lt;http_user_agent&gt;.+?(?=\ )) "-" "(?P&lt;x_forwaded_for&gt;(.+?))" "(?P&lt;http_xb_user&gt;(.+?))" (?P&lt;request_time&gt;[+-]?([0-9]*[.])?[0-9]+)""",re.IGNORECASE) </code></pre> <p>Output:</p> <pre><code>data = re.search(lineformat, log_1) data.groupdict() {'ipaddress': '1.169.137.128', 'dateandtime': '29/jun/2017:07:10:50 +0300', 'url': '/api/v2/banner/1717161', 'http_user_agent': '"Slotovod"', 'x_forwaded_for': '1498709450-2118016444-4709-10027411', 'http_xb_user': '712e90144abee9', 'request_time': '0.199'} </code></pre> <p>I believe I should make it more robust towards edge cases and broken logs. Also I consider splitting my long expression into a smaller one. Any advices towards the best-practices are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T06:29:15.137", "Id": "467531", "Score": "1", "body": "Isn't there a commonly known Python module for parsing these log files? You are for sure not the first person in the world to try this." } ]
[ { "body": "<p>At the very least, use verbose mode so you can see the whole thing at once. Remember to explicitly include whitespace.</p>\n\n<pre><code>lineformat = re.compile(r\"\"\"\n (?P&lt;ipaddress&gt;\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s+\n -\\s+\n -\\s+\n \\[(?P&lt;dateandtime&gt;\\d{2}\\/[a-z]{3}\\/\\d{4}:\\d{2}:\\d{2}:\\d{2} (\\+|\\-)\\d{4})\\]\\s+\n \\\"GET (?P&lt;url&gt;.+?(?=\\ http\\/1.1\")) http\\/1.1\"\\s+\n \\d{3}\\s+\n \\d+\\s+\n \"-\"\\s+\n (?P&lt;http_user_agent&gt;.+?(?=\\ ))\\s+\n \"-\"\\s+\n \"(?P&lt;x_forwaded_for&gt;(.+?))\"\\s+\n \"(?P&lt;http_xb_user&gt;(.+?))\"\\s+\n (?P&lt;request_time&gt;[+-]?([0-9]*[.])?[0-9]+)\n \"\"\",\n re.IGNORECASE | re.VERBOSE)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T06:07:45.040", "Id": "238401", "ParentId": "238232", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:04:34.670", "Id": "238232", "Score": "3", "Tags": [ "python", "regex", "nginx" ], "Title": "Regex for nginx log parser" }
238232
<p>In order to learn about multithreading programming in C++, I am implementing a basic multithreaded logger.</p> <p>I use a <code>std::deque</code> to store messages inside a <code>FileLogger</code> class. Each time a thread logs a message, that message is pushed to the back of the deque.</p> <p>In a separate thread the <code>FileLogger</code> checks if there are any messages in the deque and if so writes them to file.</p> <p>Access to the deque is guarded by a mutex.</p> <p>In order to make it easy to log from anywhere, the logger is implemented as a singleton.</p> <p><strong>Is my code correct? How can it be improved?</strong></p> <pre><code>// FileLogger.h: class FileLogger { public: static void initialize(const char* filePath) { // called by main thread before any threads are spawned instance_ = new FileLogger(filePath); } static FileLogger* instance() { // called from many threads simultaneously return instance_; } void log(const std::string &amp;msg); private: FileLogger(const char* filePath); void writeToFile(); static FileLogger* instance_; std::deque&lt;std::string&gt; messages; std::mutex messagesMutex; // lock/unlock this each time messages is pushed or popped std::ofstream fout; std::thread writerThread; }; // FileLogger.cpp: FileLogger* FileLogger::instance_ = nullptr; void FileLogger::writeToFile() { for (;;) { std::string message; while (messages.empty()) { std::this_thread::sleep_for(std::chrono::nanoseconds(10)); } messagesMutex.lock(); message = messages.front(); messages.pop_front(); messagesMutex.unlock(); fout &lt;&lt; message &lt;&lt; std::endl &lt;&lt; std::flush; } } FileLogger::FileLogger(const char* filePath) { fout.open(filePath); std::thread t(&amp;FileLogger::writeToFile, this); writerThread = std::move(t); } void FileLogger::log(const std::string &amp;msg) { std::lock_guard&lt;std::mutex&gt; lg(messagesMutex); messages.push_back(msg); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:55:15.520", "Id": "467234", "Score": "1", "body": "Do you ask for improvement in terms of only multithreading ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:56:48.640", "Id": "467235", "Score": "0", "body": "My main focus is multithreading but I am grateful for any improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:24:42.527", "Id": "467302", "Score": "1", "body": "If you have new concerns, please post a new question linking back to this one for extra context. Modifying the question after answers came in tends to create a mess. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:42:48.980", "Id": "467341", "Score": "1", "body": "Hi, i am kind of a new learner. I think your code looks good but I was wondering that when do you close the file? Did std::ofstream handles that? thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:50:38.620", "Id": "467342", "Score": "0", "body": "@thehilmisu: good point. I don't. When the program exits all filehandles are released. Not really nice. Should be fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:56:56.310", "Id": "467343", "Score": "0", "body": "@Andy i think you should periodically apply your changes to the file in case of a power outage or some other failures for not losing any data." } ]
[ { "body": "<p>Just up front, your code doesn't have any blatant bugs which would prevent its use. There are a few things that you could do to improve it though:</p>\n\n<ul>\n<li>One thing that I'd try to avoid is singletons. These are effectively globals and bring with them almost all their problems. In particular, it prevents isolating code for unit tests. The alternative is that you pass a logger to the constructor of every object that needs it. This is called dependency injection, as a keyword for future research.</li>\n<li>Instead of <code>fout.open(path)</code>, you could pass the filename to the constructor of <code>fout</code> using the initializer list.</li>\n<li>Your logger isn't copyable or assignable due to its members. I'd make that explicit though.</li>\n<li>When writing, <code>std::endl</code> already flushes the stream, so the explicit <code>std::flush</code> is redundant.</li>\n<li>The biggest issue is the way your writing thread operates. In effect, it wakes up every 10ns (that's 100.000.000 times per second) and looks for work (a.k.a. polling). Firstly, I can't imagine that this fast response time is actually relevant to a logger. If you have 0.1s delay between writing to the logger and seeing the data in the file, that should be enough by far. However, that's not a solution. What you actually want there is a <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"nofollow noreferrer\">condition variable</a>, which allows you to only wake up the writer thread when actual works needs to be done.</li>\n<li>There is a comment <code>lock/unlock this each time messages is pushed or popped</code>, which is already in the right direction. What has helped me in the past is to document which mutex protects which data. It may even be a good idea to put just those parts into a separate <code>struct</code> in some cases, just to make it clearer. Also, for all other members, document who is allowed to access them. For example, <code>fout</code> doesn't require synchronization, because it is exclusively accessed by the writer thread.</li>\n<li>A minor fault, but still a fault is also that you access the queue without locking to check if it is non-empty. Since this typically only involves a simple pointer comparison (though that's implementation-defined), it will probably not cause issue. Using a condition variable as sketched below fixes this part as well.</li>\n<li>You could implement this using lock-free algorithms. This is a complete rewrite though and not \"smoothing out the rough edges\" of your current approach. Just keep that in mind as future research project perhaps.</li>\n<li>A minor flaw is that there is no way to shut down the logger. This is probably harmless, but it will probably trigger memory debuggers (leak detectors). If you decide not to implement shutdown, you don't need <code>writerThread</code> though, just call <code>t.detach()</code> after starting.</li>\n<li>If your target is C++ 17 or later, you could also use the <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\">filesystem</a> library which has a dedicated path type. I'd generally prefer that over raw <code>char*</code> string. Even without C++ 17, I'd use <code>std::string</code>, unless I have good reasons not to.</li>\n<li>Concerning pushing on the queue, consider using <code>emplace_back()</code> instead, to avoid one more copying operation.</li>\n<li>Concerning removal from the queue, there is a trick: Create a second, local queue (initially empty) and swap that with the member (holding a lock for the time of that operation, of course). Then you have all the content in a local object that you can process at leasure, without having to worry about locking. This becomes important when retrieving multiple messages at once, so that you don't repeatedly lock/unlock without need. This can lead to \"thread convoys\": Imagine one thread perpetually writing messages using <code>lock/push/unlock</code> triples, so it becomes a stream of <code>lock/push/unlock/lock/push/unlock..</code>. Now, if this thread ever gets scheduled out while it holds the lock and the writer thread is scheduled in, it will then itself run a <code>lock/pop/unlock/lock/pop/unlock..</code> stream. On the first lock, it will block until the logging thread continues. This thread will be able to write <em>one</em> message, before it is blocked by the writer thread. In other words, ownership of the mutex will pingpong between the two threads, wrecking performance. Also, this is hard to catch, because it both comes and goes spontaneously.</li>\n</ul>\n\n<p>For reference, here is a sketch of the push and pop operations using a CV:</p>\n\n<pre><code>mutex mtx;\ncondition_variable cv;\ndeque&lt;string&gt; queue;\n\nvoid push(string s) {\n unique_lock&lt;mutex&gt; lck(mtx);\n queue.push_back(s);\n lck.unlock();\n cv.notify_one();\n}\n\nstring pop() {\n unique_lock&lt;mutex&gt; lck(mtx);\n cv.wait(lck, []{ return !queue.empty();})\n string res = queue.front();\n queue.pop_front();\n return res;\n}\n</code></pre>\n\n<p>This is not much more than the examples given by <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"nofollow noreferrer\">cppreference</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:23:49.323", "Id": "467242", "Score": "0", "body": "How do can you wait and wake up on notification in lock-free case? In C++20 atomic variables have wait and notify. One can make fake lock `std::condition_variable_any` but I heard its implementations tend to be dubius." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:06:00.863", "Id": "467249", "Score": "0", "body": "Thank you uli! Regarding your first point; when talking about unit tests do you have in mind a dummy logger that does nothing? Maybe I should create a ILogger interface and a LoggerFactory? The LoggerFactory then has a getLogger() method. The LoggerFactory can then be initialized to return eg. DummyLogger in the case of an unit test or FileLogger otherwise. This seems in tune with the maxime: \"program to interfaces not implementations\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T17:25:37.133", "Id": "467262", "Score": "1", "body": "In unit tests, you could also use a logger that makes sure that certain things are logged, not just one that does nothing. Both loggers could share a common interface (baseclass). Using a factory, I'd say no, because you just replace one dependency with another. A factory is useful when you need to create different types of objects based on a parameter at runtime, but here it's just one and its type is fixed. Don't overcomplicate unnecessarily." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T21:32:12.520", "Id": "467280", "Score": "2", "body": "Is it not worrying that the check messages.empty() is being done without a lock? by the time you check and the time you execute another thread could have finished all the work. @url regarding your last point, did you have in mind a more complext situation? How is it different than what is it doing now, just copying the variable to a local and then releasing the lock?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T07:39:45.293", "Id": "467298", "Score": "1", "body": "@Ant: regarding messages.empty() being done without a lock: I think this is an important point. I find it difficult to understand exactly how this can go wrong. If empty() returns false and the message has not been completely pushed into the deque that would cause a crash when I call front(). Not sure if a push_back would increase size before actually inserting the element. Anyway I think it is probably safest to put the empty() inside a mutex lock/unlock pair?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:52:35.337", "Id": "467316", "Score": "1", "body": "I just slapped my forehead, @Ant, because you're right. **Any** access to a shared, mutable resource should happen with a lock, unless there's a good reason not to. I guess that I missed this because I had the change in mind that uses a condition variable, which basically guides you into the right direction already and resolves this error as well." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:00:58.237", "Id": "238239", "ParentId": "238234", "Score": "11" } }, { "body": "<p>It seems your code will work expected. I am sure that there are other improvements for multithreading but I will just suggest some improvements in terms of readability and usability. I hesitated to share but maybe it could be beneficial for you or others.</p>\n\n<ul>\n<li><p>Firstly, intuitive expectation of most of developers is using <code>operator &lt;&lt;</code> to stream out things.</p></li>\n<li><p>Second, actually singleton is detail of your implementation. It might be hidden in a <code>class</code>. It also provides you to change the implementation later without breaking backward compatibility.</p></li>\n</ul>\n\n<p>So it is possible to support with the help of <a href=\"https://en.cppreference.com/w/cpp/io/basic_stringstream\" rel=\"nofollow noreferrer\">std::stringstream</a> combined with <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"nofollow noreferrer\">RAII</a> technique.</p>\n\n<p>Possible implementation :</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n#include &lt;functional&gt;\n\nstruct singleton_impl\n{\n\n static singleton_impl&amp; instance()\n {\n static singleton_impl impl;\n return impl;\n }\n\n void log( const std::string&amp; l )\n {\n std::cout &lt;&lt; l &lt;&lt; std::endl;\n }\n};\n\ntemplate&lt;typename Fn&gt;\nclass message\n{\n public:\n\n message( Fn&amp;&amp; fn ) : m_f { std::forward&lt;Fn&gt;( fn ) } \n { }\n\n ~message() {\n // Push to message queue\n m_f( m_ss.str() );\n }\n\n template&lt;typename T&gt;\n message&amp; operator&lt;&lt;( const T&amp; msg ) \n {\n m_ss &lt;&lt; msg;\n return *this;\n }\n\n private:\n\n std::stringstream m_ss;\n Fn m_f;\n};\n\nstruct logger\n{\n\n auto operator()() {\n return message { std::bind( static_cast&lt; void(logger::*)( const std::string&amp; )&gt;( &amp;logger::log ) , this , std::placeholders::_1 ) };\n }\n\n void log( const std::string&amp; l )\n {\n // std::cout &lt;&lt; l &lt;&lt; std::endl;\n singleton_impl::instance().log( l );\n }\n};\n\nint main()\n{\n logger logger;\n\n logger() &lt;&lt; \"Hello, world ! a number : \" &lt;&lt; 15 &lt;&lt; \". Supports 'operator &lt;&lt;'\";\n logger.log( \"another way\" );\n\n\n {\n logger() &lt;&lt; \"outputs at end of the scope.\";\n }\n\n auto output = logger();\n output &lt;&lt; \"Output over object.\";\n output &lt;&lt; \"Appended to the previous text.\";\n\n return 0;\n}\n</code></pre>\n\n<blockquote>\n <p>Hello, world ! a number : 15. Supports 'operator &lt;&lt;'<br>\n another way<br>\n outputs at end of the scope.<br>\n Output over object.Appended to the previous text</p>\n</blockquote>\n\n<p><a href=\"https://onlinegdb.com/ryCsiDsVU\" rel=\"nofollow noreferrer\">run online</a></p>\n\n<ul>\n<li><p>Another improvement could be making it extendable with the help of metaprogramming. I won't implement but the interface could be like this.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstruct with_thread_id {};\nstruct with_timestamp {};\nstruct with_this_token {\n with_this_token( const std::string&amp; t ) : m_token { t } {}\n\n private:\n std::string m_token;\n};\n// And many more\n\ntemplate&lt; typename... Features &gt;\nclass logger_impl {\n // Implement somehow\n};\n\nusing logger = logger_impl&lt; with_thread_id , with_timestamp &gt;;\n\nint main()\n{\n logger l;\n\n l() &lt;&lt; \"There will be `thread_id` and `timestamp` before this text.\";\n\n return 0;\n}\n</code></pre></li>\n<li><p>Another little performance improvement in your code. Use <a href=\"https://en.cppreference.com/w/cpp/language/move_assignment\" rel=\"nofollow noreferrer\">move assignment</a> instead of <a href=\"https://en.cppreference.com/w/cpp/language/copy_assignment\" rel=\"nofollow noreferrer\">copy assignment</a> when it is possible. </p>\n\n<pre><code> // message = messages.front();\n message = std::move( messages.front() );\n</code></pre></li>\n<li><p>For sake of better readability, <a href=\"https://en.cppreference.com/w/cpp/thread/scoped_lock\" rel=\"nofollow noreferrer\">std::scoped_lock</a> could be used instead of lock()/unlock() pair.</p>\n\n<pre><code>/* messagesMutex.lock();\nmessage = messages.front();\nmessages.pop_front();\nmessagesMutex.unlock(); */\n\n{\n std::scoped_lock lock { messagesMutex };\n message = messages.front();\n messages.pop_front();\n} \n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T05:44:34.280", "Id": "238287", "ParentId": "238234", "Score": "4" } }, { "body": "<p>Your singleton initialization pattern is unsafe for a logger that you may want to use from other static initializers (that have undefined initialization order) because you cannot guarantee that the initialize function has been executed.</p>\n\n<p>Typically you would use C++11 magic statics for this, but then you can't give a filename to it. Providing a filename as user input is always going to be a problem if you need to log from static initializes that run before <code>main()</code>. Yes, you could read the log filename from a static configuration file, but you might want to log errors from the config parse itself, and at that point the log path could be static as well. In this particular case, I recommend picking a static or generated file path for your logs.</p>\n\n<p>Next up, you will basically keep a whole CPU core busy with polling every 10ns. Use <code>std::condition_variable</code> to sleep the thread until it had logs to write.</p>\n\n<p>Finally your logging thread never exits; this is a problem depending on the platform: the behaviour of the process when you return from <code>main()</code> with active threads can differ. For example, read <em><a href=\"https://devblogs.microsoft.com/oldnewthing/20100827-00/?p=13023\" rel=\"nofollow noreferrer\">If you return from the main thread, does the process exit?</a></em> by Raymond Chen. Your logger class should have a destructor that stops the thread's loop, joins the thread and deletes the singleton instance (not necessary if you use magic statics).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:45:39.930", "Id": "238291", "ParentId": "238234", "Score": "5" } } ]
{ "AcceptedAnswerId": "238239", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T11:36:33.067", "Id": "238234", "Score": "5", "Tags": [ "c++", "multithreading" ], "Title": "A simple multithreaded FileLogger in C++" }
238234
<p>I have an array of values. (<code>cols</code>)</p> <p>I want to find out which index of <code>cols</code> contains the value closest to the mean of <code>cols</code>.</p> <p>Can I combine these functions so that I'm not repeating loops?</p> <pre><code>let mean = cols.reduce((prev, curr) =&gt; prev + curr) / cols.length; let closest = cols.reduce((prev, curr) =&gt; (curr - mean) &lt; (prev - mean) ? curr : prev); let meanCol = cols.indexOf(closest); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:25:32.810", "Id": "467237", "Score": "0", "body": "Seems like you are calculating the average, not the mean; https://byjus.com/maths/difference-between-average-and-mean/ If you wanted to actually find closest to mean, then you need only 1 loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:47:34.230", "Id": "467244", "Score": "0", "body": "Hmmm... Interesting, I actually came across that link before, but because it says multiple times that 'they can be used interchangeably' I took that to mean they're the same thing!\n\nAlso, I keep finding conflicting answers, such as this one saying that I am indeed doing mean: https://www.purplemath.com/modules/meanmode.htm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T16:21:56.333", "Id": "467256", "Score": "2", "body": "Wikipedia agrees with you, so case closed for me." } ]
[ { "body": "<p>You can remove the last line searching for the index since you can get the index in the reduce method.</p>\n\n<p>Btw, you forgot to add <code>Math.abs</code> to deal with positive value when comparing.</p>\n\n<p>Demo:</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 cols = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n\nconst mean = cols.reduce((prev, curr) =&gt; prev + curr, 0) / cols.length;\n\nconst { value, index } = cols.reduce((prev, curr, i) =&gt; {\n // You have deal in absolute \n if (Math.abs(curr - mean) &lt; Math.abs(prev.value - mean)) {\n return { value: curr, index: i }\n } else {\n return prev\n }\n}, { value: cols[0], index: 0 });\n\nconsole.log({ mean, value, index })</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T09:11:56.890", "Id": "238293", "ParentId": "238238", "Score": "3" } }, { "body": "<p>A short review;</p>\n\n<ul>\n<li>You can't reduce an empty array, I would check for empty arrays and decide how to deal with them</li>\n<li>Have a think about <code>let</code> vs. <code>const</code>, <code>mean</code> and <code>closest</code> should probably be <code>const</code></li>\n<li>You want that code in a properly named function</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T09:05:27.157", "Id": "467689", "Score": "0", "body": "Thank you. Always appreciate the details" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:42:11.727", "Id": "238314", "ParentId": "238238", "Score": "2" } } ]
{ "AcceptedAnswerId": "238293", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T12:44:51.657", "Id": "238238", "Score": "2", "Tags": [ "javascript", "algorithm" ], "Title": "An array of values. looping many times to calculate mean, closest matching array value, and then finding its index" }
238238
<p>This is a continuation of <a href="https://codereview.stackexchange.com/questions/237693/generating-png-barcodes-from-a-csv">my earlier question,</a> now updated to use a basic GUI. This is my first time using tkinter so I suspect there are a fair few things I'm missing! I've also added the ability to generate a single barcode without having to first save it in a CSV. I'm specifically interested in feedback on how I have implemented the GUI, since that's the bit I'm least confident about, but comments on anything else are very welcome too!</p> <pre class="lang-py prettyprint-override"><code>import csv import barcode from barcode.writer import ImageWriter from pathlib import Path from tkinter import * from tkinter import messagebox from tkinter import filedialog from tkinter import ttk FORBIDDEN_CHARS = str.maketrans({char: "" for char in ':;&lt;&gt;\'\"\\/?*|.'}) def remove_forbidden(string_in: str) -&gt; str: """Removes characters forbidden from windows file names from a string""" return string_in.translate(FORBIDDEN_CHARS) def get_code_png(isbn: str) -&gt; barcode.ean.EuropeanArticleNumber13: """Creates a barcode, given an ISBN""" isbn13 = barcode.get_barcode_class('ean13') return isbn13(isbn, writer=ImageWriter()) def save_code_png(isbn: str, title: str, save_folder_path: Path): """Saves one PNG barcode in a given folder""" code = get_code_png(isbn) code.save(save_folder_path.joinpath(isbn + " " + remove_forbidden(title))) def codes_from_csv(list_path: Path, save_folder_path: Path): """Creates PNG Barcodes from a CSV, placing them in a given folder""" with open(list_path, newline='') as csvfile: for row in csv.reader(csvfile, dialect='excel'): save_code_png(row[0], row[1], save_folder_path) def gui(): """Allows access to functions through a GUI""" def submit_lone(): """Creates a single barcode from a button""" try: save_code_png(txt_isbn_lone.get(), txt_title_lone.get(), Path(txt_save_path_lone.get())) except: messagebox.showerror('Error', 'Unexpected error:', sys.exc_info()[0]) else: messagebox.showinfo('Success!', 'Code Created') def submit_csv(): """Creates barcodes from a CSV from a button""" try: codes_from_csv(Path(txt_csv_path.get()), Path(txt_save_path_csv.get())) except: messagebox.showerror('Error', 'Unexpected error:', sys.exc_info()[0]) else: messagebox.showinfo('Success!', 'Codes Created') def save_path(txt_field: Entry): """Finds a folder and saves the path in a tkinter Entry widget""" txt_field.delete(0, END) txt_field.insert(0, filedialog.askdirectory()) def csv_path(): """Finds a csv file and saves the path in a tkinter Entry widget""" files = (("Comma Separated Variable", "*.csv"), ("All Files", "*.*")) txt_csv_path.delete(0, END) txt_csv_path.insert(0, filedialog.askopenfilename(filetypes=(files))) # Setting up the window window = Tk() window.geometry("400x180") window.title("Book Barcodes") tab_control = ttk.Notebook(window) lone = ttk.Frame(tab_control) csv = ttk.Frame(tab_control) tab_control.add(lone, text='Single Barcode') tab_control.add(csv, text='List from CSV') tab_control.pack(expand=1, fill='both') # Tab 1: Lone Code lbl_isbn_lone = Label(lone, text="ISBN:") lbl_isbn_lone.grid(column=0, row=0, ipadx=5, pady=5) txt_isbn_lone = Entry(lone, width=30) txt_isbn_lone.grid(column=1, row=0, ipadx=5, pady=5) lbl_title_lone = Label(lone, text="Title:") lbl_title_lone.grid(column=0, row=1, ipadx=5, pady=5) txt_title_lone = Entry(lone, width=30) txt_title_lone.grid(column=1, row=1, ipadx=5, pady=5) lbl_save_path_lone = Label(lone, text="Save Folder:") lbl_save_path_lone.grid(column=0, row=2, ipadx=5, pady=5) txt_save_path_lone = Entry(lone, width=30) txt_save_path_lone.grid(column=1, row=2, ipadx=5, pady=5) btn_save_path_lone = Button(lone, text="Find Folder", command=lambda: save_path(txt_save_path_lone)) btn_save_path_lone.grid(column=2, row=2, ipadx=5, pady=5) btn_submit_lone = Button(lone, text="Generate Code", command=submit_lone) btn_submit_lone.grid(column=2, row=3, ipadx=5, pady=5) # Tab 2: Codes from CSV instructions = Label(csv, text="""Please select a CSV file with ISBNs in the first column and titles in the second.""") instructions.grid(column=0, row=0, columnspan=3, ipadx=5, pady=5) lbl_csv_path = Label(csv, text="CSV Location:") lbl_csv_path.grid(column=0, row=1, ipadx=5, pady=5) txt_csv_path = Entry(csv, width=30) txt_csv_path.grid(column=1, row=1, ipadx=5, pady=5) btn_list_csv = Button(csv, text="Find File", command=csv_path) btn_list_csv.grid(column=2, row=1, ipadx=5, pady=5) lbl_save_path_csv = Label(csv, text="Save Folder:") lbl_save_path_csv.grid(column=0, row=2, ipadx=5, pady=5) txt_save_path_csv = Entry(csv, width=30) txt_save_path_csv.grid(column=1, row=2, ipadx=5, pady=5) btn_save_path_csv = Button(csv, text="Find Folder", command=lambda: save_path(txt_save_path_csv)) btn_save_path_csv.grid(column=2, row=2, ipadx=5, pady=5) btn_submit_csv = Button(csv, text="Generate Codes", command=submit_csv) btn_submit_csv.grid(column=2, row=3, ipadx=5, pady=5) window.mainloop() if __name__ == "__main__": gui() </code></pre>
[]
[ { "body": "<h2>Don't use wildcard imports</h2>\n\n<p>Instead of <code>from tkinter import *</code>, use <code>import tkinter as tk</code>. Then, wherever you reference a tkinter class or value, prefix it with <code>tk.</code> (eg: <code>tk.Label</code>, tk.Button`, etc).</p>\n\n<p>This makes your code easier to understand, and helps keep the number of objects in the global namespace low. Plus, it keeps it consistent with <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> guidelines. </p>\n\n<h2>Move the GUI code to a class</h2>\n\n<p>Moving the GUI code to a class helps organize your code. It makes it clear which parts of your code are related to the GUI and which aren't. An example of how to do this can be found on stackoverflow at this question: <a href=\"https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application\">Best way to structure a tkinter application?</a></p>\n\n<h2>Separate widget creation from widget layout</h2>\n\n<p>I consider the pattern where you create a widget, call grid, create a widget, call grid, ... to be an antipattern. It makes it difficult to visualize the layout and makes it more difficult to change the layout. I find that the layout code can change frequently during development as you add new widgets or improve the layout.</p>\n\n<p>For example, instead of this:</p>\n\n<pre><code>lbl_isbn_lone = Label(lone, text=\"ISBN:\")\nlbl_isbn_lone.grid(column=0, row=0, ipadx=5, pady=5)\ntxt_isbn_lone = Entry(lone, width=30)\ntxt_isbn_lone.grid(column=1, row=0, ipadx=5, pady=5)\nlbl_title_lone = Label(lone, text=\"Title:\")\nlbl_title_lone.grid(column=0, row=1, ipadx=5, pady=5)\ntxt_title_lone = Entry(lone, width=30)\ntxt_title_lone.grid(column=1, row=1, ipadx=5, pady=5)\n...\n</code></pre>\n\n<p>... do it like this:</p>\n\n<pre><code>lbl_isbn_lone = Label(lone, text=\"ISBN:\")\ntxt_isbn_lone = Entry(lone, width=30)\nlbl_title_lone = Label(lone, text=\"Title:\")\ntxt_title_lone = Entry(lone, width=30)\n...\nlbl_isbn_lone.grid(column=0, row=0, ipadx=5, pady=5)\ntxt_isbn_lone.grid(column=1, row=0, ipadx=5, pady=5)\nlbl_title_lone.grid(column=0, row=1, ipadx=5, pady=5)\ntxt_title_lone.grid(column=1, row=1, ipadx=5, pady=5)\n</code></pre>\n\n<h2>Use more whitespace</h2>\n\n<p>Right now you have a giant wall of code for creating widgets and laying them out. There's no way to tell if there's any sort of organization to your code, it's all just one giant block of code. You have some comments, but comments alone don't do a good job of helping our eye organize what we see.</p>\n\n<p>Specifically, add a blank line before <code># Tab 1: Lone Code</code> and before <code># Tab 2: Codes from CSV</code></p>\n\n<h2>Don't make complex function calls.</h2>\n\n<p>Instead of this:</p>\n\n<pre><code>save_code_png(txt_isbn_lone.get(), txt_title_lone.get(),\n Path(txt_save_path_lone.get()))\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>isbn = txt_isbn_lone.get()\ntitle = txt_title_lone.get()\npath = Path(txt_save_path_lone.get())\n\nsave_code_png(isbn, title, path)\n</code></pre>\n\n<p>I think it makes the code easier to read, and it makes the code easier to debug since it's easier to examine the values before passing them to the function. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T22:26:05.810", "Id": "239121", "ParentId": "238240", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:03:28.337", "Id": "238240", "Score": "5", "Tags": [ "python", "python-3.x", "image", "tkinter" ], "Title": "Generating PNG barcodes through a GUI" }
238240
<p>in my jurney to learn Go, I decided to write a simple router which I called it <a href="https://github.com/smoqadam/gouter" rel="nofollow noreferrer">Gouter</a>, which I think it has most of the features in gorilla/mux but in my opinion it's easier to use. Anyway, it consists of two file, <code>router.go</code> and <code>route.go</code>. There are some concerns I have about this. First about the performance and the second is, is it good enough to use it in production or not? and the finally how can I improve it. </p> <p>Thanks</p> <p><code>router.go</code></p> <pre><code>package router import ( "context" "net/http" ) type key int const ( contextKey key = iota varsKey ) type Router struct { // Routes stores a collection of Route struct Routes []Route // ctx is an interface type will be accessible from http.request ctx interface{} } // NewRouter return a new instance of Router func NewRouter() *Router { return &amp;Router{} } // GET register a GET request func (r *Router) GET(path string, h http.HandlerFunc) *Route { return r.AddRoute(path, http.MethodGet, h) } // POST register a POST request func (r *Router) POST(path string, h http.HandlerFunc) *Route { return r.AddRoute(path, http.MethodPost, h) } // PUT register a PUT request func (r *Router) PUT(path string, h http.HandlerFunc) *Route { return r.AddRoute(path, http.MethodPut, h) } // PATCH register a PATCH request func (r *Router) PATCH(path string, h http.HandlerFunc) *Route { return r.AddRoute(path, http.MethodPatch, h) } // DELETE register a DELETE request func (r *Router) DELETE(path string, h http.HandlerFunc) *Route { return r.AddRoute(path, http.MethodDelete, h) } // AddRoute create a new Route and append it to Routes slice func (r *Router) AddRoute(path string, method string, h http.HandlerFunc) *Route { route := NewRoute(path, method, h) r.Routes = append(r.Routes, route) return &amp;route } // With send an interface along side the http.request. // It is accessible with router.Context() function func (r *Router) With(i interface{}) *Router { r.ctx = i return r } // ServeHTTP implement http.handler func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { ctx := context.WithValue(req.Context(), contextKey, r.ctx) req = req.WithContext(ctx) var match *Route var h http.Handler for _, route := range r.Routes { if route.Match(req) { vars := route.extractVars(req) ctx := context.WithValue(req.Context(), varsKey, vars) req = req.WithContext(ctx) match = &amp;route break } } if match != nil &amp;&amp; match.method != req.Method { h = &amp;MethodNotAllowed{} } if h == nil &amp;&amp; match != nil { h = match.dispatch() } if match == nil || h == nil { h = http.NotFoundHandler() } h.ServeHTTP(w, req) } // Vars return a map of variables defined on the route. func Vars(req *http.Request) map[string]string { if v := req.Context().Value(varsKey); v != nil { return v.(map[string]string) } return nil } func Context(req *http.Request) interface{} { if v := req.Context().Value(contextKey); v != nil { return v } return nil } </code></pre> <p>and the <code>route.go</code>:</p> <pre><code>package router import ( "fmt" "net/http" "regexp" "strings" ) type Middleware func(handler http.Handler) http.Handler type Route struct { path string name string handler http.Handler method string mw []Middleware where map[string]string vars map[string]string } // NewRoute create a new route func NewRoute(path string, method string, handler http.HandlerFunc) Route { return Route{ path: path, handler: handler, method: method, vars: make(map[string]string), where: make(map[string]string), } } // Name assign a name for the route func (r *Route) Name(s string) *Route { r.name = s return r } // Match return true if the requested path would match with the current route path func (r *Route) Match(req *http.Request) bool { regex := regexp.MustCompile(`{([^}]*)}`) matches := regex.FindAllStringSubmatch(r.path, -1) p := r.path for _, v := range matches { s := fmt.Sprintf("{%s}", v[1]) p = strings.Replace(p, s, r.where[v[1]], -1) } regex, err := regexp.Compile(p) if err != nil { return false } matches = regex.FindAllStringSubmatch(req.URL.Path, -1) for _, match := range matches { if regex.Match([]byte(match[0])) { return true } } return false } func (r *Route) clear(s string) string { s = strings.Replace(s, "{", "", -1) s = strings.Replace(s, "}", "", -1) return s } // Where define a regex pattern for the variables in the route path func (r *Route) Where(key string, pattern string) *Route { r.where[key] = fmt.Sprintf("(%s)", pattern) return r } // Middleware register a collection of middleware functions and sort them func (r *Route) Middleware(mw ...Middleware) *Route { r.mw = mw //TODO: Fix this for i := len(r.mw)/2 - 1; i &gt;= 0; i-- { opp := len(r.mw) - 1 - i r.mw[i], r.mw[opp] = r.mw[opp], r.mw[i] } return r } // extractVars parse the requested URL and return key/value pair of // variables defined in the route path. func (r *Route) extractVars(req *http.Request) map[string]string { url := strings.Split(req.URL.Path, "/") path := strings.Split(r.clear(r.path), "/") vars := make(map[string]string) for i := 0; i &lt; len(url); i++ { if _, ok := r.where[path[i]]; ok { vars[path[i]] = url[i] } } return vars } // dispatch run route middleswares if any then run the route handler func (r *Route) dispatch() http.Handler { for _, m := range r.mw { r.handler = m(r.handler) } return r.handler } </code></pre> <h2>How to use it:</h2> <pre><code>func main() { r := router.NewRouter() r.GET("/user/{user}", userHandler). Name("index"). Where("user", "[a-z0-9]+"). Middleware(mid1) http.ListenAndServe(":3000", r) } func userHandler(w http.ResponseWriter, r *http.Request) { vars := router.Vars(r) fmt.Fprintf(w, "hello, %s!", vars["user"]) } func mid1(next http.Handler) http.Handler { return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){ fmt.Println("from middleware 1") next.ServeHTTP(w, r) // call another middleware or the final handler }); } </code></pre>
[]
[ { "body": "<p>You write:</p>\n\n<pre><code>func (r *Route) Match(req *http.Request) bool {\n regex := regexp.MustCompile(`{([^}]*)}`)\n // ...\n}\n</code></pre>\n\n<p>Therefore, we would expect your performance to be poor.</p>\n\n<p>See <a href=\"https://codereview.stackexchange.com/a/236196/13970\">https://codereview.stackexchange.com/a/236196/13970</a></p>\n\n<p>What performance testing have you done? Where are your benchmarks?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T03:57:01.813", "Id": "467294", "Score": "0", "body": "Thanks for the reply. I haven't done any benchmark but I think the regex in Go is slow and it's not specific to `MustCompile` function. right? Do you have any suggestion to fix it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:57:08.587", "Id": "467391", "Score": "0", "body": "@SaeedM.: In my answer I gave you a link to an earlier answer which explained the problem and how to solve it by moving a line." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:53:42.000", "Id": "238245", "ParentId": "238242", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:07:22.313", "Id": "238242", "Score": "-1", "Tags": [ "go", "http", "url-routing" ], "Title": "http router written in Golang" }
238242
<p><strong>Code explained</strong></p> <p>I wrote a few identical functions for each table to filter them based on the user input typed in the input fields using jQuery. After filtering it counts the rows that are left visible.</p> <p>My code is a bit flawed because I have one function for each selector or class, which is messy and can definitely be improved but after countless hours of investigating I'm exhausted.</p> <p><em>I currently got a frontpage with overview of all the tables including the input fields; here's an image for of the relevant DOM structure for the frontpage.</em> <a href="https://i.stack.imgur.com/xDMZ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDMZ7.png" alt="DOM Frontpage"></a></p> <p><strong>What I'd like to achieve</strong></p> <p>A more efficient use of DOM classes/selectors and simplify the use of my input functions, taking full advantage of switching and identifying which input selectors that is in use and yet filter out the right individual table.</p> <p><strong>Code I've tried to improve</strong></p> <p>jQuery:</p> <p><em>Each function has it's comment explaining where and what it does.</em></p> <pre><code>//jQuery search filtering $(document).ready(function(){ //count each table BEFORE user input var rowCount_master = $('.table_data tr:visible:not(:has(th))').length; $('#row_count_master').html(rowCount_master); var rowCount_utlan = $('#table_data_utlan tr:visible:not(:has(th))').length; $('#row_count_utlan').html(rowCount_utlan); var rowCount_totaloversikt = $('#table_data_totaloversikt tr:visible:not(:has(th))').length; $('#row_count_totaloversikt').html(rowCount_totaloversikt); var rowCount_midlansatt = $('#table_data_midlansatt tr:visible:not(:has(th))').length; $('#row_count_midlansatt').html(rowCount_midlansatt); var rowCount_table = $('.table_data tr:visible:not(:has(th))').length; $('#row_count').html(rowCount_table); //frontpage only - master table search, search filter in ALL tables $("#table_search_master").on("keyup", function() { var value_master = $(this).val().toLowerCase(); $(".table_data tr:not(:has(th))").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value_master) &gt; -1) }); //counts number of table rows var rowCount_master = $('.table_data tr:visible:not(:has(th))').length; $('#row_count_master').html(rowCount_master); if (rowCount_master == 0) { $('#no_result_master').css('display', 'block'); } else { $('#no_result_master').css('display', 'none'); } }); //frontpage only - only utlan table search filter $("#table_search_utlan").on("keyup", function() { var value_utlan = $(this).val().toLowerCase(); $("#table_data_utlan tr:not(:has(th))").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value_utlan) &gt; -1) }); var rowCount_utlan = $('#table_data_utlan tr:visible:not(:has(th))').length; $('#row_count_utlan').html(rowCount_utlan); if (rowCount_utlan == 0) { $('#no_result_utlan').css('display', 'block'); } else { $('#no_result_utlan').css('display', 'none'); } }); //frontpage only - only totaloversikt table search filter $("#table_search_totaloversikt").on("keyup", function() { var value_totaloversikt = $(this).val().toLowerCase(); $("#table_data_totaloversikt tr:not(:has(th))").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value_totaloversikt) &gt; -1) }); var rowCount_totaloversikt = $('#table_data_totaloversikt tr:visible:not(:has(th))').length; $('#row_count_totaloversikt').html(rowCount_totaloversikt); if (rowCount_totaloversikt == 0) { $('#no_result_totaloversikt').css('display', 'block'); } else { $('#no_result_totaloversikt').css('display', 'none'); } }); //frontpage only - only midlansatt table search filter $("#table_search_midlansatt").on("keyup", function() { var value_midlansatt = $(this).val().toLowerCase(); $("#table_data_midlansatt tr:not(:has(th))").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value_midlansatt) &gt; -1) }); var rowCount_midlansatt = $('#table_data_midlansatt tr:visible:not(:has(th))').length; $('#row_count_midlansatt').html(rowCount_midlansatt); if (rowCount_midlansatt == 0) { $('#no_result_midlansatt').css('display', 'block'); } else { $('#no_result_midlansatt').css('display', 'none'); } }); //not frontpage - common search filter for each individual site with a table $("#table_search").on("keyup", function() { var value_table = $(this).val().toLowerCase(); $(".table_data tr:not(:has(th))").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value_table) &gt; -1) }); var rowCount_table = $('.table_data tr:visible:not(:has(th))').length; $('#row_count').html(rowCount_table); if (rowCount_table == 0) { $('#no_result').css('display', 'block'); } else { $('#no_result').css('display', 'none'); } }); }); </code></pre> <p>HTML DOM:</p> <pre><code>&lt;div class="table_hits" style="display: none"&gt;Antall treff: &lt;b id="row_count_master"&gt;...&lt;/b&gt;&lt;/div&gt; &lt;input type="input" id="table_search_master" class="form-control" placeholder="Søk i hele databasen..." style=""&gt; &lt;div class="table_hits" style="display: none"&gt;Antall treff: &lt;b id="row_count_utlan"&gt;...&lt;/b&gt;&lt;/div&gt; &lt;input type="input" id="table_search_utlan" class="form-control" placeholder="Søk i utlånslisten..."&gt; &lt;div class="alert alert-danger" id="no_result_utlan" style="display:none; margin:0;"&gt;&lt;center&gt;Ingen resultat. Har du skrevet feil?&lt;/center&gt;&lt;/div&gt; &lt;div class="table_scroll_frontpage"&gt; &lt;table class="table_data" id="table_data_utlan"&gt; &lt;!-- table data --&gt; &lt;/table&gt; &lt;/div&gt; &lt;!-- same DOM for the rest of the tables --&gt; </code></pre> <p><strong>What I've tried</strong></p> <p>I've tried to merge every single selector into one filter function but naturally, that gave me issues where the input of the field would search in all tables at once and not get separated from each other.</p> <p>Every comment/answer that gives me a bit more knowledge of how to make this mess, neat and pretty is overly-appreciated! I'm highly motivated in learning more about on how to take full advantage of jQuery's nice features and improve my skills. Thanks in advance.</p>
[]
[ { "body": "<p>I think we need to start with a list of suffixes that can be put somewhere accessible(preferably as a property to a class, but global space works for now)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const suffixes = [\n 'master',\n 'utlan',\n 'totaloversikt'\n];\n</code></pre>\n\n<p>From there we can change our event listener to make a note of the suffix and register a generic function for the event.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>suffixes.foreach(suffix =&gt; {\n const isAllTableSearch = suffix === 'master';\n // Master has different behaviour\n const filterExpression = isAllTableSearch\n ? '.table_data tr:visible:not(:has(th))'\n : '#table_data_' + suffix + ' tr:visible:not(:has(th))';\n\n $(\"#table_search_\" + suffix)\n .data('suffix', suffix)\n .data('filter', filterExpression)\n .data('is-all-table-search', isAllTableSearch)\n .on(\"input\", doFiltering); // Input triggers whenever it changes including things like cut/paste rather than keyup which only triggers when a key is released\n});\n</code></pre>\n\n<p>Your doFiltering method can then use the search box to derive the suffix and filter to make the method more generic</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function doFiltering(event) {\n const searchBox = $(event.target);\n const searchQuery = searchBox.val().toLowerCase();\n $(searchBox.data('filter')).each((index, element) =&gt; {\n $(element).toggle($(element).text().toLowerCase().indexOf(searchQuery) &gt; -1)\n });\n\n // Update totals\n if (searchBox.data('is-all-table-search')) {\n updateAllTotals();\n } else {\n updateTotalForSuffix(searchBox.data('suffix'));\n }\n}\n</code></pre>\n\n<p>While we're talking adding methods for stuff I'd also suggest adding a method to recalculate the totals, this is especially important for the master which can hide rows in other tables but doesn't update their totals.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function updateTotalForSuffix(suffix) {\n const tableSearch = $(\"#table_search_\" + suffix);\n rowCount = $(tableSearch.data('filter')).length;\n $('#row_count_' + suffix).text(rowCount);\n $('#no_result_' + suffix).toggle(rowCount === 0);\n}\n\nfunction updateAllTotals() {\n suffixes.foreach(suffix =&gt; updateTotalForSuffix(suffix));\n}\n</code></pre>\n\n<p>This gives you a handy function to call on init and whenever the master search is called to avoid the info falling out of sync.</p>\n\n<p>This gives us a few advantages. We're not maintaining logic for multiple copies of the search functionality, we've got one set of methods that take an object and use it's properties to determine the behaviour rather than having changes to each bit of logic for changes in behaviour.</p>\n\n<p>Where possible I've tried to avoid <code>$(this)</code> because it can cause problems once you start abstracting stuff away into further functions(so say you wanted updating the totals to be a different method to your search but wanted a separate function for handling calling them both, using <code>$(this)</code> means to do so you now need to either change the methods or rebind the function, rather than just passing in a relevant argument like <code>event.target</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T13:17:24.643", "Id": "467455", "Score": "0", "body": "Amazing approach, I absolutely love it. I had a real fun time tweaking and learning from your code. I've made some [changes](https://jsfiddle.net/h8932yp4/) worth noting: In `const filterExpression` i changed `tr:visible:not(:has(th))` to `tr:not(:has(th))` otherwise it would only filter out visible rows and not invisible ones (not reappearing). I also added an ìf` query to the function `updateTotalForSuffix` so I can check whether or not its counting the individual table or all of the tables. As cleverly mentioned by you, I added a call to `updateAllTotals` at page load." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:06:02.270", "Id": "238304", "ParentId": "238243", "Score": "1" } } ]
{ "AcceptedAnswerId": "238304", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:12:52.697", "Id": "238243", "Score": "1", "Tags": [ "javascript", "jquery", "html", "html5" ], "Title": "Simplifying input filtering in tables with multiple selectors using jQuery" }
238243
<p>So, after <a href="https://codereview.stackexchange.com/questions/238095/filter-a-two-dimension-array">this</a> functional(?) approach and thanks to the <a href="https://stackoverflow.com/questions/60467718/calculate-when-is-convenient-taking-advantage-of-sorting-in-filtering-arrays/60477317?noredirect=1#comment106988890_60477317">great improvement</a> of @CDP1802, I've decided to try an OOP approach to filtering an two-dimensional array.</p> <p>In my opinion, the result is way more elegant and has also performance improvements.</p> <p>Now the user is able to choose the order of the filters (the more exclusive the first you set it) and can add how many filters he wants. He also can decide the columns to return and the order of the columns and, last, he can decide if comparison is case sensitive or not.</p> <p>The array maintains the original's array base.</p> <p>Do you like it? See possible improvements?</p> <p>This was the old call method:</p> <pre><code>arr = FilterArray(arr1, , , , , , 2, "B2", , , , , , , , , , , , , , , , , , 1, True, #1/1/2010#, #1/1/2020#) </code></pre> <p>and this the new:</p> <pre><code>Dim f As ArrayFilter Set f = New ArrayFilter With f .IncludeEquals "b2", 2 .IncludeBetween #1/1/2010#, #1/1/2020#, 1 .ApplyTo arr1 End With </code></pre> <p>This is the code of the ArrayFilter Class</p> <pre><code>Option Explicit Private pColumnsToReturn As Variant Private pFiltersCollection As Collection Private pPartialMatchColl As Collection Private Enum filterType negativeMatch = -1 exactMatch = 0 isBetween = 1 contains = 2 End Enum Public Property Let ColumnsToReturn(arr As Variant) pColumnsToReturn = arr End Property Public Property Get Filters() As Collection Set Filters = pFiltersCollection End Property Public Sub IncludeEquals(ByRef equalTo As Variant, ByRef inColumn As Long, _ Optional ByRef isCaseSensitive As Boolean = False) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = exactMatch With thisFilter .Add thisFilterType .Add inColumn .Add IIf(isCaseSensitive, equalTo, LCase(equalTo)) .Add isCaseSensitive End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub ExcludeEquals(ByRef equalTo As Variant, ByRef inColumn As Long, _ Optional ByRef isCaseSensitive As Boolean = False) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = negativeMatch With thisFilter .Add thisFilterType .Add inColumn .Add IIf(isCaseSensitive, equalTo, LCase(equalTo)) .Add isCaseSensitive End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub IncludeBetween(ByRef lowLimit As Variant, ByRef highLimit As Variant, ByRef inColumn As Long) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = isBetween With thisFilter .Add thisFilterType .Add inColumn .Add lowLimit .Add highLimit End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub IncludeIfContain(ByRef substring As String, Optional ByRef inColumns As Variant = 1) If IsArray(inColumns) Or IsNumeric(inColumns) Then Dim thisFilterType As filterType Set pPartialMatchColl = New Collection thisFilterType = contains With pPartialMatchColl .Add thisFilterType .Add inColumns .Add substring End With End If End Sub Public Sub ApplyTo(ByRef originalArray As Variant) If Not IsArray(originalArray) Then Exit Sub Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long Dim row As Long Dim col As Long Dim arrayOfColumnToReturn As Variant Dim partialMatchColumnsArray As Variant Dim result As Variant result = -1 arrayOfColumnToReturn = pColumnsToReturn If Not pPartialMatchColl Is Nothing Then partialMatchColumnsArray = pPartialMatchColl(2) ' If the caller don't pass the array of column to return ' create an array with all the columns and preserve the order If Not IsArray(arrayOfColumnToReturn) Then ReDim arrayOfColumnToReturn(LBound(originalArray, 2) To UBound(originalArray, 2)) For col = LBound(originalArray, 2) To UBound(originalArray, 2) arrayOfColumnToReturn(col) = col Next col End If ' If the caller don't pass an array for partial match ' check if it pass the special value 1, if true the ' partial match will be performed on values in columns to return If Not IsArray(partialMatchColumnsArray) Then If partialMatchColumnsArray = 1 Then partialMatchColumnsArray = arrayOfColumnToReturn End If firstRow = LBound(originalArray, 1) lastRow = UBound(originalArray, 1) ' main loop Dim keepCount As Long Dim filter As Variant Dim currentFilterType As filterType ReDim arrayOfRowsToKeep(lastRow - firstRow + 1) As Variant keepCount = 0 For row = firstRow To lastRow ' exact, excluse and between checks If Not Me.Filters Is Nothing Then For Each filter In Me.Filters currentFilterType = filter(1) Select Case currentFilterType Case negativeMatch If filter(4) Then If originalArray(row, filter(2)) = filter(3) Then GoTo Skip Else If LCase(originalArray(row, filter(2))) = filter(3) Then GoTo Skip End If Case exactMatch If filter(4) Then If originalArray(row, filter(2)) &lt;&gt; filter(3) Then GoTo Skip Else If LCase(originalArray(row, filter(2))) &lt;&gt; filter(3) Then GoTo Skip End If Case isBetween If originalArray(row, filter(2)) &lt; filter(3) _ Or originalArray(row, filter(2)) &gt; filter(4) Then GoTo Skip End Select Next filter End If ' partial match check If Not pPartialMatchColl Is Nothing Then If IsArray(partialMatchColumnsArray) Then For col = LBound(partialMatchColumnsArray) To UBound(partialMatchColumnsArray) If InStr(1, originalArray(row, partialMatchColumnsArray(col)), pPartialMatchColl(3), vbTextCompare) &gt; 0 Then GoTo Keep End If Next GoTo Skip End If End If Keep: arrayOfRowsToKeep(keepCount) = row keepCount = keepCount + 1 Skip: Next row ' create results array If keepCount &gt; 0 Then firstRow = LBound(originalArray, 1) lastRow = LBound(originalArray, 1) + keepCount - 1 firstColumn = LBound(originalArray, 2) lastColumn = LBound(originalArray, 2) + UBound(arrayOfColumnToReturn) - LBound(arrayOfColumnToReturn) ReDim result(firstRow To lastRow, firstColumn To lastColumn) For row = firstRow To lastRow For col = firstColumn To lastColumn result(row, col) = originalArray(arrayOfRowsToKeep(row - firstRow), arrayOfColumnToReturn(col - firstColumn + LBound(arrayOfColumnToReturn))) Next col Next row End If originalArray = result If IsArray(result) Then Erase result End Sub </code></pre>
[]
[ { "body": "<p>The code breaks at <code>.Applyto</code> with the following error:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Run-time error &quot;458&quot;\nVariable uses an Automation type not supported in Visual Basic.\n</code></pre>\n<p>I passed a worksheet range to an <code>Array</code> and this, by definition, creates a 2D array.\nHere is my testing code.</p>\n<p>Note: I verified that <code>arr1</code> gets allocated with the passed <code>Range</code>.</p>\n<pre><code>Dim arr1() As Variant\narr1 = Range(&quot;B2:F5&quot;)\nDim Destination As Range\nSet Destination = Range(&quot;K1&quot;)\n\nDim f As ArrayFilt\nSet f = New ArrayFilt\n\nWith f\n .IncludeEquals &quot;s&quot;, 2\n .ApplyTo arr1\nEnd With\n\n'more code to write the filtered array back to worksheet to check if the filter was correctly applied.\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:37:39.120", "Id": "505671", "Score": "0", "body": "Hi @seeker.. This is old code and I'm sure there were some problems, but in this case, I can't reproduce the error you're pointing out.. When I copy and run the code above, no errors are raised and the filter works smoothly.. I can't help you.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T13:31:12.553", "Id": "256144", "ParentId": "238244", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:28:39.723", "Id": "238244", "Score": "2", "Tags": [ "performance", "object-oriented", "array", "vba" ], "Title": "OOP approach to filter two-dimensional array" }
238244
<p>I have the following code: It works completely as expected, but I feel there is a better way to refactor it out.</p> <p>The flow is as follows:</p> <ol> <li>Call the end point with 1 page </li> <li>Get the total number of results.</li> <li>If total count of items more than <code>itemsPerPage</code>. </li> <li>Call the API more times till results from all pages are returned, join them together as single invoice list</li> <li>Append with initial request and send back.</li> </ol> <p>Do I need <code>GetAllInvoices</code> function? Reason it is kept there is because I believe the responsibility of calling each pages of API does not belong to main function.</p> <pre class="lang-cs prettyprint-override"><code>public async Task&lt;IEnumerable&lt;Invoice&gt;&gt; GetAllInvoicesAsync() { const string endPoint = @"foo/{0}/invoices?pageNum={1}&amp;itemsPerPage={2}"; const int itemsPerPage = xxx; InvoiceCollection response = await _apiClient .GetAsync&lt;InvoiceCollection&gt;(string.Format(endPoint, _apiClient.OrgId, 1, itemsPerPage)); if (response?.TotalCount &gt; itemsPerPage) { var allInvoices = (await GetAllInvoices(endPoint,response.TotalCount, itemsPerPage)) .SelectMany(i =&gt; i.Invoices?? Enumerable.Empty&lt;Invoice&gt;()); response.Invoices = (response.Invoices ?? Enumerable.Empty&lt;Invoice&gt;()).Concat(allInvoices); } return response?.Invoices; } private async Task&lt;List&lt;InvoiceCollection&gt;&gt; GetAllInvoices(string endPoint,int totalCount, int itemsPerPage) { var totalPages = (int)Math.Ceiling(totalCount / (double)itemsPerPage); var tasks = new List&lt;Task&lt;InvoiceCollection&gt;&gt;(); for (int currentPage = 2; currentPage&lt;=totalPages;currentPage++) { tasks.Add(_apiClient .GetAsync&lt;InvoiceCollection&gt;(string.Format(endPoint, _apiClient.OrgId, currentPage, itemsPerPage))); } var response = new List&lt;InvoiceCollection&gt;(await Task.WhenAll(tasks)); return response; } public class InvoiceCollection { [JsonProperty("foo")] public IEnumerable&lt;Invoice&gt; Invoices { get; set; } public int TotalCount { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:56:51.040", "Id": "467248", "Score": "0", "body": "Updated the title" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:30:31.417", "Id": "467252", "Score": "1", "body": "I think @BCdotWEB means that the title should mention invoicing and that the current title can be asked within the body of the question." } ]
[ { "body": "<p>When you have an assumption of getting a mix of return one or more values. You need to favor collection over single value return; because treating it as a collection would make things easier to deal with. </p>\n\n<p>So, you can get rid of <code>GetAllInvoices</code> and adjust <code>GetAllInvoicesAsync</code> to something like this : </p>\n\n<pre><code>public async Task&lt;IEnumerable&lt;Invoice&gt;&gt; GetAllInvoicesAsync()\n{\n const string endPoint = @\"foo/{0}/invoices?pageNum={1}&amp;itemsPerPage={2}\";\n const int itemsPerPage = xxx;\n int pageNumber = 1; \n int iterationCount = 0;\n\n var tasks = new List&lt;Task&lt;InvoiceCollection&gt;&gt;();\n\n var isFirstRound = true;\n\n do\n { \n var response = await _apiClient.GetAsync&lt;InvoiceCollection&gt;(string.Format(endPoint, _apiClient.OrgId, pageNumber, itemsPerPage));\n\n if(isFirstRound) \n { \n iterationCount = response?.TotalCount &lt;= itemsPerPage ? response?.TotalCount : (int) Math.Ceiling(totalPageItems / (double)itemsPerPage);\n isFirstRound = false;\n }\n\n tasks.Add(response);\n\n pageNumber++;\n } \n while(pageNumber &lt;= iterationCount)\n\n var invoiceResponseList = new List&lt;InvoiceCollection&gt;(await Task.WhenAll(tasks));\n\n var invoiceCollection = invoiceResponseList.SelectMany(i =&gt; i.Invoices ?? Enumerable.Empty&lt;Invoice&gt;());\n\n return invoiceCollection?.Invoices; \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:13:03.217", "Id": "238378", "ParentId": "238248", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:25:25.150", "Id": "238248", "Score": "1", "Tags": [ "c#", "rest" ], "Title": "Invoicing - calling multiple pages of Api and concatinating the results" }
238248
<p>I'm learning object-oriented programming in Python. I've created a class <code>RepositoryMaker</code> that contains all methods required to create a Git repository. The idea is to be able to create a single instance of this class with a constructor that only requires pertinent info to create a new repo.</p> <p>My code looks like this:</p> <pre><code>class RepositoryMaker: """Creates new Azure DevOps repositories""" def __init__(self, project_name, repo_name): self.project_name = project_name self.repo_name = repo_name with open("./repo_request_body.json", "r") as file: self.data = json.load(file) def get_project_id(self): """Returns the Azure DevOps project ID for a project name""" _request_object = make_request( "_apis/projects/", self.project_name, "?api-version=5.1-preview.1", request_method = "get" ) return _request_object.get("id") def update_project_id(self): """Updates JSON dictionary with new ID""" new_id = self.get_project_id() self.data["project"]["id"] = new_id def update_repo_name(self): """Updates JSON dictionary with new repo name""" self.data["name"] = self.repo_name return self.data json_content_type = { 'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXXXXXXXX' } def create_repository(self): """Creates a new repo under the specified project""" self.update_project_id() repo_request_body = self.update_repo_name() make_request( self.project_name, "/_apis/git/repositories", "?api-version=5.1-preview.1", request_method = "post", data = json.dumps(repo_request_body), headers = self.json_content_type ) x = RepositoryMaker(project_name, repo_name) x.create_repository() </code></pre> <p>My concern is chaining together class methods internally within the class. For example, <code>create_repository()</code> is calling <code>update_project_id()</code> which is calling <code>get_project_ID()</code>.</p> <p>Is this convention acceptable within Python? Is there a better way to group together a set of related functions than using a class?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:37:19.450", "Id": "467254", "Score": "1", "body": "I don't work with azure repos, but what if your `get_project_id` method returned empty id (for non-existent project name)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T16:34:39.133", "Id": "467258", "Score": "0", "body": "That's a helpful observation, I'll add validation to fix that." } ]
[ { "body": "<p>I think in this case, where these are the only methods of the class, you don't need the class at all. Just make it standalone functions:</p>\n\n<pre><code>import json\n\nJSON_CONTENT_TYPE = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic XXXXXXXXXXXXXXXX'\n }\n\n\ndef make_request(...):\n ...\n\n\ndef get_project_id(project_name):\n \"\"\"Returns the Azure DevOps project ID for a project name\"\"\"\n url = f\"_apis/projects/{project_name}?api-version=5.1-preview.1\"\n return make_request(url, request_method=\"get\").get(\"id\")\n\n\ndef create_repository(project_name, repo_name):\n \"\"\"Creates a new Azure DevOps repo under the specified project\"\"\"\n with open(\"./repo_request_body.json\") as file:\n data = json.load(file)\n data[\"project\"][\"id\"] = get_project_id(project_name)\n data[\"name\"] = repo_name\n\n url = f\"{project_name}/_apis/git/repositories?api-version=5.1-preview.1\"\n make_request(url, request_method=\"post\",\n data=json.dumps(data), headers=JSON_CONTENT_TYPE)\n</code></pre>\n\n<p>This uses Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends no spaces around <code>=</code> when using it for keyword arguments, <code>UPPER_CASE</code> for global constants and the relatively new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> to make formatting strings easier. Since you did not supply the <code>make_request</code> function I am not sure if that is how it is used, though.</p>\n\n<p>You might want to make the API-version also an argument of the function (maybe with a default argument).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:39:25.127", "Id": "238251", "ParentId": "238249", "Score": "4" } }, { "body": "<p>Class methods calling each other is perfectly acceptable in general, but this should be done toward the end of making the code easier to follow by encapsulating complexity. Two things in your example potentially work against that goal:</p>\n\n<ol>\n<li>All of the methods and attributes are public. (In Python you denote a \"private\" member by starting its name with <code>_</code>.)</li>\n<li>Data is passed between the methods via instance attributes.</li>\n</ol>\n\n<p>This means that someone reviewing this code for possible bugs needs to assume that a caller might call any of these methods while the object is in any arbitrary state -- that's a lot of combinations to consider!</p>\n\n<p>If the only intended usage of this class is the one you've given (create a single instance, call <code>create_repository</code> exactly once), then there isn't much benefit to making it a class with state (since that state is never meant to be reused beyond that one function call). The other typical way of grouping related functions is to simply define them locally within a larger function:</p>\n\n<pre><code>def create_repository(project_name: str, repo_name: str) -&gt; None:\n \"\"\"Creates a new repo under the specified project\"\"\"\n\n with open(\"./repo_request_body.json\", \"r\") as file:\n data = json.load(file)\n\n def get_project_id() -&gt; str:\n \"\"\"Returns the Azure DevOps project ID for a project name\"\"\"\n _request_object = make_request(\n \"_apis/projects/\",\n project_name,\n \"?api-version=5.1-preview.1\",\n request_method = \"get\"\n )\n return _request_object.get(\"id\")\n\n def update_project_id() -&gt; None:\n \"\"\"Updates JSON dictionary with new ID\"\"\"\n new_id = get_project_id()\n data[\"project\"][\"id\"] = new_id\n\n def update_repo_name() -&gt; None:\n \"\"\"Updates JSON dictionary with new repo name\"\"\"\n data[\"name\"] = repo_name\n\n json_content_type = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic XXXXXXXXXXXXXXXX'\n }\n\n update_project_id()\n update_repo_name()\n make_request(\n project_name,\n \"/_apis/git/repositories\",\n \"?api-version=5.1-preview.1\",\n request_method = \"post\",\n data = json.dumps(data),\n headers = json_content_type\n )\n\ncreate_repository(\"project_name\", \"repo_name\")\n</code></pre>\n\n<p>But given that each of these functions is only called once, is there any value to actually giving them individual names and making the reader jump around between them? I'd probably just write this as one function where everything is written in exactly the order it happens in:</p>\n\n<pre><code>def create_repository(project_name: str, repo_name: str) -&gt; None:\n \"\"\"Creates a new repo under the specified project\"\"\"\n # Load the repo request data from disk.\n with open(\"./repo_request_body.json\", \"r\") as file:\n data = json.load(file)\n\n # Get the Azure DevOps project ID for a project name\n _request_object = make_request(\n \"_apis/projects/\",\n project_name,\n \"?api-version=5.1-preview.1\",\n request_method=\"get\"\n )\n new_id = _request_object.get(\"id\")\n\n # Update JSON dictionary with new ID\n data[\"project\"][\"id\"] = new_id\n\n # Update JSON dictionary with new repo name\n data[\"name\"] = repo_name\n\n # Make the server request.\n json_content_type = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic XXXXXXXXXXXXXXXX'\n }\n make_request(\n project_name,\n \"/_apis/git/repositories\",\n \"?api-version=5.1-preview.1\",\n request_method=\"post\",\n data=json.dumps(data),\n headers=json_content_type\n )\n\ncreate_repository(\"project_name\", \"repo_name\")\n</code></pre>\n\n<p>IMO this is a lot easier to follow, in that dependencies between the different blocks of code are very obvious and I can read it from top to bottom and easily keep track of what's happening when.</p>\n\n<p>Taking it one step further, I'd eliminate the named variables that only get used once, which shortens the <code>new_id</code> part of the code (again, less for the reader to keep track of if they can see at a glance that function calls chain together to produce a single result, rather than having to try to figure out if a given value is going to be used again later):</p>\n\n<pre><code>def create_repository(project_name: str, repo_name: str) -&gt; None:\n \"\"\"Creates a new repo under the specified project\"\"\"\n # Load the repo request data from disk.\n with open(\"./repo_request_body.json\", \"r\") as file:\n data = json.load(file)\n\n # Update JSON dictionary with new ID from server API\n data[\"project\"][\"id\"] = make_request(\n \"_apis/projects/\",\n project_name,\n \"?api-version=5.1-preview.1\",\n request_method=\"get\"\n ).get(\"id\")\n\n # Update JSON dictionary with new repo name\n data[\"name\"] = repo_name\n\n # Make the server request to create the repo.\n make_request(\n project_name,\n \"/_apis/git/repositories\",\n \"?api-version=5.1-preview.1\",\n request_method=\"post\",\n data=json.dumps(data),\n headers={\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic XXXXXXXXXXXXXXXX',\n }\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:41:10.533", "Id": "238252", "ParentId": "238249", "Score": "8" } } ]
{ "AcceptedAnswerId": "238252", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T14:28:14.260", "Id": "238249", "Score": "6", "Tags": [ "python", "object-oriented" ], "Title": "Chaining Internal Class Methods in Python" }
238249
<p>A follow-up to this question is <a href="https://codereview.stackexchange.com/questions/238474/chunking-strings-to-binary-block-based-output">Chunking strings to binary block-based output</a></p> <hr> <p>I have code which takes a text file as input and creates a special binary output form of the input. Specifically, the test input I'm using is the plain text of Samuel Coleridge's poem <a href="https://www.poetryfoundation.org/poems/43991/kubla-khan" rel="nofollow noreferrer">"Kubla Khan"</a>. Here are the first few lines, shown here with line numbers which are only for reference and not actually part of the text:</p> <pre><code> 1 Kubla Khan 2 By Samuel Taylor Coleridge 3 4 Or, a vision in a dream. A Fragment. 5 6 In Xanadu did Kubla Khan 7 A stately pleasure-dome decree: 8 Where Alph, the sacred river, ran 9 Through caverns measureless to man 10 Down to a sunless sea. 11 So twice five miles of fertile ground 12 With walls and towers were girdled round; 13 And there were gardens bright with sinuous rills, 14 Where blossomed many an incense-bearing tree; 15 And here were forests ancient as the hills, 16 Enfolding sunny spots of greenery. </code></pre> <p>Here is a sample hex dump of the output with some annotations. See the "Processing" section for an explanation of this data structure.</p> <pre><code> Block 0 00000000: be ad ca fe 0a 4b 75 62 6c 61 20 4b 68 61 6e 1a .....Kubla Khan. | signature | n| first line ... | n| 00000010: 42 79 20 53 61 6d 75 65 6c 20 54 61 79 6c 6f 72 By Samuel Taylor | second line... 00000020: 20 43 6f 6c 65 72 69 64 67 65 00 24 4f 72 2c 20 Coleridge.$Or, | | n| n| fourth... | 00000030: 61 20 76 69 73 69 6f 6e 20 69 6e 20 61 20 64 72 a vision in a dr | line ... | 00000040: 65 61 6d 2e 20 41 20 46 72 61 67 6d 65 6e 74 2e eam. A Fragment. | still the fourth line. | 00000050: 00 18 49 6e 20 58 61 6e 61 64 75 20 64 69 64 20 ..In Xanadu did | n| n| sixth line... 00000060: 4b 75 62 6c 61 20 4b 68 61 6e 1f 41 20 73 74 61 Kubla Khan.A sta 00000070: 74 65 6c 79 20 70 6c 65 61 73 75 72 65 2d 64 6f tely pleasure-do 00000080: 6d 65 20 64 65 63 72 65 65 3a 21 57 68 65 72 65 me decree:!Where 00000090: 20 41 6c 70 68 2c 20 74 68 65 20 73 61 63 72 65 Alph, the sacre 000000a0: 64 20 72 69 76 65 72 2c 20 72 61 6e 22 54 68 72 d river, ran"Thr 000000b0: 6f 75 67 68 20 63 61 76 65 72 6e 73 20 6d 65 61 ough caverns mea 000000c0: 73 75 72 65 6c 65 73 73 20 74 6f 20 6d 61 6e 19 sureless to man. 000000d0: 20 20 20 44 6f 77 6e 20 74 6f 20 61 20 73 75 6e Down to a sun 000000e0: 6c 65 73 73 20 73 65 61 2e 25 53 6f 20 74 77 69 less sea.%So twi | end of tenth line | n| eleventh line | 000000f0: 63 65 20 66 69 76 65 20 6d 69 6c 65 3e f2 d5 86 ce five mile&gt;... | middle of eleventh line | checksum | Block 1 00000100: be ad ca fe 73 20 6f 66 20 66 65 72 74 69 6c 65 ....s of fertile | signature | middle of eleventh line | 00000110: 20 67 72 6f 75 6e 64 29 57 69 74 68 20 77 61 6c ground)With wal | end eleventh line | n| twelfth line ... | </code></pre> <h2>Processing</h2> <p>Each line of the text is turned into a <em>counted string</em> (also sometimes called a "Pascal string" after the way that language stores strings). A counted string is a single <code>uint8_t</code> count <span class="math-container">\$n\$</span>, followed by <span class="math-container">\$n\$</span> bytes of the string. No line is more than 255 characters long and a count of zero indicates a blank line.</p> <h3>Counted string format</h3> <p><span class="math-container">$$ \begin{array}{l|c|l} \text{name} &amp; \text{length in bytes} &amp; \text{description} \\ \hline \text{count} &amp; 1 &amp; \text{count of bytes that follow, range 0-255} \\ \text{string} &amp; 0..255 &amp; \text{string may or may not have NUL terminator} \\ \end{array} $$</span></p> <p>Then those counted strings are output as a series of <code>Block</code>s. A <code>Block</code> is a 256-byte chunk which starts with a fixed 4-byte block identifier and ends with a <code>uint32_t</code> checksum which is the simple checksum of all of the other data as though it were a series of <code>uint32_t</code> numbers, ignoring overflow.</p> <h3>Block format</h3> <p><span class="math-container">$$ \begin{array}{l|c|l} \text{name} &amp; \text{length in bytes} &amp; \text{description} \\ \hline \text{signature} &amp; 4 &amp; \text{fixed 0xfecaadbe} \\ \text{data} &amp; 248 &amp; \text{the data} \\ \text{checksum} &amp; 4 &amp; \text{checksum of block as 32-bit unsigned value} \\ &amp; &amp; \text{with same endian-ness as signature} \\ \hline \text{Block} &amp; 256 &amp; \text{total block size} \\ \end{array} $$</span></p> <h2>Questions</h2> <p>The code I have works as intended, but I'm left with the nagging feeling that it is fundamentally the wrong approach. For instance, in this code, the entire data is read and created as a <code>std::strstream</code> but I can anticipate that at some point I am going to want to process things on the fly, as from a named pipe or TCP stream where rewinding won't be possible. I thought about chaining two independent streams, one which feeds the other but I'm not sure how to approach that. Should I derive my own <code>ostream</code>? Two <code>ostream</code>s? Maybe <code>streambuf</code>? </p> <h2>encode.cpp</h2> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;array&gt; /* * The stream format consists of blocks, each 256 bytes long. * Each block begins with a fixed 4-byte block identifier and * ends with a fixed 4-byte checksum. Everything between * them is data. * * The data is in the form of counted strings. A counted * string is a one byte unsigned integer `n` followed by * that many bytes of data. A counted string may or may not * be NUL character terminated. */ class Block { public: static constexpr std::size_t mysize{0x100}; friend std::istream&amp; operator&gt;&gt;(std::istream&amp; in, Block&amp; blk) { blk.clear(); in.read(reinterpret_cast&lt;char *&gt;(&amp;blk.data), blk.datasize); blk.checksum = blk.sumcalc(); return in; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Block&amp; blk) { out.write(reinterpret_cast&lt;const char *&gt;(&amp;blk.id), sizeof(blk.id)); out.write(reinterpret_cast&lt;const char *&gt;(&amp;blk.data), blk.datasize); out.write(reinterpret_cast&lt;const char *&gt;(&amp;blk.checksum), sizeof(blk.checksum)); return out; } private: void clear() { std::fill(data.begin(), data.end(), 0); } uint32_t sumcalc() { uint32_t sum{id}; auto n{datasize/sizeof(uint32_t)}; for (uint32_t *ptr = reinterpret_cast&lt;uint32_t *&gt;(&amp;data); n; ++ptr) { sum += *ptr; --n; } return sum; } uint32_t id = 0xfecaadbe; uint32_t checksum = 0; static constexpr std::size_t datasize{mysize - sizeof(Block::id) - sizeof(checksum)}; std::array&lt;uint8_t, datasize&gt; data; }; int main(int argc, char *argv[]) { std::string line; if (argc != 3) { std::cerr &lt;&lt; "Usage: encode infile outfile\n"; return 1; } std::ifstream in(argv[1]); std::stringstream buff; while (std::getline(in, line)) { // skip long lines if (line.length() &lt; 256) { uint8_t n = line.length() &amp; 0xff; buff.put(n); buff &lt;&lt; line; } } in.close(); // second pass std::ofstream out(argv[2]); buff.seekg(0); // rewind Block b; while (buff &gt;&gt; b) { out &lt;&lt; b; } // always emit at least one block even if empty out &lt;&lt; b; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:44:32.620", "Id": "467327", "Score": "0", "body": "Just to make sure that I understand the problem correctly: can't you simply read a line, emit one Block, and then move on to the next line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:46:22.043", "Id": "467328", "Score": "1", "body": "No because each block typically contains multiple counted strings and often the last counted string in a block is a partial one that continues in the next block. I'll amend the question to try to make this more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:57:30.717", "Id": "467393", "Score": "1", "body": "I see I was misunderstanding the format. Thanks for the clear explanation!" } ]
[ { "body": "<p>I agree with you that this would be more intuitive to use by chaining streams, rather than acting as a queue that must be pushed into and pulled out of. I've never written a filtering stream like that myself, but I <em>think</em> you want to construct an <code>ostream</code> with a custom <code>streambuf</code> for each filter.</p>\n\n<p>I definitely think that separating the line encoding and the block packing would be a good thing, and would allow your unit tests to be much more selective, and therefore more diagnostic.</p>\n\n<hr>\n\n<p>We seem to be assuming these typedefs:</p>\n\n<pre><code>using std::uint32_t;\nusing std::uint8_t;\n</code></pre>\n\n<hr>\n\n<p>Reviewing the <code>main()</code> - it's quite restrictive to insist on two filenames (and that the output file be seekable). It would be more natural if it was willing to use standard i/o streams if no arguments are given.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> uint32_t sum{id};\n auto n{datasize/sizeof(uint32_t)};\n for (uint32_t *ptr = reinterpret_cast&lt;uint32_t *&gt;(&amp;data); n; ++ptr) {\n sum += *ptr;\n --n;\n }\n return sum;\n</code></pre>\n</blockquote>\n\n<p>This looks like a candidate for <code>std::span</code>:</p>\n\n<pre><code> std::span as_u32{reinterpret_cast&lt;std::uint32_t*&gt;(data.begin()),\n reinterpret_cast&lt;std::uint32_t*&gt;(data.end())};\n return std::accumulate(as_u32.begin(), as_u32.end(), std::uint32_t{});\n</code></pre>\n\n<p>Or, using a simple pair of iterators, for C++17 and earlier:</p>\n\n<pre><code> auto first = reinterpret_cast&lt;const std::uint32_t*&gt;(data.begin());\n auto last = reinterpret_cast&lt;const std::uint32_t*&gt;(data.end());\n return std::accumulate(first, last, std::uint32_t{});\n</code></pre>\n\n<p>This method should probably be declared <code>const</code>.</p>\n\n<p>We do have a problem here in that the data are interpreted as <code>std::uint32_t</code> <em>in the endianness of the host</em>. That means that different platforms can generate different checksums, something generally considered undesirable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:03:56.223", "Id": "467646", "Score": "1", "body": "I particularly like the suggestion about using `std::span` - my compiler doesn't yet support that but it's coming soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T11:25:41.177", "Id": "467707", "Score": "0", "body": "For this purpose, you can probably side-step the span - we're just using it as an iterator pair here. I've edited with a C++17 alternative; that's simpler, so may be better than `std::span` even where that's available." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T11:50:34.120", "Id": "467709", "Score": "0", "body": "In fact, that’s exactly what I did in the revised code, which I will soon post." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:13:58.257", "Id": "238320", "ParentId": "238253", "Score": "6" } }, { "body": "<p>The code is nice and readable.</p>\n\n<p>The system-dependent handling of <code>\\n</code> characters may cause problems &mdash; we may introduce a <code>\\012</code> byte in the signature, count, or checksum part that gets transformed into CR-LF (on Windows) or CR (on old MacOS). I think we can simply open the output stream in binary mode, since our data won't contain <code>\\n</code> characters that need to be handled specially.</p>\n\n<p>Here are some small improvements:</p>\n\n<hr>\n\n<blockquote>\n<pre><code>void clear() {\n std::fill(data.begin(), data.end(), 0); \n}\n</code></pre>\n</blockquote>\n\n<p>We can use the <code>fill</code> member of <code>std::array</code> to simplify the code:</p>\n\n<pre><code>data.fill(0);\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>data = {};\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>reinterpret_cast&lt;char *&gt;(&amp;blk.data)\n</code></pre>\n</blockquote>\n\n<p>This cast comes up very often. Consider making a function:</p>\n\n<pre><code>template &lt;typename T&gt;\nchar* as_chars(const T&amp; value)\n{\n return reinterpret_cast&lt;char*&gt;(value);\n}\n</code></pre>\n\n<p>So you can write</p>\n\n<pre><code>in.read(as_chars(blk.data), blk.datasize);\n// ...\n</code></pre>\n\n<p>You can even make a function for reading/writing if you do it often.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>uint32_t id = 0xfecaadbe;\n</code></pre>\n</blockquote>\n\n<p><code>static constexpr</code>, maybe?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>std::string line;\n</code></pre>\n</blockquote>\n\n<p>This variable is used several lines after. It may be more readable to put it inside the loop:</p>\n\n<pre><code>for (std::string line; std::getline(in, line);) {\n // ...\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>if (line.length() &lt; 256) {\n uint8_t n = line.length() &amp; 0xff;\n buff.put(n);\n buff &lt;&lt; line;\n}\n</code></pre>\n</blockquote>\n\n<p>If <code>line.length() &lt; 256</code>, then <code>line.length() &amp; 0xff == line.length()</code> right?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>in.close();\n</code></pre>\n</blockquote>\n\n<p>You can omit this close by putting <code>in</code> inside a scope. Not sure if that's better.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>Block b;\nwhile (buff &gt;&gt; b) {\n out &lt;&lt; b;\n}\n// always emit at least one block even if empty\nout &lt;&lt; b;\n</code></pre>\n</blockquote>\n\n<p>It took me a while to see that <code>b</code> is empty after the last failed read. Help the poor code reader by using something like <code>out &lt;&lt; Block{}</code> please :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:05:06.097", "Id": "467647", "Score": "0", "body": "I've used just about all of these suggestions, but hadn't even considered the first issue. Good review, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T01:28:48.370", "Id": "238340", "ParentId": "238253", "Score": "5" } } ]
{ "AcceptedAnswerId": "238340", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:47:07.070", "Id": "238253", "Score": "5", "Tags": [ "c++", "stream", "c++20" ], "Title": "Chunking strings to binary output" }
238253
<h2>Problem Statement</h2> <p>I'm reading each line from a .csv file and parsing each comma-delimited value and casting it to the appropriate type: </p> <pre><code>string[] words = filelines[i].Split(delimiter); // "i" is the 0-based line number // Remove double quotes encasing the timestamp DateTime tmStamp = Convert.ToDateTime(words[0].Trim('\"')); int recNum.Parse(words[1]); // Although unlikely, it's ok to throw FormatException here. There is a try/catch-all around this method call. string SSBRecvdTim = words[2].Replace("\"", "\'"); double batt_volt3, UWMBatt, SysId3, SIMId3, UWMId3, pTemp3, NumMdmOnOff, NumMdmSync, ADCP1Run, NoData1, BRK_sent1, UnkRecCnt1, ADCP1RecCnt, ADCP2Run, NoData2, BRK_sent2, UnkRecCnt2, ADCP2RecCnt, NoAQDData, AQDRecCnt; try { recNum = Int32.Parse(words[1]); batt_volt3 = Convert.ToDouble(words[3]); UWMBatt = Convert.ToDouble(words[4]); SysId3 = Convert.ToDouble(words[5]); SIMId3 = Convert.ToDouble(words[6]); UWMId3 = Convert.ToDouble(words[7]); pTemp3 = Convert.ToDouble(words[8]); NumMdmOnOff = Convert.ToDouble(words[9]); NumMdmSync = Convert.ToDouble(words[10]); ADCP1Run = Convert.ToDouble(words[11]); NoData1 = Convert.ToDouble(words[12]); BRK_sent1 = Convert.ToDouble(words[13]); UnkRecCnt1 = Convert.ToDouble(words[14]); ADCP1RecCnt = Convert.ToDouble(words[15]); ADCP2Run = Convert.ToDouble(words[16]); NoData2 = Convert.ToDouble(words[17]); BRK_sent2 = Convert.ToDouble(words[18]); UnkRecCnt2 = Convert.ToDouble(words[19]); ADCP2RecCnt = Convert.ToDouble(words[20]); NoAQDData = Convert.ToDouble(words[21]); AQDRecCnt = Convert.ToDouble(words[22]); } catch (FormatException fe) { throw fe; } </code></pre> <p>I've inherited this code and can't do anything about the number of variables. The problem is that the code is repetitive, verbose, and doesn't tell me which particular index causes<code>FormatException</code> to be thrown. The long list of <code>doubles</code> is also unwieldy.</p> <p>Those values are used to create the query:</p> <pre><code>string query = $"INSERT INTO [dbo].[{tablename}] VALUES " +$"( '{tmStamp}', {recNum}, {SSBRecvdTim}, {batt_volt3}, {UWMBatt}, {SysId3}, {SIMId3}, {UWMId3}, {pTemp3}," +$" {NumMdmOnOff}, {NumMdmSync}, {ADCP1Run}, {NoData1}, {BRK_sent1}, {UnkRecCnt1}, {ADCP1RecCnt}," +$" {ADCP2Run}, {NoData2}, {BRK_sent2}, {UnkRecCnt2}, {ADCP2RecCnt}, {NoAQDData}, {AQDRecCnt} )"; </code></pre> <h2>Solution Attempt</h2> <p>The original developer didn't know to use a database ORM framework so queries were constructed using strings. It isn't worthwhile to introduce it now since the code is on its way to retirement.</p> <p>I thought to use a dictionary to map the token # to the variable that would be assigned. I could then use a for-loop to loop over each token number. <strong>Unfortunately, this does not work because <code>Fields</code> stores copies of the doubles and aren't references to the doubles themselves</strong>. If you print <code>Fields[0]</code> you might get a double but the backing variable <code>batt_volt</code> will contain the value null.</p> <pre><code>Dictionary&lt;int, double&gt; Fields = new Dictionary&lt;int, double&gt;() { {3, batt_volt3 = 0}, {4, UWMBatt = 0}, {5, SysId3 = 0}, {6, SIMId3 = 0}, {7, UWMId3 = 0}, {8, pTemp3 = 0}, {9, NumMdmOnOff = 0}, {10, NumMdmSync = 0}, {11, ADCP1Run = 0}, {12, NoData1 = 0}, {13, BRK_sent1 = 0}, {14, UnkRecCnt1 = 0}, {15, ADCP1RecCnt = 0}, {16, ADCP2Run = 0}, {17, NoData2 = 0}, {18, BRK_sent2 = 0}, {19, UnkRecCnt2 = 0}, {20, ADCP2RecCnt = 0}, {21, NoAQDData = 0}, {22, AQDRecCnt = 0} }; List&lt;int&gt; TokenIndices = new List&lt;int&gt;(Fields.Keys); foreach (var tokenIdx in TokenIndices) { try { Fields[tokenIdx] = double.Parse(words[tokenIdx]); } catch (FormatException fe) { string errorMsg = $"FormatException thrown while trying to parse Line #{i}, Token #{tokenIdx}."; throw new FormatException(errorMsg, fe); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T17:13:20.590", "Id": "467260", "Score": "0", "body": "Why reinvent the wheel when there's already https://joshclose.github.io/CsvHelper/ ? Combine that with https://dapper-tutorial.net/ and your code is far easier to read and up to date." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T19:58:48.167", "Id": "467272", "Score": "0", "body": "The code was written around 2010 by another developer who quit who likely didn't know about ORMs. Also, I'd never heard of CsvHelper nor dapper. Dapper looks like a clone of [Entity Framework Extension](https://entityframework-extensions.net/?z=github&y=entityframework-plus) -- also with a hefty price tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T20:48:03.160", "Id": "467275", "Score": "0", "body": "In real life are the variables declared locally as you show, or are they defined as class fields?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:54:35.037", "Id": "467317", "Score": "2", "body": "@MinhTran Sometimes maintaining code means throwing out the old and replacing it with new and better code. Both Dapper and CsvHelper are free, easy to use and well-documented." } ]
[ { "body": "<p>I think the best approach instead of storing the raw values in a dictionary would be to create DbParameters (assuming you are using ADO.Net). </p>\n\n<p>You would need to change the sql insert statement to be parameterized - which you should as inserting raw values into a sql statement has been a bad practice for a long time. With SSBRecvdTim being a string the code is open for a sql injection.</p>\n\n<p>Even with your implementation you would need to change the sql insert statement to use the dictionary since updating the dictionary isn't going to update the variables or you need to map back the dictionary to the variable. </p>\n\n<p>While making it use parameters will be a tad bit more work it will be better even if the code is on the way out. </p>\n\n<p>as example you could make a method like - just an example not sure what would work best in your code base.</p>\n\n<pre><code>static SqlParameter CreateParameter(string name, string value, TypeCode typeCode, int line)\n{\n try\n {\n return new SqlParameter(name, Convert.ChangeType(value, typeCode));\n }\n catch (FormatException fe)\n {\n string errorMsg =\n $\"FormatException thrown while trying to parse Line #{line}, Token #{name}.\";\n throw new FormatException(errorMsg, fe);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T17:14:25.843", "Id": "467261", "Score": "0", "body": "You're right. The dictionary approach doesn't work because updating the dictionary value doesn't update the variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T20:54:10.370", "Id": "467276", "Score": "0", "body": "@Charles - can't you also use \"[System.Runtime.CompilerServices.CallerLineNumber] int line = 0\" so it would insert line number automatically?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T21:23:53.617", "Id": "467279", "Score": "0", "body": "@yob he wants the line number of the csv file that is being parsed as part of the error message not a code line number. I wouldn't put this example method in code as I'm sure there are better ways to make it more elegant but hard to know what that is without the surrounding code" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T16:53:25.517", "Id": "238258", "ParentId": "238255", "Score": "2" } } ]
{ "AcceptedAnswerId": "238258", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T16:07:22.903", "Id": "238255", "Score": "2", "Tags": [ "c#", "casting" ], "Title": "Parsing csv tokens as doubles and identifying which threw FormatException" }
238255
<p>I am implementing recursive backtracking algorithm for sudoku. Below is the code to create board with random filling. I wonder if I can make it better in any terms of readable coding especially validation methods. in Board class. </p> <pre><code>public class Board { private int[][] board; public final static int SIZE = 9; public Board() { create(); } public int[][] getBoard() { return board; } private void create() { int openspots = 20; board = new int[SIZE][SIZE]; Random rand = new Random(); int random, randomrow, randomcolumn; while (openspots-- &gt; 0) { random = rand.nextInt(SIZE) + 1; randomrow = rand.nextInt(SIZE); randomcolumn = (rand.nextInt(SIZE)); if (board[randomrow][randomcolumn] == 0) { board[randomrow][randomcolumn] = random; int count = 0; while (!isValid(randomrow, randomcolumn)) { if (count++ == 9) { board[randomrow][randomcolumn] = 0; openspots++; break; } random = rand.nextInt(SIZE) + 1; board[randomrow][randomcolumn] = random; } } } } public void printBoard() { for (int row = 0; row &lt; SIZE; row++) { for (int column = 0; column &lt; SIZE; column++) { System.out.print(board[row][column] + " "); } System.out.println(); } } public boolean isValid(int row, int column) { return isValidRow(row) &amp;&amp; isValidColumn(column) &amp;&amp; isValidBlock(row, column); } private boolean isValidRow(int row) { if (row &gt; 8 || row &lt; 0) throw new IllegalArgumentException("Row must be between 0 and " + (SIZE - 1) + " inclusive!"); Set&lt;Integer&gt; set = new HashSet&lt;&gt;(); for (int i = 0; i &lt; SIZE; i++) { if (board[row][i] != 0 &amp;&amp; set.contains(board[row][i])) { return false; } else { set.add(board[row][i]); } } return true; } private boolean isValidColumn(int column) { if (column &gt; 8 || column &lt; 0) throw new IllegalArgumentException("Column must be between 0 and " + (SIZE - 1) + " inclusive!"); Set&lt;Integer&gt; set = new HashSet&lt;&gt;(); for (int i = 0; i &lt; SIZE; i++) { if (board[i][column] != 0 &amp;&amp; set.contains(board[i][column])) { return false; } else { set.add(board[i][column]); } } return true; } private boolean isValidBlock(int row, int column) { if (column &gt; 8 || column &lt; 0) throw new IllegalArgumentException("Column must be between 0 and " + (SIZE - 1) + " inclusive!"); int blockrow = (row / 3) * 3; int blockcolumn = (column / 3) * 3; Set&lt;Integer&gt; set = new HashSet&lt;&gt;(); for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 3; j++) { if (board[blockrow + i][blockcolumn + j] != 0 &amp;&amp; set.contains(board[blockrow + i][blockcolumn + j])) { return false; } else { set.add(board[blockrow + i][blockcolumn + j]); } } } return true; } } </code></pre> <p>The one below is the solver class which has the main algorithm to solve sudoku. </p> <pre><code>public class Solver { public boolean solve(Board board) { int[][] boardarr = board.getBoard(); for (int i = 0; i &lt; board.SIZE; i++) { for (int j = 0; j &lt; board.SIZE; j++) { if (boardarr[i][j] == 0) { for (int k = 1; k &lt;= board.SIZE; k++) { boardarr[i][j] = k; if (board.isValid(i,j) &amp;&amp; solve(board)) { return true; } boardarr[i][j] = 0; } return false; } } } return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:16:03.300", "Id": "467321", "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)*." } ]
[ { "body": "<h2>Object Orientated Programming</h2>\n\n<p>you don't use object orientated programming! that would clean up the code in a large scale</p>\n\n<pre><code>public class Board {\n //private int[][] board; primitive obsession - use objects instead\n private Field[][] fields;\n private Column[] columns;\n private Row[] rows;\n private Block[] blocks;\n public final static int SIZE = 9; \n\n ... \n}\n</code></pre>\n\n<p>you could provide the proper methods for the field - so you could easily represent the field - instead of trying to interpret an <code>int</code> value.</p>\n\n<p>you could provide methods that are specific for these objects - you could even define an interface for common code, like <code>isFieldValid(Field candidate)</code> for <code>Row</code>, <code>Column</code> and <code>Block</code> </p>\n\n<h2>Naming</h2>\n\n<p>consider these names and you might find better</p>\n\n<pre><code>Random rand = new Random();\nint random, randomrow, randomcolumn;\n</code></pre>\n\n<p>maybe it would be </p>\n\n<pre><code>Field candidate;\n</code></pre>\n\n<p>again here, in <em>Java</em> we don't use the <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\"><em>hungarian notation</em></a> and name a variable by it's type:</p>\n\n<pre><code>//int[][] boardarr = board.getBoard();\nint[][] board = board.getBoard(); //would be better\nField[][] fields = board.getFields(); //even more better\n</code></pre>\n\n<h2>Data Structure</h2>\n\n<p>if you would use Objects for your Sudoku-Solver you could re-use values (here an example snippet for <code>Block</code>)</p>\n\n<pre><code>class Block {\n final private Set&lt;Field&gt; fields = new HashSet&lt;&gt;();\n\n boolean isFieldValid(Field field) {\n //Set&lt;Integer&gt; set = new HashSet&lt;&gt;(); we already have such set \n //and don't need to create a new one whenever we check\n return !fields.contains(field);\n }\n}\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>you already provide a <code>SIZE = 9</code> constant - so why don't you use a proper one for the block size?</p>\n\n<pre><code>int blockrow = (row / 3) * 3;\nint blockcolumn = (column / 3) * 3;\n</code></pre>\n\n<h2>Testing</h2>\n\n<p>i assume you provide enough tests but just don't put these in the question</p>\n\n<h2>Summary</h2>\n\n<p>very nice piece of code - i'm glad you have posted it here! The algorithm seems straight forward, i like it! The OO-thing is the only flaw here. I would appreciate if you would provide another question with applied OOP!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:17:43.097", "Id": "467301", "Score": "0", "body": "Regarding the solving algorithm, the Column, Row and Block classes are essentially the same. They are collections of <SIZE> elements with the restriction that any given number can ocur exactly once in the collection. The order of the Fields inside the collections is meaningful mainly for presentation only. Also, each Field exists in three collections simultaneously. This symmetry is something that can be taken advantage of when writing the algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:29:39.163", "Id": "467303", "Score": "0", "body": "@TorbenPutkonen you are totally correct. I had in mind that these Objects would be used in further context: `Panel.highLight(Row row);` or `ColumnAdviser.showHint(Column colum);` but using OOP they can be designed that they have one parent class that implements the `checkField(Field f)` interface... - but **regarding the solving algortihm** that is totally overkill and can be reduced! very right!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:04:11.150", "Id": "467319", "Score": "0", "body": "thank you so much for the reply. I made some improvemnts in the code according to your advice. (made a parent board class for another board games like n-queens) Can you check again? I cannot figure out Field thing as it complicates things" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:26:06.117", "Id": "467323", "Score": "0", "body": "as mentioned please ask another question! i think we're all keen on seeing your progress!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T06:26:12.237", "Id": "238289", "ParentId": "238263", "Score": "4" } }, { "body": "<p>A small side note: in <code>create()</code>, you wrote</p>\n\n<pre><code>int openspots = 20;\n// ...\nwhile (openspots-- &gt; 0) {\n// ...\n}\n</code></pre>\n\n<p>While it looks clean, it's weird to read and should probably be written as a <code>for</code>-loop. This way, you also reduce the scope of <code>openspots</code> to inside the loop and don't clutter up your namespace inside of <code>create()</code>. Also, the twenty seems a bit like a <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">magic number</a> to me, you shold probably put it into a constant. This would make the loop look something like this:</p>\n\n<pre><code>for (int openspots = CONST - 1; openspots &gt;= 0; openspots--) {\n// ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:37:54.470", "Id": "467448", "Score": "0", "body": "that had hit me as well - good one =) +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:19:18.897", "Id": "238361", "ParentId": "238263", "Score": "1" } } ]
{ "AcceptedAnswerId": "238289", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T18:57:41.417", "Id": "238263", "Score": "4", "Tags": [ "java", "recursion" ], "Title": "Sudoku solver recursive backtrack in Java" }
238263
<p>I wanted to make a library thing which provides specific extensions for collections/collection-like containers in kotlin:</p> <pre><code>fun &lt;T&gt; Collection&lt;T&gt;.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun String.extendEntries(length: Int) = this.toList().extendEntries(length) fun &lt;T&gt; Array&lt;T&gt;.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun CharArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun BooleanArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun DoubleArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun IntArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun LongArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun FloatArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun ByteArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } fun ShortArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } } </code></pre> <p>Is the above a good way to do it if I want to cover arrays?</p> <p>Exampe usage:</p> <blockquote> <pre><code>val a = intArrayOf(1, 2, 3) println(a.extendEntries(5)) </code></pre> </blockquote> <p>Outputs:</p> <blockquote> <pre><code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3] </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T21:59:28.997", "Id": "485978", "Score": "0", "body": "What if you instead did `a.flatMap { it.repeat(5) }` ? it's only 8 characters longer, but much shorter then `flatMap{ x -> List(5) { x } }`" } ]
[ { "body": "<p>Sadly, yes. If you want users of your library to write <code>intArrayOf(1, 2, 3).extendEntries(5)</code> then this is how it is done in Kotlin.</p>\n\n<p>In fact, the Kotlin source code contains methods similar to it, with a specific function for each type of array: (<code>kotlin.collections._Arrays.kt</code>)</p>\n\n<pre><code>/**\n * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.\n */\npublic inline fun &lt;R&gt; ShortArray.flatMap(transform: (Short) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {\n return flatMapTo(ArrayList&lt;R&gt;(), transform)\n}\n\n/**\n * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.\n */\npublic inline fun &lt;R&gt; IntArray.flatMap(transform: (Int) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {\n return flatMapTo(ArrayList&lt;R&gt;(), transform)\n}\n\n/**\n * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.\n */\npublic inline fun &lt;R&gt; LongArray.flatMap(transform: (Long) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {\n return flatMapTo(ArrayList&lt;R&gt;(), transform)\n}\n</code></pre>\n\n<p>However, Kotlin uses a generator to generate such files, see the README at <a href=\"https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib\" rel=\"nofollow noreferrer\">https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib</a></p>\n\n<p>In your case, you might consider just implementing <code>Iterable&lt;T&gt;.extendEntries</code> as all of these specific types of arrays can be transformed to an <code>Iterable&lt;T&gt;</code> using the Kotlin stdlib <code>.asIterable</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:18:30.267", "Id": "467420", "Score": "1", "body": "see also: \nhttps://discuss.kotlinlang.org/t/why-do-the-primitive-array-classes-need-to-be-exposed/1455?u=tieskedh" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T19:35:16.947", "Id": "238265", "ParentId": "238264", "Score": "2" } } ]
{ "AcceptedAnswerId": "238265", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T19:08:31.263", "Id": "238264", "Score": "1", "Tags": [ "kotlin" ], "Title": "Make extensions for kotlin arrays" }
238264
<p>I have a table in Hadoop that looks like this (with up to hundreds of columns and millions of rows):</p> <pre><code>+--------+-----------+--------+-----+ | field0 | field1 | field2 | ... | +--------+-----------+--------+-----+ | 0.66 | 0.4364153 | 0.31 | | | 0.28 | 0.281724 | -1 | | | 0.48 | 0.4210872 | 0.58 | | | 0.44 | 0.4381265 | 0.59 | | | 0.5 | 0.3220857 | 0.65 | | | 0.42 | 0.287387 | -1 | | | 0.49 | 0.2775216 | -1 | | | 0.63 | 0.4347056 | 0.54 | | | 0.43 | 0.4501439 | 0.54 | | | 0.39 | 0.4312909 | 0.66 | | | 0.41 | 0.4432687 | 0.56 | | | 0.71 | 0.2678676 | -1 | | | 0.43 | 0.270604 | -1 | | | 0.51 | 0.2888133 | -1 | | | 0.6 | 0.270604 | -1 | | | 0.68 | 0.4177005 | 0.67 | | | ... | ... | ... | ... | +--------+-----------+--------+-----+ </code></pre> <p>The values inside the fields are always between 0 and 1 (inclusive), -1, or blank (empty string). I want to find the minimum and maximum cutoff points when quantiling the data (with each column quantiled independently). (You can read up on quantiling here <a href="https://en.wikipedia.org/wiki/Quantile" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Quantile</a>)</p> <p>I have a script which generates Hive SQL code like the following (using n=9 as an example). Is there any way to optimize this SQL code so that it does not require so many joins? Each join requires a separate Hadoop MapReduce job (and due to environmental issues, we cannot enable the parallelizable feature which enables multiple SQL jobs to run at once).</p> <pre><code>select outer0.nonile_field0 as nonile, outer0.min_field0, outer0.max_field0, outer1.min_field1, outer1.max_field1, outer2.min_field2, outer2.max_field2, ... from ( select middle0.nonile_field0, min(middle0.field0) as min_field0, max(middle0.field0) as max_field0 from ( select inner0.field0, ntile(9) over (order by inner0.field0) as nonile_field0 from ( select repo.field0 from my_table as repo where repo.field0 &gt;= 0 and repo.field != "" ) as inner0 ) as middle0 group by middle0.nonile_field0 ) as outer0 inner join ( select middle1.nonile_field1, min(middle1.field1) as min_field1, max(middle1.field1) as max_field1 from ( select inner1.field1, ntile(9) over (order by inner1.field1) as nonile_field1 from ( select repo.field1 from my_table as repo where repo.field1 &gt;= 0 and repo.field1 != "" ) as inner1 ) as middle1 group by middle1.nonile_field1 ) as outer1 on outer0.nonile_field0 = outer1.nonile_field1 ... order by nonile </code></pre> <p>The output of the query will look like this (for example):</p> <pre><code>+--------+--------------+--------------+--------------+--------------+ | nonile | min_field0 | max_field0 | min_field1 | max_field1 | +--------+--------------+--------------+--------------+--------------+ | 1 | 0 | 0.27 | 0.09892169 | 0.2505006 | | 2 | 0.27 | 0.33 | 0.2505006 | 0.2900893 | | 3 | 0.33 | 0.37 | 0.2900893 | 0.3300329 | | 4 | 0.37 | 0.41 | 0.3300329 | 0.3687165 | | 5 | 0.41 | 0.46 | 0.3687165 | 0.4048001 | | 6 | 0.46 | 0.5 | 0.4048001 | 0.4399964 | | 7 | 0.5 | 0.55 | 0.4399964 | 0.4828034 | | 8 | 0.55 | 0.62 | 0.4828034 | 0.5445772 | | 9 | 0.62 | 0.98 | 0.5445772 | 0.7808363 | +--------+--------------+--------------+--------------+--------------+ </code></pre> <p>Note that I've manually edited the field and table names so that they are generic for this post, but the code should still be correct.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T19:59:43.873", "Id": "238266", "Score": "1", "Tags": [ "sql", "join", "hiveql" ], "Title": "Creating Quantile Cutoffs using SQL Hive" }
238266
<p>I am using Java 8. I haven't found another question that fits mine exactly, and I've come across some conflicting information on best practices with what I'm trying to do.</p> <p>I'm creating a POJO which is essentially a business object - to be returned by my API - that will have its fields initialized from another object.</p> <p>I'm using the <a href="https://projectlombok.org/features/Data" rel="nofollow noreferrer"><code>@Data</code></a> lombok annotation to generate the getters/setters/toString.</p> <p>I'm wondering which of the following options would align with best practices:</p> <p><strong>Note: It is guaranteed that <code>authUser</code> will be not null when calling the <code>User</code> constructor.</strong></p> <p><strong>1. Null-checks with if-statements and default field values</strong></p> <pre><code>@Data public class User { private String userId = ""; private String fullName = ""; private String email = ""; private Set&lt;String&gt; roles = Collections.emptySet(); public User(AuthUser authUser, Set&lt;String&gt; roles) { if (authUser.getUserId() != null) { this.userId = authUser.getUserId(); } if (authUser.getFullName() != null) { this.fullName = authUser.getFullName(); } if (authUser.getEmail() != null) { this.email = authUser.getEmail(); } if (roles != null) { this.roles = roles; } } } </code></pre> <p>I feel like this is a safe/generic way to do this, and I could store the values retrieved from the getters to local variables so the get calls aren't redundant.</p> <p><strong>2. Null-checks using ternaries with redundant get calls</strong></p> <pre><code>@Data public class User { private String userId; private String fullName; private String email; private Set&lt;String&gt; roles; public User(AuthUser authUser, Set&lt;String&gt; roles) { this.userId = authUser.getUserId() == null ? "" : authUser.getUserId(); this.fullName = authUser.getFullName() == null ? "" : authUser.getFullName(); this.email = authUser.getEmail() == null ? "" : authUser.getEmail(); this.roles = roles == null ? Collections.emptySet() : roles; } } </code></pre> <p>The purpose of this is to reduce code-cluttering, but I believe <em>Clean Code</em> argues against ternaries, so I'd probably not prefer this option for the sake of readability.</p> <p><strong>3. Null-checks with Optionals without redundant get calls</strong></p> <pre><code>@Data public class User { private String userId; private String fullName; private String email; private Set&lt;String&gt; roles; public User(AuthUser authUser, Set&lt;String&gt; roles) { this.userId = Optional.ofNullable(authUser.getUserId()).orElse(""); this.fullName = Optional.ofNullable(authUser.getFullName()).orElse(""); this.email = Optional.ofNullable(authUser.getEmail()).orElse(""); this.roles = Optional.ofNullable(roles).orElse(Collections.emptySet()); } } </code></pre> <p>The purpose of this is to reduce code-cluttering and redundant get calls without creating local variables in order to remove that redundancy. I think this is preferable to ternaries but am not sure.</p> <p><strong>4. Null-checks with Apache <a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#defaultString-java.lang.String-" rel="nofollow noreferrer">StringUtils.defaultString</a> and <a href="https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#emptyIfNull-java.util.Collection-" rel="nofollow noreferrer">CollectionUtils.emptyIfNull</a></strong></p> <pre><code>@Data public class User { private String userId; private String fullName; private String email; private Set&lt;String&gt; roles; public User(AuthUser authUser, Set&lt;String&gt; roles) { this.userId = StringUtils.defaultString(authUser.getUserId()); this.fullName = StringUtils.defaultString(authUser.getFullName()); this.email = StringUtils.defaultString(authUser.getEmail()); this.roles = CollectionUtils.emptyIfNull(roles); } } </code></pre> <p>This a little shorter than using <code>Optional</code>s, but I feel like using native Java is preferable to third-party libraries (<code>ApacheUtils</code> is already included as a dependency).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T07:40:45.150", "Id": "467299", "Score": "5", "body": "I get the feeling that you're going out of your way to figure out ways to not need null-values. Can you explain why you do not want to use null-values to represent a field that does not have a value set? Null values or, null checks for that matter, are not a problem. The problem is not knowing, on a compiler level, if a method returns null (Optionals were designed to solve that). Lombok does not have an annotation for optional getters so you will have to ditch it (and that is not a big loss at all)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:47:54.510", "Id": "467305", "Score": "0", "body": "Another way to avoid invoking an accessor more than once would be `if (null == (attribute = parameter.getAttribute())) attribute = default;`." } ]
[ { "body": "<p>Multiple facets to this answer:</p>\n\n<h2>First, direct responses to the given approaches</h2>\n\n<h3>1.</h3>\n\n<p>Initializing fields with a value, only to reinitialize them in a constructor is not useful - skimming the class, which will be done in time, would lead to confusion. When initializing values with defaults, it would be better to modify them using setters.\nThe empty String may, however, not be a good default. A Constructor is supposed to instantiate an Object in a way that it can be used - however, a user without a user id appears relatively useless.</p>\n\n<h3>2.</h3>\n\n<p>This approach is better, but the concepts are not cleanly understood.\nFirst off, Clean Code does not argue against ternaries in general. Ternary operations can be very useful, if utilized correctly. The way you use them here is <strong>not</strong> a good way to use a ternary. This however is</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static &lt;T&gt; T valueOrDefault(T value, T default) {\n return value != null\n ? value\n : default;\n}\n</code></pre>\n\n<p>This is a ternary which is instantly understandable, as it is entirely alone, and formatted in a way that it makes understanding easier.\nThis is also a suggestion to use here, as declaring this method within the User class allows for the following constructor:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public User(AuthUser authUser, Set&lt;String&gt; roles) {\n this.userId = valueOrDefault(authUser.getUserId(), \"\");\n // omitted\n}\n</code></pre>\n\n<p>While this is very readable in both constructor and utility method, it is also technically overengineered here, as the use of generics is not necessary in this case, it merely removes the need to declare two extremely similar functions.</p>\n\n<h3>3.</h3>\n\n<p>Do not use <code>Optional</code> like this. Optional has a very specific and limited use, which is as a return type on specific methods and function calls.\nAlso, while this is one way to remove a redundant <code>get</code>-call, this also adds a rather large amount of unnecessary overhead, plus it is much less readable than the second approach.\nThis reduced readability and increased overhead in comprehension and execution remains even if the formatting in improved for readability.</p>\n\n<h3>4.</h3>\n\n<p>This is the most acceptable approach in general, however this is only true if the necessary dependencies are already present on the classpath. Adding <code>commons-lang</code> for null-checks only is, while technically adhering to the KISS principle, too much cost for effect.</p>\n\n<h2>Second: Considerations</h2>\n\n<p>Is this an Object or a data structure? Right now, it is <em>technically speaking</em> both, which is inherently problematic. See <a href=\"https://stackoverflow.com/questions/23406307/whats-the-difference-between-objects-and-data-structures\">here</a> for <em>some</em> explanations, the mentioned book would help you more though.</p>\n\n<p>Considering the construction approach: the constructor seems to copy fields from object a, which is also a kind of user, and append a <code>Set</code> of <code>String</code>s to the object. So it is neither a copy constructor nor a plain constructor. This is in so far confusing that, when described from a more distanced view,\n<em>the User is instantiated by passing a User and Roles. The Passed User is not present in the User Object, but some fields of it are.</em>\nIf you find this sentence confusing: people who read your code will most likely think along these lines. At least, I do, as I always try to simplify as much as possible.</p>\n\n<p>As this kind of construction CAN be confusing, it may be useful to create a Mapper or Converter accepting <code>AuthUser</code> and <code>Set&lt;String&gt;</code> and returning <code>User</code>. This would separate the data structure from the logic, and it would allow more validation logic to happen without bloating the user object.</p>\n\n<p>This would also allow the user to be a <code>@Value</code>-class, meaning no setters and all fields final, which makes this object almost immutable and easy to share - almost as the <code>Set</code> still can be modified.</p>\n\n<h2>Third: the <code>null</code>-problem</h2>\n\n<p>Is <code>null</code> really the same as the empty String in case of id, name and email? And, are \"no roles\" the same as <code>null</code>?\n<code>null</code> in java is, despite the dreaded <code>NullPointerException</code>, a very useful value, and replacing it with \"I don't want to do null check\"-defaults is rarely a good idea.</p>\n\n<p>It would actually be better practice to not modify the values at all and take them at face value, as that allows you to determine if there was an error during authentication or data binding (as data binding errors often lead to empty strings, while authentication errors fail to instantiate objects correctly).</p>\n\n<p>Try to incorporate <code>null</code>-values into your application as valid values - for example as validation values, or as markers for errors.</p>\n\n<p>Also, for good measure, <strong>never</strong> allow or return <code>null</code> where <code>Collection</code>s, <code>Map</code>s, <code>array</code>s or other similar objects are expected, as effectively no one expects these to be <code>null</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T15:09:05.270", "Id": "467345", "Score": "0", "body": "You're right -- I was over-concerned with null-checking because I was using `JSONObject` before which complains when creating a null property. When switching to a business object, I carried over the same concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T15:37:10.270", "Id": "467350", "Score": "0", "body": "I ended up making a copy constructor that took an `AuthUser` and `roles` which returns both, which makes more sense as you pointed out. I was overly concerned about only returning the fields I want for the api but it doesn't actually matter, and the method I was going about it didn't make sense. Thanks for the help!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T23:49:33.990", "Id": "238275", "ParentId": "238268", "Score": "7" } } ]
{ "AcceptedAnswerId": "238275", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T20:15:16.383", "Id": "238268", "Score": "2", "Tags": [ "java", "comparative-review", "optional" ], "Title": "Best practice to initialize instance variables for a POJO when values are null" }
238268
<p>My goal is to scrape the no. 1 suggestion of the suggestion list on <a href="https://finance.yahoo.com" rel="nofollow noreferrer">https://finance.yahoo.com</a> for any entry. If there is no suggestion the code should write <code>f"nan_{what_ever_the_entry_was}"</code>.</p> <p>As basis I used the solution from <a href="https://stackoverflow.com/questions/50355120/how-to-scrape-the-yahoo-finance-search-auto-suggestion-result-with-selenium-pyth/60496531#60496531">https://stackoverflow.com/questions/50355120/how-to-scrape-the-yahoo-finance-search-auto-suggestion-result-with-selenium-pyth/60496531#60496531</a>.</p> <p>Since I want to scrape the first suggestion for various values in a list, I created a for-loop. If I had kept the third to last line of the original solution</p> <pre><code>WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))).send_keys("goog") </code></pre> <p>the function won't work properly, because the elements are already loaded for the second loop. That's why I added two <code>time.sleep()</code> blocks instead. Now the function works well.</p> <h3>Question</h3> <p>The <code>time.sleep()</code> part does not seem very <em>elegant</em> to me. Is this the best way or are there more elegant/pythonic ways to resolve the problem?</p> <h3>Input</h3> <pre><code>from typing import List import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") options.add_argument('headless') def get_ticker_symbols(isin_list: List) -&gt; List: driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Program Files (x86)\Google\Chrome\Chromedriver\chromedriver.exe') driver.get('https://finance.yahoo.com/') driver.find_element_by_xpath("//button[@type='submit' and @value='agree']").click() ticker_list=[] for isin in isin_list: try: WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))).send_keys(f"{isin}") time.sleep(1) ticker = driver.find_element_by_xpath('(//div[@class="_0ea0377c _4343c2a0 _50f34a35"])[1]').text except: ticker = f'nan_{isin}' time.sleep(0.1) finally: ticker_list.append(ticker) driver.find_element_by_xpath("//input[@name='yfin-usr-qry']").clear() return ticker_list get_ticker_symbols(['GB00BD2ZT390','bmw','dasdas', 'nike', 'GB00BK8FL363']) </code></pre> <h3>Output</h3> <pre><code>['GPH.L', 'BMW.DE', 'nan_dasdas', 'NKE', 'HZD.L'] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T14:03:58.110", "Id": "467466", "Score": "0", "body": "Whoever is voting to close this question, please leave a comment stating why." } ]
[ { "body": "<h1><code>WebDriverWait</code></h1>\n\n<p>Your intuition about <code>time.sleep()</code> not being ideal here is correct. A better alternative is to use the <a href=\"https://selenium-python.readthedocs.io/waits.html#explicit-waits\" rel=\"nofollow noreferrer\">Selenium <code>WebDriverWait</code> API</a> to wait for elements of interest to appear/disappear. More specifically,</p>\n\n<ul>\n<li>after entering a query in the query field, we want to wait for the list elements to show up in the DOM so we can retrieve the first element</li>\n<li>after clearing the query field, we want to wait for any of the aforementioned list elements to disappear from the DOM, as a sanity check to ensure we've reset the page to a state that is ready for our next query</li>\n</ul>\n\n<p>For waiting for the elements to show up in the DOM, we can use <a href=\"https://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.expected_conditions.presence_of_all_elements_located\" rel=\"nofollow noreferrer\"><code>presence_of_all_elements_located</code></a>:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>first_element = WebDriverWait(driver, 5).until(\n EC.presence_of_all_elements_located(\n (By.XPATH, \"//div[@class='_0ea0377c _4343c2a0 _50f34a35']\")\n )\n)[0]\nticker = first_element.text\n</code></pre>\n\n<p>For waiting for any of the above elements to disappear from the DOM, we can use <a href=\"https://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.expected_conditions.staleness_of\" rel=\"nofollow noreferrer\"><code>staleness_of</code></a> or <a href=\"https://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.expected_conditions.invisibility_of_element_located\" rel=\"nofollow noreferrer\"><code>invisibility_of_element_located</code></a>:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>WebDriverWait(driver, 5).until(EC.staleness_of(first_element))\n</code></pre>\n\n<p></p>\n\n<pre class=\"lang-python prettyprint-override\"><code># also works, but we're repeating ourselves a bit here\nWebDriverWait(driver, 5).until(\n EC.invisibility_of_element_located(\n (By.XPATH, \"//div[@class='_0ea0377c _4343c2a0 _50f34a35']\")\n )\n)\n</code></pre>\n\n<h1>Query field: retrieve once then reuse</h1>\n\n<blockquote>\n <pre class=\"lang-python prettyprint-override\"><code>for isin in isin_list:\n try:\n WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, \"//input[@name='yfin-usr-qry']\"))).send_keys(f\"{isin}\")\n</code></pre>\n</blockquote>\n\n<p>We only need to wait for the search query field to become clickable once. So we can move the <code>WebDriverWait</code> line outside of the loop and save its return value (reference to the query field element) in <code>query_field</code>:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>query_field = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable((By.XPATH, \"//input[@name='yfin-usr-qry']\"))\n)\nfor query in queries:\n try:\n query_field.send_keys(query)\n # ...\n</code></pre>\n\n<h1>Incorrect assumption about modal always appearing</h1>\n\n<blockquote>\n <pre class=\"lang-python prettyprint-override\"><code>driver.find_element_by_xpath(\"//button[@type='submit' and @value='agree']\").click()\n</code></pre>\n</blockquote>\n\n<p>This appears to handle a pop-up modal by clicking past it, but I don't think the modal shows up all the time. When I ran the original script the above line threw a <code>NoSuchElementException</code>.</p>\n\n<p>To handle the case when the modal doesn't appear, ignore <code>NoSuchElementException</code> when it is raised from that line:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>try:\n driver.find_element_by_xpath(\n \"//button[@type='submit' and @value='agree']\"\n ).click()\nexcept NoSuchElementException:\n pass\n</code></pre>\n\n<h1>Use <code>None</code> to represent the absence of a value</h1>\n\n<blockquote>\n <p>If there is no suggestion the code should write <code>f\"nan_{what_ever_the_entry_was}\"</code>.</p>\n</blockquote>\n\n<p>I would highly recommend against doing this. Instead, use <code>None</code> to represent the absence of a value (see <a href=\"https://docs.python.org/3/library/typing.html#typing.Optional\" rel=\"nofollow noreferrer\"><code>typing.Optional</code></a>). </p>\n\n<p><code>get_ticker_symbols</code> would then return a <code>List[Optional[str]]</code>, which is a clear way of expressing in the function signature that it is possible for a search query to return an \"empty\" result.</p>\n\n<p>As for the current function signature,</p>\n\n<blockquote>\n <pre class=\"lang-python prettyprint-override\"><code>def get_ticker_symbols(isin_list: List) -&gt; List:\n</code></pre>\n</blockquote>\n\n<p>this can be improved by specifying the types of elements in each list:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def get_ticker_symbols(queries: List[str]) -&gt; List[Optional[str]]:\n</code></pre>\n\n<p>Also, <code>isin_list</code> is not a very descriptive name and it almost sounds like a boolean, which is misleading, so I'd go with something like <code>queries</code> instead.</p>\n\n<h1>Specify the exceptions you are handling</h1>\n\n<p>Avoid using bare <code>except</code> clauses, which catch all exceptions and can obscure/hide real issues or bugs. Instead, specify the exception you are handling:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>try:\n # some code that could throw a `TimeoutException`,\n # e.g. `presence_of_all_elements_located`\nexcept TimeoutException:\n # ...\n</code></pre>\n\n<h1>Close resources after use</h1>\n\n<p>It's a good idea to call <code>close()</code> or <code>quit()</code> on the WebDriver to exit the browser once we're done using it. That said, if we invoke the WebDriver as a context manager, we don't have to worry about this:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>with webdriver.Chrome(options=options) as driver:\n driver.get(\"https://finance.yahoo.com/\")\n # ...\n</code></pre>\n\n<p>Selenium allows us to invoke the WebDriver as a context manager as shown above, which means we don't need to call <code>driver.close()</code> or <code>driver.quit()</code> explicitly because it will be done for us when the flow of execution leaves the indented block.</p>\n\n<h1>Refactored version</h1>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nfrom typing import List, Optional\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument(\"disable-infobars\")\noptions.add_argument(\"--disable-extensions\")\noptions.add_argument(\"headless\")\n\n\ndef get_ticker_symbols(queries: List[str]) -&gt; List[Optional[str]]:\n with webdriver.Chrome(options=options) as driver:\n driver.get(\"https://finance.yahoo.com/\")\n\n try:\n driver.find_element_by_xpath(\n \"//button[@type='submit' and @value='agree']\"\n ).click()\n except NoSuchElementException:\n pass\n\n query_field = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable(\n (By.XPATH, \"//input[@name='yfin-usr-qry']\")\n )\n )\n ticker_list = []\n for query in queries:\n try:\n query_field.send_keys(query)\n first_element = WebDriverWait(driver, 5).until(\n EC.presence_of_all_elements_located(\n (\n By.XPATH,\n \"//div[@class='_0ea0377c _4343c2a0 _50f34a35']\",\n )\n )\n )[0]\n ticker = first_element.text\n except TimeoutException:\n ticker = None\n\n ticker_list.append(ticker)\n # web_element.clear() doesn't fire any keyboard events, and\n # as a result the change to the text field isn't registered\n # as we would expect. So as a workaround, we delete the query\n # via Keys.BACKSPACE\n query_field.send_keys(Keys.BACKSPACE * len(query))\n WebDriverWait(driver, 5).until(EC.staleness_of(first_element))\n\n return ticker_list\n\n\nif __name__ == \"__main__\":\n queries = [\"GB00BD2ZT390\", \"bmw\", \"dasdas\", \"nike\", \"GB00BK8FL363\"]\n print(get_ticker_symbols(queries))\n</code></pre>\n\n<hr>\n\n<h1>Alternative solution: Use undocumented API</h1>\n\n<p>This is a bit out of scope for this code review, but I do think it deserves a mention. Simply put, there is an even better way of doing all of this without using Selenium or other web scraping libraries.</p>\n\n<p>Using something like Chrome Developer Tools, we can track the XHRs made when typing in the search field and figure out which API call is providing the data we care about.</p>\n\n<p>In this case it's an <a href=\"https://developer.yahoo.com/api/\" rel=\"nofollow noreferrer\">undocumented API</a> <code>https://query1.finance.yahoo.com/v1/finance/search</code> which we can call directly with <a href=\"https://requests.readthedocs.io/\" rel=\"nofollow noreferrer\"><code>requests</code></a>:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport requests\n\nfrom typing import Any, Dict, Optional, List\n\n\ndef get_ticker_symbols(queries: List[str]) -&gt; List[Optional[str]]:\n def get_params(query: str) -&gt; Dict[str, Any]:\n return {\n \"q\": query,\n \"lang\": \"en-US\",\n \"region\": \"US\",\n \"quotesCount\": 1,\n \"newsCount\": 0,\n \"enableFuzzyQuery\": False,\n }\n\n ticker_list = []\n with requests.Session() as session:\n for query in queries:\n response = session.get(\n \"https://query1.finance.yahoo.com/v1/finance/search\",\n params=get_params(query),\n )\n response.raise_for_status()\n quotes = response.json()[\"quotes\"]\n ticker_symbol = quotes[0][\"symbol\"] if quotes else None\n ticker_list.append(ticker_symbol)\n\n return ticker_list\n\n\nif __name__ == \"__main__\":\n queries = [\"GB00BD2ZT390\", \"bmw\", \"dasdas\", \"nike\", \"GB00BK8FL363\"]\n print(get_ticker_symbols(queries))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T22:10:29.803", "Id": "468612", "Score": "1", "body": "+1 for going the extra mile. I too have noticed that many Ajax-powered sites make background calls to undocumented APIs, usually returning JSON. So you could as well go straight to the source. Both the API and the website are subject to change without notice at any time anyway. Checking the website with your browser's developer tools is a must-do before you embark on that type of development." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T20:55:05.097", "Id": "469137", "Score": "0", "body": "Thank you very much, especially for the add-on, which is extremely faster. That was, what I originally was looking for." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:08:06.520", "Id": "238924", "ParentId": "238270", "Score": "4" } } ]
{ "AcceptedAnswerId": "238924", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T21:18:59.393", "Id": "238270", "Score": "3", "Tags": [ "python", "python-3.x", "search", "selenium" ], "Title": "Elegant Method for Sleeping with Selenium Webscraper" }
238270
<p>After the feedback I got on my <a href="https://codereview.stackexchange.com/questions/238000/o-o-style-palindrome-checker">previous question</a>, I decided to try one more program to see if I understand O.O.P. The idea for this is also based off the project I am working on im my class for this semester which is to make an interactive school tour. </p> <p>This program just has you make a bunch of teacher instances and then prints them all out.</p> <pre class="lang-py prettyprint-override"><code>class Teacher: def __init__(self, name, subject, room_number): self.name = name self.subject = subject self.room_number = room_number def print_info(self): return self.name, self.subject, self.room_number def instagator(teachers: list) -&gt; list: """Creates a version of the teacher class""" print("") name = input("Please enter a teachers name: ") subject = input("Please enter that teachers subject: ") room_number = input("Please enter what room that teacher teaches in: ") # Makes the varible that holds the instance names after the teacher globals()[name] = Teacher(name, subject, room_number) teachers.append(globals()[name]) return teachers teachers = [] print("Please enter the name of 10 teachers, the subject they teach, and the room they teach that subject in.") for _ in range(10): teachers = instagator(teachers) print("\n") for teacher in teachers: info = teacher.print_info() print(f"{info[0].capitalize()} teaches {info[1]} in room {info[2]}. \n") </code></pre> <p>As with before I just want to know if there is anything wrong with my approach to O.O.P. as I still have very little idea of what I am doing.</p>
[]
[ { "body": "<ol>\n<li><p>Is the user of your <code>Teacher</code> class supposed to be able to modify the <code>name</code>, <code>subject</code>, and <code>room_number</code> attributes after they're set? If not, make them private by putting a <code>_</code> at the start of those names.</p></li>\n<li><p>Python objects have a magic method <code>__repr__</code> that turns them into a string for printing. That would be a good place to put your formatting logic.</p></li>\n<li><p>I don't know what this stuff with <code>globals</code> is trying to do, but as a general rule you should not touch <code>globals</code>.</p></li>\n<li><p>Your <code>instagator</code> function says that it creates a <code>Teacher</code>, but it also takes a list of the existing teachers, appends to it, and then returns it. Try to have your functions do one obvious thing instead of doing multiple non-obvious things. </p></li>\n</ol>\n\n<p>If your <code>instagator</code> function just does the one thing it says it does (creates a <code>Teacher</code>), and if you move the string formatting into the <code>__repr__</code> function instead of having an intermediate <code>print_info</code> that doesn't actually print anything, the code gets a bit simpler:</p>\n\n<pre><code>class Teacher:\n def __init__(self, name: str, subject: str, room_number: str):\n self._name = name\n self._subject = subject\n self._room_number = room_number\n\n def __repr__(self) -&gt; str:\n return f\"{self._name.capitalize()} teaches {self._subject} in room {self._room_number}.\"\n\n\ndef instagator() -&gt; Teacher:\n \"\"\"Creates a Teacher from user input.\"\"\"\n print(\"\")\n name = input(\"Please enter a teachers name: \")\n subject = input(\"Please enter that teachers subject: \")\n room_number = input(\"Please enter what room that teacher teaches in: \")\n return Teacher(name, subject, room_number)\n\n\nprint(\"Please enter the name of 10 teachers, the subject they teach, and the room they teach that subject in.\")\nteachers = [instagator() for _ in range(10)]\nprint(\"\\n\")\n\nfor teacher in teachers:\n print(teacher)\n</code></pre>\n\n<p>Note that since <code>instagator</code> returns a <code>Teacher</code> I can just use a simple list comprehension to build a list of all the <code>Teacher</code>s, one for each number in the <code>range</code>. And since I implemented <code>__repr__</code> I don't need to have multiple lines of code to build the string to print; I can just print the <code>teacher</code> directly and that will automagically turn into the formatted string that I want.</p>\n\n<p>I don't think it's great practice in general to have a constructor prompt for user input, but for a practice exercise like this I think it's fine to demonstrate how you can use a class to encapsulate all of the logic that pertains to building an object:</p>\n\n<pre><code>class Teacher:\n def __init__(self):\n \"\"\"Creates a Teacher from user input.\"\"\"\n print(\"\")\n self._name = input(\"Please enter a teachers name: \")\n self._subject = input(\"Please enter that teachers subject: \")\n self._room_number = input(\"Please enter what room that teacher teaches in: \")\n\n def __repr__(self) -&gt; str:\n return f\"{self._name.capitalize()} teaches {self._subject} in room {self._room_number}.\"\n\n\nprint(\"Please enter the name of 10 teachers, the subject they teach, and the room they teach that subject in.\")\nteachers = [Teacher() for _ in range(10)]\nprint(\"\\n\")\n\nfor teacher in teachers:\n print(teacher)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T01:56:29.993", "Id": "467288", "Score": "0", "body": "The globals() command is to make it so the name of the variable the instance is assigned to is the name of the teacher. I am not entirely sure how it works, but I could not find any better way of doing this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T03:36:25.063", "Id": "467293", "Score": "1", "body": "You should not do this at all. There's no need to have named variables for these values at the global scope, especially since you never do anything with those values after you've set them (that's why the purpose was unclear to me). Global variables in general should be avoided, and defining them dynamically in random places is almost never going to be a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T23:12:15.073", "Id": "467385", "Score": "2", "body": "You don't want to implement `__repr__`, you want to implement `__str__`. They are similar, but different. Roughly speaking: `__repr__` is designed for debugging, and perhaps serialization; `__str__` is for human-readable output. See [str -vs- repr](https://www.geeksforgeeks.org/str-vs-repr-in-python/)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T21:51:53.683", "Id": "238272", "ParentId": "238271", "Score": "7" } }, { "body": "<p>Maybe you have not gotten this far in your study, but there are actually solutions for this within OOP.</p>\n\n<p>Alternative constructors can be done in Python by <a href=\"https://www.geeksforgeeks.org/classmethod-in-python/\" rel=\"nofollow noreferrer\">using a <code>classmethod</code></a> (since function overloading is not so easy). Classmethods take as a first argument the class instead of an instance (customarily called <code>cls</code> instead of <code>self</code>) and return an instance of that class. You can create them by decorating a method with <code>@classmethod</code>.</p>\n\n<p>Keeping track of all instances created can be done by having a mutable class attribute which gets updated in the <code>__init__</code> method.</p>\n\n<p>In addition I also removed your <code>print_info</code> method and added a <code>__str__</code> method which prints what you need later, instead. The <code>__str__</code> method is called whenever you do <code>str(x)</code>, which happens internally also in the <code>print</code> function. The <code>__str__</code> and <code>__repr__</code> methods are similar, but not the same. The former is for when you want a nice human-readable visualization of the instance, and the latter should be a complete representation of the instance, ideally such that <code>eval(repr(x)) == x</code>. For more information <a href=\"https://www.geeksforgeeks.org/str-vs-repr-in-python/\" rel=\"nofollow noreferrer\">read this</a>.</p>\n\n<pre><code>class Teacher:\n all_teachers = {}\n\n def __init__(self, name, subject, room_number):\n self.name = name\n self.subject = subject\n self.room_number = room_number\n self.all_teachers[name] = self\n\n @classmethod\n def from_user(cls):\n \"\"\"Interactive creation of a teacher.\"\"\"\n print(\"\")\n name = input(\"Please enter a teachers name: \")\n subject = input(\"Please enter that teachers subject: \")\n room_number = input(\"Please enter what room that teacher teaches in: \")\n return cls(name, subject, room_number)\n\n def __str__(self):\n return f\"{self.name.capitalize()} teaches {self.subject} in room {self.room_number}\"\n\nif __name__ == \"__main__\":\n print(\"Please enter the name of 10 teachers, the subject they teach, and the room they teach that subject in.\")\n teachers = [Teacher.from_user() for _ in range(10)]\n\n for teacher in teachers:\n print(teacher)\n print()\n</code></pre>\n\n<p>The dictionary containing all teachers was not even needed, but you can access it via <code>Teacher.all_teachers</code> or <code>teacher.all_teachers</code>, where <code>teacher</code> is an instance.</p>\n\n<p>Instead I used a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a> to build a list of teachers.</p>\n\n<p>I also added a <a href=\"https://stackoverflow.com/q/419163/4042267\"><code>if __name__ == \"__main__\":</code></a> guard to allow importing from this script without it running.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:30:39.183", "Id": "238290", "ParentId": "238271", "Score": "3" } } ]
{ "AcceptedAnswerId": "238272", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T21:29:22.217", "Id": "238271", "Score": "8", "Tags": [ "python", "beginner", "python-3.x", "object-oriented" ], "Title": "O.O. Teacher List" }
238271
<p>I needed a special graph structure for my code and thought I'd write a generic one for later reuse.<br> At first I wanted to use pointers instead of indices as map keys but I quickly forfeited that idea once I realized, that changing the vertex vector might invalidate them. I'm especially interested if there are problems with my design (I expect way below 100 vertices tops, in case that's relevant), code style suggestions and maybe some improvements on the print function, which admittedly looks a bit ugly, because I needed to write it for debugging purposes.</p> <p>This graph is undirectional, allows multiple connections between two vertices and even connections from a vertex to itself.</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;memory&gt; #include &lt;vector&gt; namespace Util{ /** * @class Pseudo_Graph * An undirected graph that allows for multiple connections between the same vertices (including to itself) * Allows to specify additional information for each vertex and the costs to transverse between vertices * The graph is represented by an adjacency map * * Example: * Let there be vertices A, B, C and D where we use the vertex name as first template parameter &lt;Info=char&gt; * Let there be the following connections where the number behind denotes the cost to transverse &lt;Cost=unsigned int&gt; * A &lt;-&gt; A (1) * A &lt;-&gt; B (1) * A &lt;-&gt; D (8) * B &lt;-&gt; C (2) * B &lt;-&gt; C (4) * C &lt;-&gt; D (3) * This would be result in the following internal representation (numerical indices have been resolved for clarity) * Pseudo_Graph&lt;char, unsigned int&gt; * vertices = {'A', 'B', 'C', 'D'} * costs = {1, 8, 2, 4, 3} * graph['A'] = {{'A', {1}}, {'B', {1}}, {'D', {8}}} * graph['B'] = {{'A', {1}}, {'C', {2, 4}}} * graph['C'] = {{'B', {2, 4}}, {'D', {3}}} * graph['D'] = {{'A', {8}}, {'C', {3}}} * @tparam Info the information associated with each vertex * @tparam Cost the cost to traverse from one vertex to another */ template&lt;class Info, class Cost&gt; class Pseudo_Graph{ protected: struct Vertex{ Info info; bool visited; }; std::vector&lt;Vertex&gt; vertices_; std::vector&lt;Cost&gt; costs_; std::map&lt;std::size_t, std::map&lt;std::size_t, std::vector&lt;std::size_t&gt;&gt; &gt; graph_; bool contains_loops(std::size_t last, std::size_t next){ for( const auto&amp; to_cost_pointer : graph_[next] ){ if( to_cost_pointer.first == last ){ // we just came from here continue; } if( vertices_[to_cost_pointer.first].visited || to_cost_pointer.second.size() &gt; 1 ){ return true; } vertices_[to_cost_pointer.first].visited = true; if( contains_loops(next, to_cost_pointer.first) ){ return true; } } return false; } void visit_neighbours(std::size_t next){ for( const auto&amp; to_cost_pointer : graph_[next] ){ if( vertices_[to_cost_pointer.first].visited ){ continue; } vertices_[to_cost_pointer.first].visited = true; visit_neighbours(to_cost_pointer.first); } } public: void add_vertex(const Info&amp; info){ vertices_.push_back({info, false}); } void add_vertices(const std::vector&lt;Info&gt;&amp; info_vector){ for( auto info : info_vector ){ vertices_.push_back({info, false}); } } void add_link(const std::size_t from, const std::size_t to, const Cost&amp; costs){ if( from &gt;= vertices_.size() ){ throw std::runtime_error("Can not add link: Source vertex does not exist in Graph."); } if( to &gt;= vertices_.size() ){ throw std::runtime_error("Can not add link: Target vertex does not exist in Graph."); } graph_[from][to].push_back(costs); graph_[to][from].push_back(costs); } bool contains_loops(){ unvisit_all(); for( const auto&amp; from_to_pair : graph_ ){ if( vertices_[from_to_pair.first].visited ){ continue; } vertices_[from_to_pair.first].visited = true; for( const auto&amp; to_cost_pair : from_to_pair.second ){ if( vertices_[to_cost_pair.first].visited ){ continue; } vertices_[to_cost_pair.first].visited = true; if( to_cost_pair.second.size() &gt; 1 || contains_loops(from_to_pair.first, to_cost_pair.first) ){ return true; } } } return false; } void unvisit_all(){ for( auto&amp; vertex : vertices_ ){ vertex.visited = false; } } bool is_connected(){ unvisit_all(); if( graph_.empty() ){ return false; } visit_neighbours((*graph_.begin()).first); for( const auto&amp; vertex : vertices_ ){ if( !vertex.visited ){ return false; } } return true; } void print() const{ for( auto from_to_pair : graph_ ){ std::cout &lt;&lt; "[" &lt;&lt; from_to_pair.first &lt;&lt; "] = ["; bool outer_is_first{true}; for( const auto&amp; to_cost_pair : from_to_pair.second ){ if( !outer_is_first ){ std::cout &lt;&lt; ", "; } outer_is_first = false; std::cout &lt;&lt; "[" &lt;&lt; to_cost_pair.first &lt;&lt; ", ["; bool inner_is_first{true}; for( const auto&amp; cost : to_cost_pair.second ){ if( !inner_is_first ){ std::cout &lt;&lt; ", "; } inner_is_first = false; std::cout &lt;&lt; cost; } std::cout &lt;&lt; "]"; } std::cout &lt;&lt; "]\n"; } } }; } </code></pre>
[]
[ { "body": "<p>Some of the places where you use <code>push_back</code> would be better served using <code>emplace_back</code>. In <code>add_vertex</code>, using <code>vertices_.emplace_back(info, false);</code> would construct the Vertex directly in the vector and avoid creating a temporary object.</p>\n\n<p>The first <code>for</code> loop in <code>print</code> should use <code>const auto &amp;from_to_pair</code> (like you are with the other range based for loops) to avoid making a copy of all those map elements.</p>\n\n<p>To reduce memory and help with cache usage, and since it is only used internally, consider making <code>visited</code> a separate (private) vector, rather than bundling it with <code>Vertex</code>. By adding that one <code>bool</code> to <code>Vertex</code> (along with <code>Info</code>) there will probably be 3 or 7 padding bytes added to the struct. If you put <code>visited</code> in a separate vector you can reclaim that memory, and not even have it allocated when you aren't using it. You could use <code>std::vector&lt;bool&gt;</code>, which packs all the bools into bits and has some restrictions, or <code>std::vector&lt;char&gt;</code>. Resize it before you use it, then clear it when you're done. This would then let you get rid of the <code>unvisit_all</code> method, unless you want to keep it around to resize that new vector properly. If this vector is declared <code>mutable</code>, then your <code>is_connected</code> and <code>contains_loops</code> could potentially be declared <code>const</code>, which would be the expectation given their names. Or this new vector could be a local variable in the functions that need it, and passed to the other functions that need it as a parameter, which would be a necessary step (but not the only step) to make the class friendlier for multithreaded use.</p>\n\n<p>And one note on style: Your use of spaces is a bit atypical. It is more common to see a space between keyword and paren, and between close paren and the curly bracket, like <code>if (condition) {</code>. However, you are consistent in your usage which is good. Also, sometimes you have a blank line between functions and other times you don't. You could be more consistent in your use of spacing there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:25:11.887", "Id": "467313", "Score": "0", "body": "Thanks, that are some interesting things to read up upon!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T01:18:38.443", "Id": "238279", "ParentId": "238274", "Score": "2" } } ]
{ "AcceptedAnswerId": "238279", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T23:33:25.607", "Id": "238274", "Score": "2", "Tags": [ "c++", "graph" ], "Title": "Pseudograph Implementation" }
238274
<p>NOTE: I am beginner in Python</p> <p>I learnt the Heap sort today and tried my own implementation using Python. Can i get feedback for my code and areas of improvement. I have tried to add comments inline, but if still something is unclear, then i will add more comments. </p> <pre><code> def max_heap(listmax): i = 1 # if there is only one node, so thats is the max heap # for only 1 node, it wont go inside while loop and max heap will be node itself while i &lt;= len(listmax) -1: # for 2 nodes of more, the parent is checked against child # when there are 2 nodes, i will have max 1 value = len(listmax) - 1 # j is actually the parent of i, i can have 2 children which will have odd and even index # for eg. if 3 nodes, i can be 0,1,2 so 0 is parent and 1,2 will be children if i%2 == 0: j = int(i/2 -1) else: j = int(i//2) # here the listmax[i] will have the value of child node and listmax[j] has value of parent # if the parent &gt; children, then else is executed which moves to the next child of the parent if listmax[i] &gt; listmax[j]: listmax[i],listmax[j] = listmax[j],listmax[i] # the i &gt; 2 is there because then only, the children can become parents, and hence i make # the children as parents and compare it further up # the children are made parent by the below logic if i &gt; 2: if i%2 == 0: i = int(i/2 -1) else: i = int(i//2) else: i = i +1 else: i = i +1 return listmax def sort_heap(randomlist): max_heap_tree = max_heap(randomlist) sorted_heap = [] sorted_heap.append(max_heap_tree[0]) while len(max_heap_tree) &gt; 1: # the next highest number is found using the max_heap by removing the [0] element from the list max_heap_tree = max_heap(max_heap_tree[1:]) sorted_heap.append(max_heap_tree[0]) return sorted_heap randomlist = [10,15,30,12,15,20,17,20,32] sort_heap(randomlist) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:03:41.703", "Id": "467353", "Score": "0", "body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" } ]
[ { "body": "<p>This sorts the list in reverse, but that's still sorting, no issue there. But I think that should be noted in the code, since it is important and may not be expected. There are plenty of comments that explain the minutia, but not bigger things such as that. There is also no mention of what algorithm <code>max_heap</code> uses.</p>\n\n<p>The way <code>max_heap</code> works is, to me, very confusing. At the face of it, it is not at all obvious what kind of iteration is happening here. The way the algorithm picks up where it left off after bubbling-up an item is remeniscent of <a href=\"https://en.wikipedia.org/wiki/Gnome_sort\" rel=\"nofollow noreferrer\">Gnome sort</a>, slowly walking over all the items in between again. That's clever, but a more conventional setup with a nice counted for-loop and a while-loop inside of it to bubble-up an item would not need to make repeated passes over the entire list.</p>\n\n<p>So unless I made a mistake in my reasoning, and that is easily possible because this is a quite confusing arrangement, <code>max_heap</code> may take quadratic time in the worst case. That is not good, it can be done in linear time using the classic <a href=\"https://www.geeksforgeeks.org/time-complexity-of-building-a-heap/\" rel=\"nofollow noreferrer\">bottom-up heap construction</a>, or at least in O(n log n) time using two loops, one over all the items and an other to bubble-up that item. O(n log n) construction isn't <em>too</em> bad, that is the overall complexity of HeapSort anyway, but O(n²) heap construction is a waste of a good algorithm. But maybe I'm wrong and maybe your algorithm isn't quadratic time, let me know, and add comments explaining the bigger picture.</p>\n\n<p>The way <code>max_heap</code> is used is an other issue. First, <code>sort_heap</code> throws away a useful property of Heap Sort: it can be done in-place. That is done by extracting an item from the heap, which \"shrinks\" the heap by one place, then the extracted item goes into the space that was emptied at the end of the heap. That way, the sorted array is built up from the end, at the same time that the heap is being used up. It's a nice trick. Using it is not mandatory of course. This trick is why a max heap is usually used rather than a min heap: the biggest item is needed first, to put it at the end of the array.</p>\n\n<p>A bigger issue is that <code>max_heap</code> keeps being used every time an item is removed from the heap. It's a very expensive way to restore the heap property, and there is a much better solution: grab the last item in the heap, make it the new root, then restore the heap property top-down (aka \"bubble down\"). That way only O(log n) work is involved per iterating of the sorting loop, instead of however much <code>max_heap</code> costs (which depends on the algorithm used, but at least linear time).</p>\n\n<p>Due to this and the quadratic time <code>max_heap</code> (overall leading a cubic time algorithm), I would say that this algorithm does not match what Heap Sort is supposed to be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T15:56:59.227", "Id": "467351", "Score": "0", "body": "Thanks for the feedback. Yes i worked on improving my code. I have literally coded it they way, as if someone would do it on paper. I counted the iterations also and i cant think of any iteration which i can save now. Thanks for your feedback and would appreciate more constructive feedback. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:12:55.317", "Id": "467357", "Score": "1", "body": "@prabh manipulating `i` in an even more complex way is not what I meant. You can propably make it faster that way.. but there is a much simpler way: loop over the list (just a normal plain old `for`-loop) and perform \"bubble up\" for each of the items (you can make that its own function even, why not) independently of the outer loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T02:39:15.577", "Id": "238283", "ParentId": "238277", "Score": "3" } }, { "body": "<p>I have improved my code and here's my new code:</p>\n\n<pre><code> def max_heap(listmax):\n\n i = 1\n k = 0\n\n while i &lt;= len(listmax) -1:\n\n if i%2 == 0:\n j = int(i/2 -1)\n else:\n j = int(i//2)\n\n# parent is compared with the child and swapped if not in order. \n\n if listmax[i] &gt; listmax[j]:\n listmax[i],listmax[j] = listmax[j],listmax[i]\n\n# k is used here to store the index of the latest node which is compared in the array. So that next time\n# the parent is compared to the child, then it starts with k+1 occurence.\n# coming inside this if loop means child was greater than parent and hence it was swapped. Also k will\n# now hold the index of child node\n\n# k is checked for 0 first because, we want to have the very first node when the swapping starts, so that \n# the next node read should be from k+1 node\n\n if k == 0:\n k = i\n\n# i &gt; 2 means that the child also becomes parent in the flow, so the child is made parent and checked in while loop \n\n if i &gt; 2: \n if i%2 == 0:\n i = int(i/2 -1)\n else:\n i = int(i//2)\n else:\n if k &gt; 2:\n i = k +1\n else:\n i = i +1\n k = 0\n else:\n\n# this else means, parent was greater than the child, so no swapping happened\n# k has the value of last child where the swapping started so next node to be read should be k+1\n# if k is zero, it means the last child which was read was already smaller than parent and hence we \n# just move to next node by i +1\n\n if k != 0:\n i = k +1\n k = 0\n else:\n i = i +1\n\n return listmax\n\ndef sort_heap(randomlist): \n\n max_heap_tree = max_heap(randomlist)\n sorted_heap = []\n\n sorted_heap.append(max_heap_tree[0])\n\n while len(max_heap_tree) &gt; 1: \n\n# the next highest number is found using the max_heap by removing the [0] element from the list \n\n max_heap_tree = max_heap(max_heap_tree[1:])\n sorted_heap.append(max_heap_tree[0])\n\n return sorted_heap\n\n\nrandomlist = [10,15,20,25,30,35,40,45,50,55] \nsort_heap(randomlist)\n</code></pre>\n\n<p>I had put a counter in while loop and to get max heap with 10 nodes in the above example it took 19 iterations and overall to sort the complete list 60 iterations. Not sure if can be improved more.</p>\n\n<p>Also, the way i am creating the max heap is literally how we would do it on paper. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T19:12:58.677", "Id": "467378", "Score": "1", "body": "You still use the same max_heap function to construct the initial heap, and for each step of bubbling down. Once you have a heap, you need to take advantage of that to make sure each individual element only needs log time. Look up the \"heapify\" function and how it is different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T21:27:53.930", "Id": "467383", "Score": "1", "body": "@KennyOstrom i think i got your point now. Once i have the max heap, i just need to take the max element and then take the last node to position 0 and rearrange the heap which will take maximum of iterations as the height of the tree." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:10:10.273", "Id": "238318", "ParentId": "238277", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T00:26:20.057", "Id": "238277", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "sorting", "heap-sort" ], "Title": "Heap Sort in Python" }
238277
<pre><code>void selectionSortC() { //Not wasting time inputting arrary int arr[6] = { 2,4,-22,4,2,1 }; size_t minIdx = 0; int len = sizeof(arr) / sizeof(int); for (int i = 0; i &lt; len; i++) { for (int j = i + 1; j &lt; len; j++) { if (arr[i] &gt; arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for (int i = 0; i &lt; len; i++) { printf("%d ",arr[i]); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T07:42:16.487", "Id": "467408", "Score": "0", "body": "You should never write \"non-prototype style\" functions in C, it's an obsolete feature. That is, never write `void selectionSortC()`, always write `void selectionSortC(void)`." } ]
[ { "body": "<h1>Missing includes</h1>\n<p>We need to include <code>&lt;stdio.h&gt;</code> (for <code>printf</code>); this also defines <code>size_t</code> for us (but see next item).</p>\n<h1>Don't mix I/O with algorithms</h1>\n<p>The code is hard to re-use, because we can't give a different array to sort, or do anything with the result apart from printing. Prefer an interface like this:</p>\n<pre><code>#include &lt;stddef.h&gt; /* for size_t */\n\nvoid selection_sort(int *array, size_t len);\n</code></pre>\n<p>We can use it like this:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n int arr[] = { 2, 4, -22, 4, 2, 1 };\n const size_t len = sizeof arr / sizeof *arr;\n\n selection_sort(arr, len);\n\n for (size_t i = 0; i &lt; len; ++i) {\n printf(&quot;%d &quot;, arr[i]);\n }\n puts(&quot;&quot;);\n}\n</code></pre>\n<h1>Unused variable</h1>\n<p>What's the point of <code>minIdx</code>? We never use it after it's initialised.</p>\n<h1>Use appropriate types</h1>\n<p>We should be using <code>size_t</code> for lengths and indices, rather than <code>int</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Here's what I arrived at after making the improvements above:</p>\n<pre><code>#include &lt;stddef.h&gt;\n\nvoid selection_sort(int *arr, size_t len)\n{\n for (size_t i = 0; i &lt; len; i++) {\n for (size_t j = i + 1; j &lt; len; j++) {\n if (arr[i] &gt; arr[j]) {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n}\n\n#include &lt;stdio.h&gt;\nint main(void)\n{\n int arr[] = { 2, 4, -22, 4, 2, 1 };\n const size_t len = sizeof arr / sizeof *arr;\n\n selection_sort(arr, len);\n\n for (size_t i = 0; i &lt; len; ++i) {\n printf(&quot;%d &quot;, arr[i]);\n }\n puts(&quot;&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T09:18:07.490", "Id": "238294", "ParentId": "238280", "Score": "0" } } ]
{ "AcceptedAnswerId": "238294", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T01:33:17.390", "Id": "238280", "Score": "-2", "Tags": [ "c", "sorting" ], "Title": "Selection sort in C" }
238280
<p>Configs.java</p> <pre class="lang-java prettyprint-override"><code>package main; /** * @author Daniel * * A load of configs for the application. */ public class Configs { public static final String APPLICATION_NAME = "Sorting Algorithm Animation"; public static final int APPLICATION_WIDTH = 1280; public static final int APPLICATION_HEIGHT = 720; public static final int DISPLAY_PANEL_WIDTH = Configs.APPLICATION_WIDTH * 4 / 5; public static final int DISPLAY_PANEL_HEIGHT = Configs.APPLICATION_HEIGHT; public static final int BUTTONS_PANEL_WIDTH = Configs.APPLICATION_WIDTH / 5; public static final int BUTTONS_PANEL_HEIGHT = Configs.APPLICATION_HEIGHT; public static final int INITIAL_LIST_STARTING_VALUE = 1024; public static final String[] ALL_SORTS_COMBO_BOX_VALUES = {"Bubble Sort", "Quick Sort", "Selection Sort", "Insertion Sort", "Merge Sort"}; public static final int MAXIMUM_DELAY_VALUE = 10000; public static final int MINIMUM_DELAY_VALUE = 0; public static final int TICK_SPACING = 3333; public static final int INITIAL_DELAY_VALUE = MAXIMUM_DELAY_VALUE / 2; } </code></pre> <p>SortingAlgorithmAnimationApp.java</p> <pre class="lang-java prettyprint-override"><code>package main; import javax.swing.SwingUtilities; import gui.AppGUI; /** * @author Daniel * * The driver class. */ public class SortingAlgorithmAnimationApp { public static void main(String[] args) { SwingUtilities.invokeLater(AppGUI::new); } } </code></pre> <p>AppGUI,java</p> <pre class="lang-java prettyprint-override"><code>package gui; import java.awt.FlowLayout; import javax.swing.JFrame; import gui_components.GUIComponents; import main.Configs; import storage.NumbersList; /** * @author Daniel * * Puts the GUI together. */ public class AppGUI { public AppGUI() { NumbersList.generateList(Configs.INITIAL_LIST_STARTING_VALUE); initGUI(); } private void initGUI() { JFrame window = new JFrame(); window.getContentPane().setLayout(new FlowLayout()); window.getContentPane().add(GUIComponents.buttonsPanel); window.getContentPane().add(GUIComponents.displayPanel); window.setTitle(Configs.APPLICATION_NAME); window.setResizable(false); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.pack(); window.setLocationRelativeTo(null); window.setVisible(true); } } </code></pre> <p>GUIComponents.java</p> <pre class="lang-java prettyprint-override"><code>package gui_components; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import drawing.PaintSurface; import main.Configs; import sorting_algorithms.BubbleSort; import sorting_algorithms.InsertionSort; import sorting_algorithms.MergeSort; import sorting_algorithms.QuickSort; import sorting_algorithms.SelectionSort; import sorting_algorithms.SortingAlgorithm; import storage.NumbersList; /** * @author Daniel * * Creates and holds all the GUI components. */ public class GUIComponents { // don't let anyone instantiate this class. private GUIComponents() {} public static JPanel buttonsPanel, displayPanel; private static JButton newListButton; public static JSlider delaySlider; private static JButton randomizeListButton; private static JComboBox&lt;String&gt; allSortsComboBox; private static JButton doSortButton; private static SortingAlgorithm algorithm; static { initButtonsPanel(); displayPanel = new PaintSurface(); } private static void initButtonsPanel() { buttonsPanel = new JPanel(); buttonsPanel.setPreferredSize(new Dimension(Configs.BUTTONS_PANEL_WIDTH, Configs.BUTTONS_PANEL_HEIGHT)); buttonsPanel.setBackground(Color.LIGHT_GRAY); initNewListButton(); initDelaySlider(); initRandomizeListButton(); initAllSortsComboBox(); initDoSortButton(); buttonsPanel.add(new JLabel("Sorting Delay (ms)")); buttonsPanel.add(delaySlider); buttonsPanel.add(newListButton); buttonsPanel.add(randomizeListButton); buttonsPanel.add(allSortsComboBox); buttonsPanel.add(doSortButton); } private static void initNewListButton() { newListButton = new JButton("New List"); newListButton.addActionListener((ActionEvent event) -&gt; { int amount = NumbersList.getList().length; try { String temp = JOptionPane.showInputDialog(null, "How many numbers?", "Enter Information", JOptionPane.INFORMATION_MESSAGE); if(temp != null &amp;&amp; temp.length() &gt; 0) { amount = Integer.parseInt(temp); } else return; } catch(java.lang.NumberFormatException exception) { JOptionPane.showMessageDialog(null, "Something went wrong!", "Error", JOptionPane.ERROR_MESSAGE); return; } if(amount &lt; 0 || amount &gt; 1024) { JOptionPane.showMessageDialog(null, "Invalid Amount! 0 - 1024 only.", "Error", JOptionPane.ERROR_MESSAGE); return; } NumbersList.generateList(amount); GUIComponents.displayPanel.repaint(); }); } private static void initDelaySlider() { delaySlider = new JSlider(JSlider.HORIZONTAL, Configs.MINIMUM_DELAY_VALUE, Configs.MAXIMUM_DELAY_VALUE, Configs.INITIAL_DELAY_VALUE); delaySlider.setMajorTickSpacing(Configs.TICK_SPACING); delaySlider.setMinorTickSpacing(10); delaySlider.setPaintLabels(true); delaySlider.setSnapToTicks(true); delaySlider.setBackground(Color.LIGHT_GRAY); delaySlider.addChangeListener((ChangeEvent event) -&gt; { if(algorithm != null) algorithm.changeDelay(delaySlider.getValue() * 1000); }); } private static void initRandomizeListButton() { randomizeListButton = new JButton("Randomize List"); randomizeListButton.addActionListener((ActionEvent event) -&gt; { NumbersList.randomizeList(); GUIComponents.displayPanel.repaint(); }); } private static void initAllSortsComboBox() { allSortsComboBox = new JComboBox&lt;String&gt;(Configs.ALL_SORTS_COMBO_BOX_VALUES); } private static void initDoSortButton() { doSortButton = new JButton("Do Sort"); doSortButton.addActionListener((ActionEvent event) -&gt; { randomizeListButton.setEnabled(false); newListButton.setEnabled(false); doSortButton.setEnabled(false); allSortsComboBox.setEnabled(false); switch((String) allSortsComboBox.getSelectedItem()) { case "Bubble Sort": algorithm = new BubbleSort(); break; case "Quick Sort": algorithm = new QuickSort(); break; case "Selection Sort": algorithm = new SelectionSort(); break; case "Insertion Sort": algorithm = new InsertionSort(); break; case "Merge Sort": algorithm = new MergeSort(); break; } new Thread(new Runnable() { @Override public void run() { algorithm.doSort(NumbersList.getList()); randomizeListButton.setEnabled(true); newListButton.setEnabled(true); doSortButton.setEnabled(true); allSortsComboBox.setEnabled(true); }}).start(); displayPanel.repaint(); }); } } </code></pre> <p>NumbersList.java</p> <pre class="lang-java prettyprint-override"><code>package storage; import main.Configs; /** * @author Daniel * * Holds the list and methods concerning the list. */ public class NumbersList { private static int[] numbers; public static void generateList(int amount) { numbers = new int[amount]; double spacing = (double) Configs.APPLICATION_HEIGHT / amount, height = spacing; for(int i = 0; i &lt; amount; i++) { numbers[i] = (int) (height); height += spacing; } } public static void randomizeList() { for(int i = 0; i &lt; NumbersList.numbers.length; i++) { int temp = NumbersList.numbers[i]; int randomPlace = (int) (Math.random() * NumbersList.numbers.length); NumbersList.numbers[i] = NumbersList.numbers[randomPlace]; NumbersList.numbers[randomPlace] = temp; } } public static int[] getList() { return NumbersList.numbers; } } </code></pre> <p>PaintSurface.java</p> <pre class="lang-java prettyprint-override"><code>package drawing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JPanel; import main.Configs; import storage.NumbersList; /** * @author Daniel * * The display panel for the animation. */ public class PaintSurface extends JPanel { private static final long serialVersionUID = 1L; public static int currentBarIndex = 0; public PaintSurface() { this.setPreferredSize(new Dimension(Configs.DISPLAY_PANEL_WIDTH, Configs.DISPLAY_PANEL_HEIGHT)); this.setBackground(Color.PINK); } @Override protected void paintComponent(Graphics g) { Graphics2D graphics = (Graphics2D) g; graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(graphics); int[] listNumbers = NumbersList.getList(); double x = 0, width = (double) Configs.DISPLAY_PANEL_WIDTH / listNumbers.length; for(int i = 0; i &lt; listNumbers.length; i++) { if(currentBarIndex == i) graphics.setPaint(Color.RED); else graphics.setPaint(Color.BLACK); graphics.fillRect((int) x, Configs.APPLICATION_HEIGHT - listNumbers[i], (int) width + 1, listNumbers[i]); x += width; } graphics.dispose(); g.dispose(); } } </code></pre> <p>BubbleSort.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import gui_components.GUIComponents; /** * @author Daniel * * Implementation of the bubble sort. */ public class BubbleSort implements SortingAlgorithm { private int delay = GUIComponents.delaySlider.getValue() * 1000; @Override public String getName() { return "Bubble Sort"; } @Override public void doSort(int[] nums) { int n = nums.length; for (int i = 0; i &lt; n - 1; i++) for (int j = 0; j &lt; n - i - 1; j++) if (nums[j] &gt; nums[j + 1]) { int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; SortingAlgorithm.setCurrentBar(j+1); SortingAlgorithm.sleepFor(delay); } SortingAlgorithm.setCurrentBar(0); } @Override public void changeDelay(int delay) { this.delay = delay; } } </code></pre> <p>QuickSort.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import gui_components.GUIComponents; public class QuickSort implements SortingAlgorithm { private int delay = GUIComponents.delaySlider.getValue() * 1000; @Override public String getName() { return "Quick Sort"; } @Override public void doSort(int[] nums) { sort(nums, 0, nums.length - 1); } private int partition(int nums[], int low, int high) { int pivot = nums[high]; int i = (low - 1); for (int j = low; j &lt; high; j++) { if (nums[j] &lt; pivot) { i++; int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } } int temp = nums[i + 1]; nums[i + 1] = nums[high]; nums[high] = temp; return i + 1; } private void sort(int nums[], int low, int high) { if (low &lt; high) { int pi = partition(nums, low, high); sort(nums, low, pi - 1); sort(nums, pi + 1, high); } } @Override public void changeDelay(int delay) { this.delay = delay; } } </code></pre> <p>SelectionSort.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import gui_components.GUIComponents; /** * @author Daniel * * Implementation of the selection sort. */ public class SelectionSort implements SortingAlgorithm { private int delay = GUIComponents.delaySlider.getValue() * 1000; @Override public String getName() { return "Selection Sort"; } @Override public void doSort(int[] nums) { int n = nums.length; for (int i = 0; i &lt; n - 1; i++) { int minIndex = i; for (int j = i + 1; j &lt; n; j++) if (nums[j] &lt; nums[minIndex]) { minIndex = j; SortingAlgorithm.setCurrentBar(i); SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } int temp = nums[minIndex]; nums[minIndex] = nums[i]; nums[i] = temp; } } @Override public void changeDelay(int delay) { this.delay = delay; } } </code></pre> <p>InsertionSort.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import gui_components.GUIComponents; /** * @author Daniel * * Implementation of the insertion sort. */ public class InsertionSort implements SortingAlgorithm { private int delay = GUIComponents.delaySlider.getValue() * 1000; @Override public String getName() { return "Insertion Sort"; } @Override public void doSort(int[] nums) { int n = nums.length; for (int i = 1; i &lt; n; ++i) { int key = nums[i]; int j = i - 1; while (j &gt;= 0 &amp;&amp; nums[j] &gt; key) { nums[j + 1] = nums[j]; j--; } nums[j + 1] = key; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } } @Override public void changeDelay(int delay) { this.delay = delay; } } </code></pre> <p>MergeSort.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import gui_components.GUIComponents; public class MergeSort implements SortingAlgorithm { private int delay = GUIComponents.delaySlider.getValue() * 1000; @Override public String getName() { return "Merge Sort"; } @Override public void doSort(int[] nums) { sort(nums, 0, nums.length - 1); } private void merge(int nums[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for(int i = 0; i &lt; n1; ++i) L[i] = nums[l + i]; for(int j = 0; j &lt; n2; ++j) R[j] = nums[m + 1 + j]; int i = 0, j = 0; int k = l; while (i &lt; n1 &amp;&amp; j &lt; n2) { if (L[i] &lt;= R[j]) { nums[k] = L[i]; i++; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } else { nums[k] = R[j]; j++; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } k++; } while (i &lt; n1) { nums[k] = L[i]; i++; k++; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } while (j &lt; n2) { nums[k] = R[j]; j++; k++; SortingAlgorithm.setCurrentBar(j); SortingAlgorithm.sleepFor(delay); } } private void sort(int nums[], int l, int r) { if (l &lt; r) { int m = (l + r) / 2; sort(nums, l, m); sort(nums, m + 1, r); merge(nums, l, m, r); } } @Override public void changeDelay(int delay) { this.delay = delay; } } </code></pre> <p>SortingAlgorithm.java</p> <pre class="lang-java prettyprint-override"><code>package sorting_algorithms; import drawing.PaintSurface; import gui_components.GUIComponents; /** * @author Daniel * * Template for the sorting algorithms. */ public abstract interface SortingAlgorithm { public abstract String getName(); public abstract void doSort(int[] nums); public abstract void changeDelay(int delay); public static void setCurrentBar(int currentBarIndex) { PaintSurface.currentBarIndex = currentBarIndex; } public static void sleepFor(int delay) { long timeElapsed; final long startTime = System.nanoTime(); do { timeElapsed = System.nanoTime() - startTime; } while(timeElapsed &lt; delay); GUIComponents.displayPanel.repaint(); } } </code></pre> <p>Any helpful recommendations, comments, or suggestions are great. I'm only in high school, so any constructive criticism is nice! Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T06:44:15.707", "Id": "467297", "Score": "0", "body": "Welcome to CodeReview@SE! Have a (another) look at [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and try and find a better title - I think *simulation* slightly off, as the sorting is as real as it comes, with *visualisation* welded in. It may prove useful to present more context: what details of `interface SortingAlgorithm` are your own design, what was specified beforehand?" } ]
[ { "body": "<p>Welcome to CodeReview, your program is advanced for high school. I have some suggestions for you:</p>\n\n<blockquote>\n<pre><code>private int delay = GUIComponents.delaySlider.getValue() * 1000;\n</code></pre>\n</blockquote>\n\n<p>You repetead this line all the classes implementing one different sorting method, you could use a constructor and pass this as a value like the class below:</p>\n\n<pre><code>public class BubbleSort implements SortingAlgorithm {\n\n private int delay;\n\n public BubbleSort(int delay) {\n this.delay = delay;\n }\n\n //other methods\n}\n\n//after in your code\nint delay = GUIComponents.delaySlider.getValue() * 1000;\nSortingAlgorithm bubble = new BubbleSort(delay);\n</code></pre>\n\n<p>I don't know if you are aware about the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">Map</a> class, that maps keys to value, you could use in the following way:</p>\n\n<pre><code>int delay = GUIComponents.delaySlider.getValue() * 1000;\nMap&lt;String, SortingAlgorithm&gt; map = new TreeMap&lt;String, SortingAlgorithm&gt;();\nmap.put(\"Bubble sort\", new BubbleSort(delay));\nmap.put(\"Quick sort\", new QuickSort(delay));\nSet&lt;String&gt; set = map.keySet(); //[Bubble sort, Quick sort]\nSortingAlgorithm bubble = map.get(\"Bubble sort\");\nSortingAlgorithm quick = map.get(\"Quick sort\");\n</code></pre>\n\n<p>In this example I created one <code>BubbleSort</code> object and one <code>QuickSort</code> object mapping them with their labels by <code>put</code> method and you can access them using the <code>get</code> method.</p>\n\n<p>One thing you could change is the name of the class <code>NumbersList</code> : <code>List</code> is about a structure that can be modified while your class is an array, perhaps you could rename it as <code>NumbersArray</code>. Below my implementation for your class:</p>\n\n<pre><code>public class NumbersArray {\n private static int[] numbers;\n\n public static void generateArray(int amount) {\n numbers = new int[amount];\n\n double spacing = (double) Configs.APPLICATION_HEIGHT / amount;\n for(int i = 0; i &lt; amount; i++) {\n numbers[i] = (int) ((i + 1) * spacing);\n }\n }\n\n public static void randomizeArray() {\n Collections.shuffle(Arrays.asList(numbers));\n }\n\n public static int[] getArray() {\n return numbers;\n }\n}\n</code></pre>\n\n<p>I used <code>Collections.shuffle</code> method to randomize the elements of your array. Anyway again you made a great job.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T18:49:06.223", "Id": "238330", "ParentId": "238285", "Score": "4" } } ]
{ "AcceptedAnswerId": "238330", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T04:00:36.027", "Id": "238285", "Score": "7", "Tags": [ "java", "object-oriented", "sorting", "swing", "data-visualization" ], "Title": "This is a sorting algorithm visualization program" }
238285
<p>I'm currently learning about Dynamic Programming and solving a &quot;coding question&quot; related to the topic.</p> <blockquote> <p>Given an array of non-negative integers, you are initially positioned at the first index of the array.</p> <p>Each element in the array represents your maximum jump length at that position.</p> <p>Determine if you are able to reach the last index.</p> <h3>Example 1:</h3> <p>Input: <code>[2,3,1,1,4]</code><br /> Output: <code>true</code></p> <h3>Example 2:</h3> <p>Input: <code>[3,2,1,0,4]</code><br /> Output: <code>false</code></p> </blockquote> <p>Here's my code:</p> <pre class="lang-py prettyprint-override"><code> def canJump(nums: List[int]) -&gt; bool: memo = {len(nums) - 1: True} def canJumpPos(pos): if pos &gt;= len(nums): return False elif pos in memo: return memo[pos] else: for i in range(nums[pos], 0, -1): if canJumpPos(i + pos): return True memo[pos] = False return canJumpPos(0) </code></pre> <p>I'm having trouble reasoning about the time/space complexity of my approach. My understanding is that without memoization, this approach would be exponential. But, with memoization, this becomes a linear time algorithm? Is this correct? How would you recommend I calculate time complexity in the future when I'm dealing with dynamic programming?</p>
[]
[ { "body": "<h1>All paths do not <code>return</code></h1>\n\n<pre><code> def canJumpPos(pos):\n if pos &gt;= len(nums):\n return False\n elif pos in memo:\n return memo[pos]\n else:\n for i in range(nums[pos], 0, -1):\n if canJumpPos(i + pos):\n return True\n memo[pos] = False\n # Missing Return\n</code></pre>\n\n<p>This means <code>canJump([3,2,1,0,4])</code> returns <code>None</code>, not <code>False</code>! A violation of your declared <code>-&gt; bool</code> return.</p>\n\n<h1>No memoization of <code>True</code></h1>\n\n<p>When this code returns <code>True</code>:</p>\n\n<pre><code> if canJumpPos(i + pos):\n return True\n</code></pre>\n\n<p><code>memo[pos]</code> is never set to <code>True</code>. This means that if <code>canJumpPos(pos)</code> is called called with the same <code>pos</code> value, it will have to redo all the work it has already done to return the same <code>True</code> value!</p>\n\n<h1>Eschew offset additions, assiduously</h1>\n\n<pre><code> for i in range(nums[pos], 0, -1):\n if canJumpPos(i + pos):\n</code></pre>\n\n<p>Here, you are always using <code>i + pos</code>, never <code>i</code> by itself.\nInstead of repeating this addition over and over again,\nyou could roll that addition into the <code>range()</code> end-points.</p>\n\n<pre><code> for i in range(nums[pos] + pos, pos, -1):\n if canJumpPos(i):\n</code></pre>\n\n<h1>Any and All</h1>\n\n<p>Looping over some condition until you find a <code>True</code> condition:</p>\n\n<pre><code> for i in range(nums[pos] + pos, pos, -1):\n if canJumpPos(i):\n return True\n # ...\n</code></pre>\n\n<p>is often better performed using <code>any(...)</code>:</p>\n\n<pre><code> if any(canJumpPos(i) for i in range(nums[pos] + pos, pos, -1)):\n return True\n # ...\n</code></pre>\n\n<p>The <code>any(...)</code> will terminate when the first <code>True</code> is found, and return <code>True</code>. If no <code>True</code> value is found, it will return <code>False</code>.</p>\n\n<p>There is a similar function <code>all(...)</code>, which will terminate at the first <code>False</code> returning <code>False</code>. If no <code>False</code> value is found, it returns <code>True</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T22:49:52.520", "Id": "238335", "ParentId": "238292", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:50:55.647", "Id": "238292", "Score": "2", "Tags": [ "python", "python-3.x", "interview-questions", "dynamic-programming" ], "Title": "Is there a route to the end of the jump table?" }
238292
<p>I am trying to write a graph implementation in Java. I would appreciate it if someone can please review the code for me and give constructive feedback.</p> <pre><code>import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; public class Graph { private int V; // Number of vertices private int E; // Number of edges private HashMap&lt;Integer, LinkedList&lt;Integer&gt;&gt; adj; // adjacency list Graph() { adj = new HashMap&lt;&gt;(); } /** * Returns the number of vertices * @return Number of vertices in the graph */ public int vertices() { return this.V; } /** * Number of edges in the graph * @return Returns the number of edges in the graph */ public int edges() { return this.E; } public void addEdge(int v, int w) { if(adj.containsKey(v)) { adj.get(v).add(w); ++E; } else if(adj.containsKey(w)) { adj.get(w).add(v); ++E; } else { LinkedList&lt;Integer&gt; llOne = new LinkedList&lt;&gt;(); LinkedList&lt;Integer&gt; llTwo = new LinkedList&lt;&gt;(); llTwo.add(v); llOne.add(w); adj.put(v, llOne); adj.put(w, llTwo); ++V; ++E; } } @Override public String toString() { StringBuilder returnString = new StringBuilder(); for (int key : adj.keySet()) { returnString.append(key).append(": "); LinkedList&lt;Integer&gt; nodesList = adj.get(key); returnString.append(Arrays.toString(nodesList.toArray())); } return returnString.toString(); } } </code></pre>
[]
[ { "body": "<h1>Thinking about naming...</h1>\n<ul>\n<li>When I see a single capital letter, it makes me think of generic type. I find your usage misleading.</li>\n<li>Single letter variable names can be OK when it's obvious what they are, such as indexers in loops, I would suggest avoiding them for anything with larger scope, particularly at the field level.</li>\n<li><code>int V; // Number of vertices</code>, why not just call it <code>numberOfVertices</code>? You don't need the comment and the rest of the code is that little bit easier to interpret?</li>\n<li><code>edges()</code>: Typically in Java I'd expect this type of method to be called <code>getEdges</code>, it's really just returning the field. In fact, when I first saw it, I thought it would be returning some collection of edges, but it doesn't it just returns a count. Consider renaming it to match what it returns.</li>\n<li><code>LinkedList&lt;Integer&gt; llOne = new LinkedList&lt;&gt;();</code>. Generally, avoid embedding the type information (ll) in the variable name. Think about what the list is representing and call it that, rather than 'one' and 'two'.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T15:58:46.193", "Id": "467352", "Score": "0", "body": "Thanks for the pointers. I agree with you that having capital letters variable names can confuse someone about it being a generic type and not a variable name.\nI have made the required changes to the code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T10:57:31.690", "Id": "238298", "ParentId": "238296", "Score": "5" } }, { "body": "<p>Your constructor might as well be public; it doesn't matter if a user can create a separate <code>Graph</code> instance after all.</p>\n\n<pre><code>private int V; // Number of vertices\nprivate int E; // Number of edges\n</code></pre>\n\n<p>Why not directly call them <code>numberOfVertices</code> and <code>numberOfEdges</code> or even just <code>vertices</code> and <code>edges</code>? Throughout the program you act if the variables are part of a math equation. However, that doesn't make your code any more readable.</p>\n\n<p>Note that on most IDE's you can easily refactor after typing in the code as well. The current names make the variables look like generic types or constants. Not good.</p>\n\n<pre><code>public int vertices() {\n</code></pre>\n\n<p>I'd call that <code>getVertices</code>; you directly retrieve a field value without any other side effects, so this is consider a getter by most.</p>\n\n<pre><code>public void addEdge(int v, int w) {\n</code></pre>\n\n<p>Now we have two variables called <code>v</code>, that's not a good idea, even if they just vary in case.</p>\n\n<hr>\n\n<p>About the functionality of the program:</p>\n\n<ol>\n<li>There doesn't seem to be an option in case both <code>v</code> and <code>w</code> are present; in that case an edge needs to be added (it's separate from the other ones as no vertex needs to be added).</li>\n<li>This program assumes that if one of the vertices already exists (the first branch in the <code>if</code> statement) that the edge cannot add a vertex (at least the count doesn't go up). This seems incorrect.</li>\n<li>It also assumes that you can add parallel edges. So this is a multi-graph. In that case name your class that way.</li>\n<li>In the case none of the vertices exist then you only add one to <code>V</code> which cannot be correct.</li>\n<li>There doesn't seem any special handling for <code>v == w</code>: so called <em>loops</em>. I don't know if that's correct or not.</li>\n</ol>\n\n<p>If you only want singular edges between vertices then you should explicitly skip if a <code>v</code> can be found with a <code>w</code> in the list. In that case you might be better off using a <code>SortedSet</code> such as a <code>TreeSet</code>.</p>\n\n<hr>\n\n<p>If you allow your vertices and edges to be counted then you you would not have the trouble of keeping more state than necessary and getting out of sync. For instance, you could simply only count those edges to values higher than the key in the map (or divide by 2?). Counting the vertices should be easy.</p>\n\n<p>For instance, I would come up with something similar to the following:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * Implements a multi-graph without loops. A loop is an edge from one vertex to the same vertex.\n */\npublic class MultiGraph {\n private HashMap&lt;Integer, List&lt;Integer&gt;&gt; adjacentVerticesByVertex;\n\n /**\n * Constructs an empty graph.\n */\n public MultiGraph() {\n adjacentVerticesByVertex = new HashMap&lt;&gt;();\n }\n\n public int getNumberOfVertices() {\n return this.adjacentVerticesByVertex.size();\n }\n\n public int getNumberOfEdges() {\n int edgesBothWays = 0;\n for (var adjForVertice : adjacentVerticesByVertex.values()) {\n edgesBothWays += adjForVertice.size();\n }\n return edgesBothWays / 2;\n }\n\n public void addEdge(int vertexA, int vertexB) {\n if (vertexA == vertexB) {\n throw new IllegalArgumentException(\"Loops are not allowed\");\n }\n\n addVertexAsAdjacent(vertexA, vertexB);\n addVertexAsAdjacent(vertexB, vertexA);\n }\n\n private void addVertexAsAdjacent(int vertexA, int vertexB) {\n var verticesForVertexA =\n adjacentVerticesByVertex.getOrDefault(vertexA, new LinkedList&lt;Integer&gt;());\n verticesForVertexA.add(vertexB);\n if (verticesForVertexA.size() == 1) {\n adjacentVerticesByVertex.put(vertexA, verticesForVertexA);\n }\n }\n\n @Override\n public String toString() {\n var sb = new StringBuilder();\n\n sb.append(String.format(\"Vertices: %d, Edges: %d, Adjacent vertices:\",\n getNumberOfVertices(), getNumberOfEdges()));\n\n for (int key : adjacentVerticesByVertex.keySet()) {\n sb.append(String.format(\" (V: %d \", key));\n var nodesList = adjacentVerticesByVertex.get(key);\n sb.append(Arrays.toString(nodesList.toArray()));\n sb.append(\")\");\n }\n\n return sb.toString();\n }\n\n public static void main(String[] args) {\n var g = new MultiGraph();\n g.addEdge(0, 1);\n g.addEdge(0, 2);\n g.addEdge(0, 2);\n g.addEdge(10, 11);\n System.out.println(g);\n }\n}\n</code></pre>\n\n<p>The disadvantage of counting all the edges this way is of course that you have to iterate over all vertices and check the size. Furthermore, as it is, it stores each edge twice - this way it is easier to go back and forth between two vertices with an edge, but it also means more memory usage.</p>\n\n<p>But as you can see V is now gone, and just getting the number of keys in the set is undoubtedly just one call, so we are all the better for it: <em>try and minimize the state within objects</em> falls firmly within KISS principles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:04:11.607", "Id": "467364", "Score": "0", "body": "Thanks for the feedback. I have changed the variable names as everyone recommended.\nPoints about functionality of the program:\n- Thanks for catching the edge case. I had missed that.\n- I didn't understand the second point. Can you please re-phrase it?\n- I will change the name. This is a multi-graph\n- What do you mean that I add only one to `V`. I thought I was adding it\n- I did not want to include loops, I will need to add checks for that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:18:46.170", "Id": "467367", "Score": "0", "body": "Put a remark between parentheses for point #2 - basically you didn't add to V - the vertex count even though only one vertex was known." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:49:32.237", "Id": "467433", "Score": "0", "body": "Thanks for modifying your comment and adding the code. It clarified a lot of doubts. I will read up more about KISS principles." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T10:59:03.483", "Id": "238299", "ParentId": "238296", "Score": "5" } }, { "body": "<p>Additional to these good answers a minor issue: using interfaces instead of concrete classes.</p>\n\n<p>When you're working with <code>List</code> it would be helpful to work with the interface instead of its concrete implementation, for instance:</p>\n\n<pre><code>//LinkedList&lt;Integer&gt; llOne = new LinkedList&lt;&gt;(); concrete\nList&lt;Integer&gt; llOne = ... //interface - as mentioned above consider better naming\n</code></pre>\n\n<p>same here:</p>\n\n<pre><code>//LinkedList&lt;Integer&gt; nodesList = adj.get(key); concrete\nList&lt;Integer&gt; nodesList = adj.get(key); //interface\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:24:36.720", "Id": "467322", "Score": "0", "body": "my bad - i was so fixed on the list i hit the wrong line ^_^ - `put` is valid for `Map`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:29:51.740", "Id": "467325", "Score": "1", "body": "Removed previous comment. Note also the use of `HashMap`. For local vars you can also use `var` (although then you need to parameterize the type on the right hand side)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:06:35.613", "Id": "467354", "Score": "0", "body": "I don't think I understand what you meant to say here.\nAre you saying that I should not write LinkedList but List?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:52:34.527", "Id": "238303", "ParentId": "238296", "Score": "3" } }, { "body": "<p><strong>Naming</strong></p>\n\n<p>Firstly, you must change the names from V to say \"numberOfVertices\" and \"E\" to numberOfEdges. The functions to get the numberOfVertices would be named as \"getNumberOfVertices\" and so on. Try to make the naming such that comments become entirely unnecessary.Similarly, adj should at least be named as \"adjacencyList\".</p>\n\n<pre><code>LinkedList&lt;Integer&gt; llOne = new LinkedList&lt;&gt;();\nLinkedList&lt;Integer&gt; llTwo = new LinkedList&lt;&gt;();\n</code></pre>\n\n<p>are also not suitably named.</p>\n\n<pre><code> StringBuilder returnString = new StringBuilder();\n</code></pre>\n\n<p>Bad name again. It does not convey any other information that it is supposed to be returned and it is a string.</p>\n\n<p><strong><em>Usability</em></strong></p>\n\n<p>How is this graph supposed to be used outside this class? The only information that you are allowing someone to access is the number of vertices, edges and stringified graph. How is the user of this class supposed to traverse this graph if he needs to? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T15:58:21.523", "Id": "238317", "ParentId": "238296", "Score": "1" } } ]
{ "AcceptedAnswerId": "238299", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T10:10:22.737", "Id": "238296", "Score": "5", "Tags": [ "java" ], "Title": "Basic abstract graph implementation in Java" }
238296
<p>I'm practicing recursive functions and I would be glad to receive some feedback for the following Python code I wrote. I did several tests and the function yielded correct results but I wonder if it can be written more concise or if it can be criticised in some way. Your feedback would help me become better. The functionality of the function is described in the docstring.</p> <pre><code>def roman(n): """Takes a roman number n as an argument (roman(n) assumes that the string n is correctly written, i.e. it provides no error-checking) and returns an integer.""" #The base-cases: if n == "": return 0 elif n == "M": return 1000 elif n == "D": return 500 elif n == "C": return 100 elif n == "L": return 50 elif n == "X": return 10 elif n == "V": return 5 elif n == "I": return 1 #If a smaller number precedes a bigger number, #then the smaller number is to be subtracted from #the bigger number. Else, it has to be added: else: if roman(n[0]) &lt; roman(n[1]): return (roman(n[1]) - roman(n[0])) + roman(n[2:]) else: return roman(n[0]) + roman(n[1:]) def main(n): print(roman(n)) main("MMMCMXCIX") </code></pre>
[]
[ { "body": "<p>Writing down all your basecases takes a lot of space. I would instead use a dictionary, which could even be a global constant.</p>\n<p>I find using <code>n</code> as an argument for something that is not an integer to be misleading. A generic <code>x</code> or <code>s</code> or <code>roman_numeral</code> would be clearer, IMO.</p>\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using four spaces as indentation.</p>\n<pre><code>BASE_CASES = {&quot;&quot;: 0, &quot;M&quot;: 1000, &quot;D&quot;: 500, &quot;C&quot;: 100, &quot;L&quot;: 50, &quot;X&quot;: 10, &quot;V&quot;: 5, &quot;I&quot;: 1}\n\ndef roman(s):\n &quot;&quot;&quot;Takes a roman number x as an argument and returns an integer.\n Assumes that the string is correctly written, i.e. it provides no error-checking.\n &quot;&quot;&quot;\n if s in BASE_CASES:\n return BASE_CASES[s]\n\n # If a smaller number precedes a bigger number, \n # then the smaller number is to be subtracted from \n # the bigger number. Else, it has to be added:\n first, second = map(roman, s[:2])\n if first &lt; second:\n return second - first + roman(s[2:])\n else:\n return first + roman(s[1:])\n</code></pre>\n<p>Of course, using a recursive approach in Python is usually not the best idea, converting it to an iterative approach is much better (i.e. usually faster and not fraught with stack limit issues):</p>\n<pre><code>from itertools import tee\n\ndef pairwise(iterable):\n &quot;s -&gt; (s0,s1), (s1,s2), (s2, s3), ...&quot;\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\ndef roman(s):\n if s in BASE_CASES:\n return BASE_CASES[s]\n return sum(first if first &gt;= second else second - first\n for first, second in pairwise(map(BASE_CASES.get, s)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:55:25.013", "Id": "238307", "ParentId": "238297", "Score": "6" } } ]
{ "AcceptedAnswerId": "238307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T10:35:48.357", "Id": "238297", "Score": "4", "Tags": [ "python", "recursion" ], "Title": "Recursively Convert Roman Number to Integer" }
238297
<p>So there is an existing codebase which calculates the total time worked per month.</p> <h3>What the code is doing:</h3> <ul> <li>iterates through all the working days entries</li> <li>retreives the value of net work time which is in format: <code>HH:mm</code></li> <li>calculates the minutes out of the net work time string</li> <li>formats the net work time to the report day row (back again) </li> <li>adds the daily calculated minutes to monthly total</li> <li>formats the total monthly minutes to the report totals row</li> </ul> <h3>Problem</h3> <p>The code randomly calculates the data properly. When data is calculated properly:</p> <ul> <li>the total is calculated properly,</li> <li>the day rows adds up to the total value</li> </ul> <p>When data is not properly calculated:</p> <ul> <li>the total has always 1h less</li> <li>every entry which does not have minutes part has 1h less which means that it does not even adds up to the wrongly calculated total</li> </ul> <p>To resolve the problem we obviously need to get rid of type conversion from <code>double</code> (<code>ts.TotalHours</code>) to <code>int</code></p> <p>But the questions are:</p> <ol> <li>Why the calculations are wrong randomly (or this is just my impression)?</li> <li>How to mimic the wrong calculation behavour in unit tests?</li> </ol> <p>Based on this SO thread: <a href="https://stackoverflow.com/q/47302758/1498401">https://stackoverflow.com/q/47302758/1498401</a> it seems that floating point calculation might be platform specific so additional information about server configuration:</p> <ul> <li>There are 2 fronted servers with win 2k12r2</li> </ul> <pre class="lang-cs prettyprint-override"><code>static int totalMinutesCounter { get; set; } public static string GetFormatedTime(string s, out int minutesCounter) { minutesCounter = 0; if (s == null) { return string.Empty; } int workedTimeMinutes = GetNumberOfMinutes(s); if (workedTimeMinutes &lt; 0) { throw new ArgumentOutOfRangeException("workedTimeHours", "Negative values not allowed"); } minutesCounter = workedTimeMinutes; TimeSpan ts = new TimeSpan(0, workedTimeMinutes, 0); return ((int)ts.TotalHours).ToString() + ts.ToString(@"\:mm"); } static string GetFormatedTimeFromMinutes(int minutes, ref int minutesCounter) { TimeSpan ts = new TimeSpan(0, minutes, 0); minutesCounter += minutes; return ((int)ts.TotalHours).ToString() + ts.ToString(@"\:mm"); } private static int GetNumberOfMinutes(string s) { if (string.IsNullOrWhiteSpace(s)) { return 0; } char[] charSeparators = new char[] { ':' }; string[] result = s.Split(charSeparators, StringSplitOptions.None); string sh = result[0].ToString(); string sm = result[1].ToString(); int hh = int.Parse(sh); int mm = int.Parse(sm); return mm + 60 * hh; } </code></pre> <p>My unit test i would like to see failing ;)</p> <pre class="lang-cs prettyprint-override"><code> [TestMethod] public void TestMethod1() { List&lt;string&gt; times = new List&lt;string&gt;() { "11:30","12:00","08:00","09:30","07:00","11:00","09:30","11:00","11:30","07:00","08:00","09:30","10:30","09:00","09:45","08:00","10:15","11:00","10:00" }; for (int i = 0; i &lt; 10000; i++) { foreach (var s in times) { int minutesCounter = 0; var rowValue = GetFormatedTime(s, out minutesCounter); totalMinutesCounter += minutesCounter; } int temp = 0; var result = GetFormatedTimeFromMinutes(totalMinutesCounter, ref temp); totalMinutesCounter = 0; Assert.AreEqual("184:00", result); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T18:00:14.070", "Id": "467373", "Score": "1", "body": "do you use 24 or 12 hours system ? and what is the table data structure (with datatype) that you are getting these timespans from ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:17:01.613", "Id": "467474", "Score": "0", "body": "also, we need a raw data sample from the application source. Without these two requirements, I believe you won't have a concrete answer to solve this issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T09:35:15.343", "Id": "467553", "Score": "0", "body": "@iSR5 we use 24 hour system. The concrete sample from application source code is overcomplicated, but the thing it does, it loops throught the sharepoint list timesheet entries, gets day net time in format HH:mm which is correct and then does the calculation as i've done it in this unit test scenario." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:34:02.957", "Id": "467558", "Score": "0", "body": "your comment made things clear and enough for me. Your main issue is that you're getting a 24 hour clock system, and treat it as 12 hour clock system, without the proper conversions. If you add \"00:05\" to your tests, it will only add 5 minutes to the results, which is false. it should add 1 hour and 5 minutes. So, you need to deal with it as 24 hours system or do proper conversion. the easiest way is to use `DateTime` and then work from there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:11:15.863", "Id": "467568", "Score": "0", "body": "I am confused. The times list contains the entries with net work time in single day, ie. 10:00 means 10 hours and 0 minutes, 13:15 means 13 hours and 15 minutes. So i don't see it that 00:05 entry should add 1 hour and 5 minutes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:14:22.293", "Id": "467569", "Score": "0", "body": "it is a typo. I meant 12 hour and 5 minutes. where \"00:05\" is 5 minutes passed midnight in 24 hour clock system." } ]
[ { "body": "<p>Why does your code pointlessly reinvent the wheel? Microsoft provides <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime\" rel=\"nofollow noreferrer\">methods to convert <code>string</code>s to <code>DateTime</code>s</a>; why not use those instead of your own clunky <code>GetNumberOfMinutes</code>? Or perhaps even better: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan.parse\" rel=\"nofollow noreferrer\">convert the <code>string</code> directly to a <code>TimeSpan</code></a>.</p>\n\n<p>On the subject of <code>GetNumberOfMinutes</code>: why even do <code>string sh = result[0].ToString();?</code> The result of <code>spring.Split</code> is an array of <code>string</code>s, why then the need to convert a <code>string</code> to a <code>string</code>? And that's just one of the things that are wrong with that method, there are several more.</p>\n\n<hr>\n\n<p>The whole flow of your code is IMHO needlessly complex. Why not simply convert each <code>time</code> to a <code>TimeSpan</code>, thus getting a <code>List&lt;TimeSpan&gt;</code>, then <a href=\"https://stackoverflow.com/a/4703056/648075\">calculate the amount of minutes</a>, add those up, and then convert those to a \"readable\" format?</p>\n\n<p>I don't even understand why you do this: <code>((int)ts.TotalHours).ToString() + ts.ToString(@\"\\:mm\");</code>. Surely this can be <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan\" rel=\"nofollow noreferrer\">expressed much more elegantly and readable</a>.</p>\n\n<hr>\n\n<p>On a general note: use proper, self-explanatory names for your variables, and not <code>ts</code> or <code>sh</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:53:36.330", "Id": "467334", "Score": "0", "body": "Thank you for your time, of course you're right, this code is wrong in many ways, but what i am really curious about is why it gives wrong/random calculations when deployed on web servers and does not in unit tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:47:47.567", "Id": "467432", "Score": "1", "body": "@tinamou Your bug is likely caused by converting vs casting, e.g. https://stackoverflow.com/questions/10754251/converting-a-double-to-an-int-in-c-sharp . What you should do is research how to do predictable rounding -- https://stackoverflow.com/questions/35409965/c-sharp-rounding-down-to-nearest-integer -- instead of trying to write tests that reproduce the bug." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:32:19.430", "Id": "238302", "ParentId": "238300", "Score": "3" } } ]
{ "AcceptedAnswerId": "238302", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T11:00:17.263", "Id": "238300", "Score": "2", "Tags": [ "c#", "floating-point" ], "Title": "C# calculate total time worked with TimeSpan" }
238300
<p><strong>TLDR</strong></p> <p>I created a curry/partial binding "lib. My request for "code review" is, what possible improvements I need to achieve "release quality", if I wanted to release this as a lib?</p> <p>You can see the end result here. <a href="https://godbolt.org/z/SnFnFt" rel="nofollow noreferrer">https://godbolt.org/z/SnFnFt</a></p> <p><strong>Complete story and analyzing the code</strong> </p> <p>This weekend I caught myself testing some new C++2x functionalities and come up with a "lib" that allow me to do this:</p> <pre><code>int sum(int a, int b, int c) { return a+b+c; } ... auto f = $(sum); std::cout &lt;&lt; "1: " &lt;&lt; f(1)(2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "2: " &lt;&lt; f(1,2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "3: " &lt;&lt; f(1)(2,3) &lt;&lt; std::endl; std::cout &lt;&lt; "4: " &lt;&lt; f(1,2,3) &lt;&lt; std::endl; std::cout &lt;&lt; "5: " &lt;&lt; (f &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3)() &lt;&lt; std::endl; std::cout &lt;&lt; "6: " &lt;&lt; (f &lt;&lt; 1 &lt;&lt; 2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "7: " &lt;&lt; (f &lt;&lt; 1)(2, 3) &lt;&lt; std::endl; ... auto v = std::vector&lt;int&gt;{1,2,3}; std::transform(std::begin(v), std::end(v), std::begin(v), $$( $(sum) &lt;&lt; 1 &lt;&lt; 2, $(times) &lt;&lt; 2) ); std::cout &lt;&lt; "11: " &lt;&lt; v &lt;&lt; std::endl; </code></pre> <p>Complete code is at the end of this post. I will try to explain my rationale and the code as much as possible here.</p> <p>The code relies heavily on "parameter pack" and "fold expressions" and very complex enable_if. Truly the only complex and hard-to-read part of the code, in my opinion. But let me try to explain it as much as possible.</p> <p>It all start at the function <code>$</code>. <code>TF</code> here is meant to be callable. <code>TF*</code> is, of course, a pointer to this callable. In the example above, a pointer to <code>sum</code>. All I do here is create my wrapper class and return it. All the "magic" will happen in side this wrapper.</p> <pre><code>template &lt;typename TF&gt; auto $(TF* f) { return typename make_f&lt;TF&gt;::type { std::make_tuple(f) }; } </code></pre> <p>Here I have my first problem. To create my wrapper I need to know all <code>TF</code> arguments types, because I will use them to guarantee the binding is correct.</p> <p>There is a "very easy way" to do this.</p> <pre><code>template&lt;typename... TArgs&gt; struct types { using type = std::tuple&lt;TArgs...&gt;; }; template&lt;class T&gt; struct args; template&lt;class TReturn, class... TArgs&gt; struct args&lt;TReturn (TArgs...)&gt; : types&lt;TArgs...&gt; {}; template&lt;class TReturn, class... TArgs&gt; struct args&lt;TReturn (*)(TArgs...)&gt; : types&lt;TArgs...&gt; {}; template&lt;class T&gt; using args_t = typename args&lt;T&gt;::type; </code></pre> <p>So <code>args_t&lt;(int (*) (int,int)&gt;</code> returns <code>std::tuple&lt;int,int&gt;</code>.<br> See more here: <a href="https://godbolt.org/z/h4sbtW" rel="nofollow noreferrer">https://godbolt.org/z/h4sbtW</a></p> <p>With this I can build my wrapper type with:</p> <pre><code>using type = Func&lt;TF, args_t&lt;TF&gt;, std::tuple&lt;TF*&gt;&gt;; </code></pre> <p>This is the type of the wrapper completely unbound. Its template parameters are: 1 - function type;<br> 2 - <code>std:tuple</code> of TF arguments, as we saw above'<br> 3 - <code>std:tuple</code> of all bound parameters so far. Up until now just the function pointer. </p> <p>The idea now is that everytime you give one more argument, I store in a "bigger" tuple with <code>std::tuple_cat(old, new_argument)</code>, until this "catted" tuple matches the function definition.</p> <p>Then I just call the target function.</p> <p>The "heart" of the code that does that is:</p> <pre><code>template &lt;typename TF, typename... TArgs, typename... TBounds&gt; struct Func&lt;TF, std::tuple&lt;TArgs...&gt;, std::tuple&lt;TF*, TBounds...&gt;&gt; { ... // all args to the target function using tuple_args = std::tuple&lt;TArgs...&gt;; // bound args so far using tuple_bound = std::tuple&lt;TF*, TBounds...&gt;; ... // bound args store in a tuple tuple_bound bound; ... // magic happen here: bind, partial apply on operator() template &lt; typename... TBinds, size_t QTD = sizeof...(TBinds), // avoid binding more arguments than possible typename = std::enable_if_t&lt;QTD &lt;= (sizeofArgs - sizeofBounds)&gt;, // test if arguments types match, otherwise generate compiler error // more on this below typename = std::enable_if_t&lt; types_match&lt; sizeofBounds, tuple_args, std::tuple&lt;TBinds...&gt;, std::make_index_sequence&lt;sizeof...(TBinds)&gt; &gt;::type::value &gt; &gt; auto operator() (TBinds... binds) { auto newf = Func&lt;TF, tuple_args, std::tuple&lt;TF*, TBounds..., TBinds...&gt; &gt; { std::tuple_cat(bound, std::make_tuple(binds...)) }; // if we bound exactly the number of args, call target function // else returns a partial applied function if constexpr (QTD == (sizeofArgs - sizeofBounds)) return newf(); else return newf; } } </code></pre> <p>I have a "Func" template specialization for when the bind is complete:</p> <pre><code>template &lt;typename TF, typename... TArgs&gt; struct Func&lt;TF, std::tuple&lt;TArgs...&gt;, std::tuple&lt;TF*, TArgs...&gt;&gt; { std::tuple&lt;TF*, TArgs...&gt; bound; auto operator() () { return std::apply(fwd, bound); } static auto fwd(TF* f, TArgs... args) { return f(args...); } }; </code></pre> <p>It guarantees that only the exact types are bound and it only allows you to call the function. In theory it represents a "auto (*) ()" function. If that was possible.</p> <p>One nice feature of all of this, is that I can generate an (horrible) compile error when you try to bind arguments with the wrong type. This is done by the <code>enable_if</code> below that exists on the "operator ()" of the Func class.</p> <pre><code>template &lt; // all new arguments that you are trying to bind typename... TBinds, // enabled only if the new binds match possible arguments typename = std::enable_if_t&lt; types_match&lt; sizeofBounds, tuple_args, std::tuple&lt;TBinds...&gt;, std::make_index_sequence&lt;sizeof...(TBinds)&gt; &gt;::type::value </code></pre> <p>The "magic" here is:</p> <p>1 - <code>tuple_args</code> would be, for example, <code>std:tuple&lt;int,int&gt;</code>;<br> 2 - We have not bound anything yet, so <code>sizeofBounds</code> is zero, and we are passing <code>TBinds...</code> new arguments. So, I need to check if these new types match what is expected. I do this with the <code>types_match</code> type trait. It receives two <code>std::tuple</code> and an offset, and check if their types match. </p> <p>Something like this.</p> <pre><code>std::is_same&lt; decltype(std::get&lt;0&gt;(tuple1), decltype(std::get&lt;0 + OFFSET&gt;(tuple2) &gt; &amp;&amp; std::is_same&lt; decltype(std::get&lt;1&gt;(tuple1), decltype(std::get&lt;1 + OFFSET&gt;(tuple2) &gt; &amp;&amp; ... </code></pre> <p>See more here: <a href="https://godbolt.org/z/wG8JYr" rel="nofollow noreferrer">https://godbolt.org/z/wG8JYr</a> </p> <p>This allows you to bind any number of arguments at any time. The only constraints are that the types must match, and you cannot bind more than needed.</p> <p>All of this seems like a huge burden to a simple function call, but "Godbolting" this with:</p> <pre><code>($(sum) &lt;&lt; rand() &lt;&lt; rand() &lt;&lt; rand())(); </code></pre> <p>generates:</p> <pre><code>call rand mov ebx, eax # ebx = rand() call rand mov ebp, eax # ebp = rand() call rand # eax = rand() add ebp, ebx add ebp, eax # ebp = ebp + ebx + eax </code></pre> <p>Which I consider a wonderful result. The compiler optimization killed everything. Wonderful beasts they are!</p> <p>I even did a small performance test to assert this. The performance is pretty much identical to normally calling the function.</p> <p><a href="https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/main.cpp#L87" rel="nofollow noreferrer">https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/main.cpp#L87</a></p> <pre><code>TEST_CASE("Func.Performance.Should not be slower than manual code", "[ok]") { using namespace std; // I will generate some random numbers below random_device rnd_device; mt19937 mersenne_engine{ rnd_device() }; uniform_int_distribution&lt;int&gt; dist{ 1, 52 }; auto gen = [&amp;dist, &amp;mersenne_engine]() { return dist(mersenne_engine); }; vector&lt;int&gt; vec(3); std::clock_t start; start = std::clock(); // Benchmark. Manual calling sum with tree random numbers /* MANUAL CODE */ auto r = true; for (int i = 0; i &lt; 10000000; ++i) { generate(begin(vec), end(vec), gen); auto expected = sum(vec[0], vec[1], vec[2]); //using this just to guarantee that the compiler will not drop my code. r &amp;= (sum(vec[0], vec[1], vec[2]) == expected); } /* MANUAL CODE */ auto manualTime = (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000); start = std::clock(); // Now we are using the "lib" code /* FUNC CODE */ auto rr = true; for (int i = 0; i &lt; 10000000; ++i) { generate(begin(vec), end(vec), gen); auto expected = sum(vec[0], vec[1], vec[2]); auto f = $(sum) &lt;&lt; vec[0] &lt;&lt; vec[1] &lt;&lt; vec[2]; // again just to guarantee nothing is dropped. rr &amp;= (f() == expected); } /* FUNC CODE */ auto funcTime = (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000); std::cout &lt;&lt; "manual: " &lt;&lt; manualTime &lt;&lt; ", func: " &lt;&lt; funcTime &lt;&lt; " (func/manual = " &lt;&lt; (float)funcTime / (float)manualTime &lt;&lt; ")" &lt;&lt; std::endl; REQUIRE(r == rr); // Assert that we are inside a "noise threshold" in RELEASE #ifdef NDEBUG REQUIRE(funcTime &lt; (manualTime * 1.05)); // Func cannot be 5% slower than manual code #endif } </code></pre> <p>Complete code using the "lib":<br> <a href="https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/main.cpp" rel="nofollow noreferrer">https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/main.cpp</a></p> <p>Possible steps would be: </p> <p>1 - Test with member function;<br> 2 - Test functions with (references, pointers, moves etc...);<br> 3 - Test with Polymorphism;<br> 4 - Test with unmaterialized templates;<br> 5 - The pipeline function creates a tuple of "constructed" objects. Is this avoidable?<br> 6 - Test bounding High-Order-Functions with other function and "partial applied" function.<br> 7 - Test with more callback, events, observers etc... systems. </p> <p>Complete "lib" code:<br> <a href="https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/func.h" rel="nofollow noreferrer">https://github.com/xunilrj/sandbox/blob/master/sources/cpp/func/func.h</a></p> <p>Me going through what/why and how:<br> <a href="https://github.com/xunilrj/sandbox/tree/master/sources/cpp/func" rel="nofollow noreferrer">https://github.com/xunilrj/sandbox/tree/master/sources/cpp/func</a></p> <p><strong>Complete code</strong></p> <pre><code>#include &lt;tuple&gt; #include &lt;iostream&gt; #include &lt;type_traits&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; template &lt;typename TF, typename TArgs, typename TBound&gt; struct Func{}; template &lt;typename TF, typename... TArgs&gt; struct Func&lt;TF, std::tuple&lt;TArgs...&gt;, std::tuple&lt;TF*, TArgs...&gt;&gt; { std::tuple&lt;TF*, TArgs...&gt; bound; auto operator() () { return std::apply(fwd, bound); } static auto fwd(TF* f, TArgs... args) { return f(args...); } }; template &lt;typename TF, typename... TArgs, typename... TBounds&gt; struct Func&lt;TF, std::tuple&lt;TArgs...&gt;, std::tuple&lt;TF*, TBounds...&gt;&gt; { using result_of = std::invoke_result_t&lt;TF, TArgs...&gt;; using tuple_args = std::tuple&lt;TArgs...&gt;; using tuple_bound = std::tuple&lt;TF*, TBounds...&gt;; constexpr static size_t sizeofArgs = sizeof...(TArgs); constexpr static size_t sizeofBounds = sizeof...(TBounds); using next_argument = std::tuple_element_t&lt;sizeofBounds, tuple_args&gt;; tuple_bound bound; template &lt;size_t OFFSET, typename TAs, typename TBs, typename SQ&gt; struct types_match {}; template &lt;size_t OFFSET, typename TAs, typename TBs, size_t... IA&gt; struct types_match&lt;OFFSET, TAs, TBs, std::index_sequence&lt;IA...&gt; &gt; { using type = std::conjunction&lt; std::is_same&lt; std::tuple_element_t&lt;OFFSET + IA, TAs&gt;, std::tuple_element_t&lt;IA, TBs&gt; &gt;... &gt;; }; template &lt; typename... TBinds, size_t QTD = sizeof...(TBinds), typename = std::enable_if_t&lt;QTD &lt;= (sizeofArgs - sizeofBounds)&gt;, typename = std::enable_if_t&lt; types_match&lt; sizeofBounds, tuple_args, std::tuple&lt;TBinds...&gt;, std::make_index_sequence&lt;sizeof...(TBinds)&gt; &gt;::type::value &gt; &gt; auto operator() (TBinds... binds) { auto newf = Func&lt;TF, tuple_args, std::tuple&lt;TF*, TBounds..., TBinds...&gt; &gt; { std::tuple_cat(bound, std::make_tuple(binds...)) }; if constexpr (QTD == (sizeofArgs - sizeofBounds)) return newf(); else return newf; } template &lt; typename... TBinds, size_t QTD = sizeof...(TBinds), typename = std::enable_if_t&lt;QTD &lt;= (sizeofArgs - sizeofBounds)&gt;, typename = std::enable_if_t&lt; types_match&lt; sizeofBounds, tuple_args, std::tuple&lt;TBinds...&gt;, std::make_index_sequence&lt;sizeof...(TBinds)&gt; &gt;::type::value &gt; &gt; auto operator &lt;&lt; (TBinds... binds) { auto newf = Func&lt;TF, tuple_args, std::tuple&lt;TF*, TBounds..., TBinds...&gt; &gt; { std::tuple_cat(bound, std::make_tuple(binds...)) }; return newf; } }; template &lt;typename TF&gt; struct make_f { template&lt;typename... TArgs&gt; struct types { using type = std::tuple&lt;TArgs...&gt;; }; template&lt;class Sig&gt; struct args; template&lt;class R, class...Args&gt; struct args&lt;R (Args...)&gt; : types&lt;Args...&gt; { }; template&lt;class R, class...Args&gt; struct args&lt;R (*)(Args...)&gt; : types&lt;Args...&gt; { }; template&lt;class Sig&gt; using args_t = typename args&lt;Sig&gt;::type; using type = Func&lt;TF, args_t&lt;TF&gt;, std::tuple&lt;TF*&gt;&gt;; }; template &lt;typename TF&gt; auto $(TF* f) { return typename make_f&lt;TF&gt;::type { std::make_tuple(f) }; } template &lt;typename Fs1, typename... Fs&gt; struct pipeline { using functions_type = std::tuple&lt; Fs1, Fs... &gt;; functions_type fs; using data_type = std::tuple&lt; typename Fs1::next_argument, typename Fs1::result_of, typename Fs::result_of... &gt;; data_type t; pipeline(Fs1 fs1, Fs... fs) : fs{fs1, fs...}, t{} { } auto operator() (typename Fs1::next_argument arg) { std::get&lt;0&gt;(t) = arg; call_pipe(t, fs, std::make_index_sequence&lt;sizeof...(Fs) + 1&gt;{} ); return std::get&lt;std::tuple_size_v&lt;data_type&gt; - 1&gt;(t); } template &lt;size_t... Is&gt; void call_pipe(data_type&amp; t, functions_type&amp; fs, std::index_sequence&lt;Is...&gt; s) { (( std::get&lt;Is + 1&gt;(t) = std::get&lt;Is&gt;(fs) ( std::get&lt;Is&gt;(t) ) ),...); } }; template &lt;typename Fs1, typename... Fs&gt; auto $$(Fs1 fs1, Fs... fs) { return pipeline{fs1, fs...}; } template&lt;typename T&gt; std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, const std::vector&lt;T&gt;&amp; items) { out &lt;&lt; "["; for(auto&amp;&amp; x : items) out &lt;&lt; x &lt;&lt; ","; return out &lt;&lt; "]"; } int sum(int a, int b, int c) { return a+b+c; } int times(int a, int b) { return a*b; } int main (int argc, char** argv) { auto f = $(sum); std::cout &lt;&lt; "1: " &lt;&lt; f(1)(2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "2: " &lt;&lt; f(1,2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "3: " &lt;&lt; f(1)(2,3) &lt;&lt; std::endl; std::cout &lt;&lt; "4: " &lt;&lt; f(1,2,3) &lt;&lt; std::endl; std::cout &lt;&lt; "5: " &lt;&lt; (f &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3)() &lt;&lt; std::endl; std::cout &lt;&lt; "6: " &lt;&lt; (f &lt;&lt; 1 &lt;&lt; 2)(3) &lt;&lt; std::endl; std::cout &lt;&lt; "7: " &lt;&lt; (f &lt;&lt; 1)(2, 3) &lt;&lt; std::endl; auto v = std::vector&lt;int&gt;{1,2,3}; std::transform(std::begin(v), std::end(v), std::begin(v), $(times) &lt;&lt; 2); std::cout &lt;&lt; "8: " &lt;&lt; v &lt;&lt; std::endl; std::transform(std::begin(v), std::end(v), std::begin(v), $(times)(2)); std::cout &lt;&lt; "9: " &lt;&lt; v &lt;&lt; std::endl; auto p1 = $$($(sum) &lt;&lt; 1 &lt;&lt; 2, $(times) &lt;&lt; 2); std::cout &lt;&lt; "10: " &lt;&lt; p1(4) &lt;&lt; std::endl; std::transform(std::begin(v), std::end(v), std::begin(v), $$($(sum) &lt;&lt; 1 &lt;&lt; 2, $(times) &lt;&lt; 2)); std::cout &lt;&lt; "11: " &lt;&lt; v &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:28:06.273", "Id": "467324", "Score": "1", "body": "Welcome to Code Review! You've shown us the left ventricle of your heart - the most important part, but we also need to examine the other three chambers in order to effectively assess the circulatory ability of your heart, which are unfortunately hidden behind `...`s. (Sorry if anything's wrong with this metaphor - my biology isn't competent!) In order words, the code you presented in its current form is not meaningfully reviewable, because it lacks too much detail. Post more code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:01:25.450", "Id": "467329", "Score": "0", "body": "No problem. Let us strip the rest of the organs!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:07:43.227", "Id": "467330", "Score": "0", "body": "In fact, I'd suggest posting the complete code from the godbolt link, including the tests. It's not that much code, and showing the complete implementation really helps generate better reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:53:46.120", "Id": "467335", "Score": "0", "body": "Done. I also included the performance test and two more links to godbolt of smaller parts. I think that will be helpful." } ]
[ { "body": "<p>This is a cool idea. You can improve the code by using the STL utilities that support currying/composition.</p>\n\n<p>For currying, there is <code>std::bind</code> and <code>std::bind_front</code>:</p>\n\n<pre><code>// this is the STL way to curry functions\nauto demoSTL() {\n auto sum1 = std::bind_front(sum, 1);\n auto sum123 = std::bind_front(sum1, 2, 3);\n auto call = sum123();\n return call;\n}\n</code></pre>\n\n<p>You can make template wrappers around <code>std::bind_front</code> to make the interface look like your <code>$</code> function. Here's some starter code: <a href=\"https://godbolt.org/z/S-kni4\" rel=\"nofollow noreferrer\">https://godbolt.org/z/S-kni4</a>.</p>\n\n<p>One major advantage of the STL functions is that they do type checking for you. It's always nice to have (relatively) bug free code written for you for free! So you might as well use that instead of writing complex <code>enable_if</code>s and <code>tuple_cat</code>s.</p>\n\n<p>One of the hard parts of currying as you've implemented it is checking whether the <code>operator()</code> should return a value or another currying object. This is a bit easier if you are restricted to function pointers (as your code is). But if you want to support all callables, it's harder. Consider this case:</p>\n\n<pre><code>struct Overloaded {\n int foo(int) { /*...*/ }\n int foo(int, int) { /*...*/ }\n};\n</code></pre>\n\n<p>What should <code>$(foo)(1)</code> do? Should it call the first overload or curry the second one?</p>\n\n<p>You can get around this problem and simplify your code by changing the interface a little bit. Let the user decide when a function should be called. Then <code>$(foo)(1)()</code> calls the first overload and <code>$(foo)(1)(2)()</code> calls the second overload. Let <code>std::bind_front</code> deal with compiler errors in case the programmer puts the call in the wrong place. This allows you to support all callables.</p>\n\n<p>I don't have as much to say about composition. Note that the raw language already has good support for composition with calls like <code>multiply2(sum4(5))</code> (or a lambda that does the same thing)... if you would rather write <code>compose(sum4, multiply2)(5)</code> then you can write wrappers, but it gets a pretty ugly (IMO) when you have more than one input/output. Might be easier to just write a lambda every time you want to compose functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T19:08:21.203", "Id": "240002", "ParentId": "238306", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T12:14:26.233", "Id": "238306", "Score": "1", "Tags": [ "c++", "functional-programming" ], "Title": "Functional Utility in C++ (Curry, Partial Binding and Pipeline)" }
238306
<p>I am new to programming, and I wanted to ask, is my code inefficient / poorly written?</p> <p>Here is my code below for an exercise I just did. The point is for the user to guess the number 0, but it also:</p> <ul> <li>Calculates the average number</li> <li>Calculates the number of attempts</li> <li>Gives the sum of attempts </li> </ul> <p>Are there ways of improving this code? If so, how do you know where to look? Am I overusing <code>if</code>/<code>while</code> statements?</p> <pre><code>#User must guess a number: until they reach value of 0 #Must calculate average sum of guesses, track sum of numbers entered, keep count of attempts guess = '' count = 0 total_sum = 0 while guess != 0: print("Guess the number: ") guess = int(input()) #Count no. of attempts count += 1 #Total Sum of guesses total_sum += guess if guess == 0: print("Congratulations!, you guessed the correct number") #Average number of guesses try: average = (total_sum / (count - 1)) print("Average number:", average) except ZeroDivisionError: print("No average") print("Attempts: ", count) print("Total sum of guesses: ", total_sum) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:25:49.500", "Id": "467339", "Score": "2", "body": "To know if something is inefficient you run it and if it takes too long to run, then that's normally a hint. From there you [profile](https://en.wikipedia.org/wiki/Profiling_(computer_programming)) your code and determine the [complexity](https://en.wikipedia.org/wiki/Big_O_notation) of the offending code, to see if you can get something better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:28:01.707", "Id": "467340", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." } ]
[ { "body": "<p>Well, I always start with <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">using a main block.</a> It's just a good habit to have.</p>\n\n<p>Name your constants. What if you wanted the change the number the user was supposed to guess to, say, 5? You already have at least two places in the code where 0 shows up, and what you actually mean by that is \"the target value\". Give it a name and use that name.</p>\n\n<pre><code>target = 0\n\nwhile guess != target: # ...\n</code></pre>\n\n<p>You're checking the game-end logic twice, once in the outer <code>while</code> loop, once in the inner <code>if</code> check. <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Only do so in one place</a>. E.g., make the outer loop <code>while True:</code> or, better yet, <code>for _ in range(max_num_guesses):</code> with an explicitly set maximum number of guesses. Then, inside the <code>if</code> statement that checks if the user got the answer right, just <code>break</code> to exit the loop.</p>\n\n<p>Now, about what you particularly ask about: computing the sum/mean/count of the users' guesses. Your current approach scatters the logic of what you're trying to do: summation happens on one line, counting on another, division on another... this code sample isn't big, but already this goal is scattered across your code. It'd be a lot cleaner if we dealt with all those similar things in one place. To do this, let's just keep track of the guesses inside the loop, then later, we'll do all the relevant computations with them. Something like:</p>\n\n<pre><code>target = 0\nguesses = []\n\nwhile True:\n print(\"Guess the number: \")\n guess = int(input())\n guesses.append(guess)\n\n if guess == target:\n break\n\n print(\"Nope.\")\n\nprint(f\"Attempts: {len(guesses)}\")\nprint(f\"Total sum of guesses: {sum(guesses)}\")\nprint(f\"Average guess: {sum(guesses) / len(guesses)}\")\n</code></pre>\n\n<p>This snippet doesn't do exactly what your code does, but hopefully it gives you an idea for how you can keep different chunks of your code focused on different purposes, and thus keep each bit clean and keep the logic simple. See how the <code>while</code>-loop section is solely focused on running the game logic, and the <code>print</code> section is solely focused on what details you want to print back to the user. The only crossover is the the <code>guesses.append(guess)</code> line in the loop, which just says \"I'll want this info later\" and let you, later, figure out exactly what you want to do. E.g., let's say you wanted to report the median guess, or how many guesses were above versus below the target; these are easy to add later if we have a list of guesses, but would add yet more fluff to the loop if we tried to keep track as we went along. Note that, since you're just keeping track of user input, this list is never expected to get so big that counting and summing it is worth bothering about; even if you want to report this value in each loop iteration, just compute it each time rather than trying to calculate things incrementally.</p>\n\n<p>Oh, and finally, <a href=\"https://stackoverflow.com/questions/7604636/better-to-try-something-and-catch-the-exception-or-test-if-its-possible-first\">while I'm all for the try-and-fail</a> when it makes your code cleaner, this probably isn't such an occasion. I'd consider:</p>\n\n<pre><code>if count &gt; 1:\n average = (total_sum / (count - 1))\n print(\"Average number:\", average)\nelse:\n print(\"No average\")\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>print(f\"Average number: {total_sum / (count - 1)}\" if count &gt; 1 else \"No average\")\n</code></pre>\n\n<p>to be cleaner than using a <code>try/except ZeroDivisionError</code> here.</p>\n\n<p>(PS: Note the use of f-strings rather than relying on the <code>print</code> function to append things to strings... that's also a good habit, though not a significant improvement in this particular case.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:24:04.100", "Id": "238383", "ParentId": "238313", "Score": "3" } } ]
{ "AcceptedAnswerId": "238383", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:21:28.013", "Id": "238313", "Score": "2", "Tags": [ "python", "python-3.x", "number-guessing-game" ], "Title": "Number guessing game with statistics" }
238313
<h1>Introduction</h1> <p>By default, input streams (e.g., <code>std::cin</code> or a <code>std::istringstream</code>) split words at space when using the <code>&gt;&gt;</code> operator. If we want to split at other characters (e.g., <code>\n</code>), we need to use <code>std::getline</code>:</p> <pre><code>std::vector&lt;std::string&gt; lines; for (std::string line; std::getline(std::cin, line);) { lines.push_back(std::move(line)); } </code></pre> <p>However, many interfaces are designed for use with <code>&gt;&gt;</code> only (e.g., <code>std::istream_iterator</code> or the typical <code>operator&gt;&gt;</code> of a container). I implemented a <strong>custom manipulator</strong> that allows the user to specify at which characters words should be split, so that the aforementioned loop can be converted into a call to <code>std::copy</code>: (hopefully the awkward syntax can get better with C++20 ranges)</p> <pre><code>std::cin &gt;&gt; set_delim("\n"); // magic here std::vector&lt;std::string&gt; lines; std::copy(std::make_move_iterator(std::istream_iterator&lt;std::string&gt;{std::cin}), std::make_move_iterator(std::istream_iterator&lt;std::string&gt;{}), std::back_inserter(lines)); </code></pre> <p><code>set_delim</code> can also be used for other purposes &mdash; for example, <code>&gt;&gt; set_delim(",")</code> helps when parsing comma-separated lists. More than one delimiter can be supplied &mdash; for example, <code>&gt;&gt; set_delim("0123456789")</code> causes <code>01I2know34I'm5not678alone9</code> to be parsed as <code>I</code> <code>know</code> <code>I'm</code> <code>not</code> <code>alone</code>.</p> <h1>Implementation notes</h1> <p>The whitespace behavior of <code>std::istream</code> is not easily customizable; what I did is change the underlying <code>ctype</code> facet of locale associated with the stream. Here are some points to consider:</p> <ul> <li><p>We are overwriting how <code>isspace</code> of the locale works, but other properties are retained. For example, after <code>std::cin &gt;&gt; set_delim(',')</code>, <code>std::isspace(' ', std::cin.getloc())</code> is no longer true, but <code>std::isalpha('A', std::cin.getloc())</code> is still true. There are some test cases about this point in the online demonstration.</p></li> <li><p>The interface of <code>std::ctype&lt;char&gt;</code> (lookup tables) is fundamentally different from that of the other specializations of <code>std::ctype</code> (virtual functions). I only implemented the <code>char</code> case for simplicity. The implementation basically builds up a new lookup table by modifying that of the underlying locale (see the previous point).</p></li> <li><p><code>set_delim</code> is intended to be used as a manipulator only, so it uses <code>std::string_view</code> internally to pass the delimiters. Thing like</p> <pre><code>auto manip = set_delim(std::to_string(42)); std::cin &gt;&gt; manip; </code></pre> <p>will cause dangling pointers.</p></li> </ul> <h1>Code</h1> <p>set_delim.hpp</p> <pre><code>#ifndef INC_SET_DELIM_HPP_DbZxaxlZMs #define INC_SET_DELIM_HPP_DbZxaxlZMs #include &lt;algorithm&gt; #include &lt;istream&gt; #include &lt;locale&gt; #include &lt;string&gt; #include &lt;string_view&gt; namespace detail { // generate std::ctype&lt;char&gt; style mask table // allocated with new to fit the std::ctype&lt;char&gt; interface // the std::ctype&lt;char&gt; constructor should be called with del = true const std::ctype_base::mask* new_table(std::string_view delim, std::locale underlying_locale) { static constexpr auto table_size = std::ctype&lt;char&gt;::table_size; auto underlying_table = std::use_facet&lt;std::ctype&lt;char&gt;&gt;(underlying_locale).table(); auto table = new std::ctype_base::mask[table_size]; // copy underlying table, with the space mask unset std::transform(underlying_table, underlying_table + table_size, table, [](std::ctype_base::mask mask) { return mask &amp; ~std::ctype_base::space; }); // set the space mask for delimiters for (auto c : delim) { table[static_cast&lt;unsigned char&gt;(c)] |= std::ctype_base::space; } return table; } class ctype_space : public std::ctype&lt;char&gt; { using Base = std::ctype&lt;char&gt;; public: ctype_space(std::string_view d, std::locale l) : Base{new_table(d, l), true} { } }; struct set_delim_manip { std::string_view delim; }; std::istream&amp; operator&gt;&gt;(std::istream&amp; is, set_delim_manip manip) { auto underlying_locale = is.getloc(); is.imbue(std::locale{ underlying_locale, new ctype_space{manip.delim, underlying_locale} }); return is; } } auto set_delim(std::string_view delim) { return detail::set_delim_manip{delim}; } #endif </code></pre> <p>An <a href="https://wandbox.org/permlink/N9njUZubldi2PGsE" rel="noreferrer">online demonstration</a> with test cases is available on Wandbox.</p> <h1>Usage example</h1> <pre><code>#include "set_delim.hpp" #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; int main() { std::cin &gt;&gt; set_delim(","); std::copy(std::istream_iterator&lt;std::string&gt;{std::cin}, std::istream_iterator&lt;std::string&gt;{}, std::ostream_iterator&lt;std::string&gt;{std::cout, "\n"}); } </code></pre> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>a b, c d ,e f </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>a b c d e f </code></pre> <p>(The second line has a trailing space.)</p> <p><a href="https://wandbox.org/permlink/dCz6etueNdLl9GGN" rel="noreferrer">live demo</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:18:58.927", "Id": "467358", "Score": "2", "body": "I find the set_delim(\"1234567890\") very unintuitive. I would expect the entire sequence to be the delimiter. Instead you could provide an overload accepting two input iterators representing a range in container containing the allowed delimiters as individual container elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:46:47.050", "Id": "467362", "Score": "1", "body": "That's a clever idea, to use the facet like that. I'm impressed!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T21:37:49.287", "Id": "467384", "Score": "1", "body": "Love it. Always a fan of using local and facet to simplify the usage of streams. Very good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T07:58:25.650", "Id": "467410", "Score": "0", "body": "Very good work." } ]
[ { "body": "<p>I could have written the code better ...</p>\n\n<hr>\n\n<h1>Removing violation of the one-definition rule</h1>\n\n<p>I made a silly mistake &mdash; I violated the one-definition rule by failing to mark the following functions <code>inline</code>:</p>\n\n<ul>\n<li><p><code>new_table</code></p></li>\n<li><p><code>operator&gt;&gt;</code></p></li>\n<li><p><code>set_delim</code></p></li>\n</ul>\n\n<p>I was too accustomed to writing templates ...</p>\n\n<hr>\n\n<h1>Preserving the <code>toupper</code>, etc. behavior of the original locale</h1>\n\n<p>The <code>ctype_space</code> facet inherits from <code>std::ctype&lt;char&gt;</code> rather than the type of the current facet in the locale because dynamically determining the base type to derive from is not possible. Unfortunately, this also means that the overridden versions of virtual functions are lost. Copying the underlying lookup table ensures that the semantics of the <code>is</code> function is preserved because they use the table instead of relying on dynamic dispatching; however, the following functions use dynamic dispatching and their custom semantics is lost:</p>\n\n<ul>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/locale/ctype/toupper\" rel=\"nofollow noreferrer\"><code>toupper</code></a></p></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/locale/ctype/tolower\" rel=\"nofollow noreferrer\"><code>tolower</code></a></p></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/locale/ctype/widen\" rel=\"nofollow noreferrer\"><code>widen</code></a></p></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/locale/ctype/narrow\" rel=\"nofollow noreferrer\"><code>narrow</code></a> (takes an additional fallback character argument)</p></li>\n</ul>\n\n<p>The protected virtual <code>do_</code> version of each of these functions has two overloads, operating on a single character and a sequence of characters respectively.</p>\n\n<p>Correctly forwarding the behavior of the original facet requires storing the underlying locale:</p>\n\n<pre><code>class ctype_space : public std::ctype&lt;char&gt; {\n using Base = std::ctype&lt;char&gt;;\n std::locale underlying_locale;\n\n const Base&amp; underlying_facet() const\n {\n return std::use_facet&lt;Base&gt;(underlying_locale);\n }\npublic:\n ctype_space(std::string_view d, std::locale l)\n : Base{new_table(d, l), true}\n , underlying_locale{l}\n {\n }\n char do_toupper(char c) const override\n {\n return underlying_facet().toupper(c);\n }\n const char* do_toupper(char* first, const char* last) const override\n {\n return underlying_facet().toupper(first, last);\n }\n char do_tolower(char c) const override\n {\n return underlying_facet().tolower(c);\n }\n const char* do_tolower(char* first, const char* last) const override\n {\n return underlying_facet().tolower(first, last);\n }\n char do_widen(char c) const override\n {\n return underlying_facet().widen(c);\n }\n const char* do_widen(const char* begin, const char* end, char* dest) const override\n {\n return underlying_facet().widen(begin, end, dest);\n }\n char do_narrow(char c, char fallback) const override\n {\n return underlying_facet().narrow(c, fallback);\n }\n const char* do_narrow(const char* begin, const char* end,\n char fallback, char* dest) const override\n {\n return underlying_facet().narrow(begin, end, fallback, dest);\n }\n};\n</code></pre>\n\n<hr>\n\n<h1>Minimizing usage of <code>new</code></h1>\n\n<p>The <code>new_table</code> function allocates memory for the lookup table using <code>new</code>. The underlying facet is responsible for deleting the memory because I passed <code>del = true</code> to the constructor. I should have used <code>std::unique_ptr</code> to control the memory and <code>release</code> the ownership at the end to ensure exception safety.</p>\n\n<p>But now that I think of it, I don't need dynamic allocation at all. I can simply make the table a member of the <code>ctype_space</code> facet, and pass <code>del = false</code>. The table will still live as long as the underlying facet.</p>\n\n<hr>\n\n<p>I'm pretty sure I came up with a fourth issue at some time, but I can't seem to recall it right now ...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T11:16:37.777", "Id": "238760", "ParentId": "238315", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T14:58:56.650", "Id": "238315", "Score": "6", "Tags": [ "c++", "c++17", "stream", "localization" ], "Title": "Custom manipulator for changing at what characters a std::istream split words" }
238315
<p>I've been working on re-writing <a href="https://codegolf.stackexchange.com/a/34950/61846">comfortablydrei's answer</a> to <a href="https://codegolf.stackexchange.com/q/34887/61846">this PPCG Question</a> regarding creating a illusion animation in pure Excel VBA. So far, I've been able to rewrite the code to function in VBA, and to get the cycle time for the animation down substantially, but have run into an issue where I am GPU-limited on my current system (that is, the animation causes the GPU to pin @ 100% 3D usage)</p> <p>To reduce the cycle time, I have tried </p> <ul> <li>modifying how frequently the <code>VBA.DoEvents</code> call is made, and while this does reduce the time, it also breaks the animation severely</li> <li>Adding <code>Application.ScreenUpdating = False</code> and <code>"=True</code> calls, and this appears not to work </li> <li>reducing the code in the <code>Animate</code> Subroutine to be as simple as I can, with the result being the below</li> </ul> <p>Is there anything that I have missed (general or case-specific tricks or tips) that can make this faster, or is this about as good as can be expected for animations made in Excel VBA?</p> <p>I am pimarily concerned with the performance of the <code>animate</code> subroutine, and am otherwise only concerned with the readiblity of the other routines </p> <hr> <h2><code>Animate</code> Subroutine</h2> <pre><code>'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' Private (looping) Animation Subroutine '' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Private Sub animate() '' dim vars Dim iter As Integer, _ iPos As Double, _ iX As Double, _ iY As Double '' Debug Vars #If DebugMode Then Dim t As Long Debug.Print "Animation Cycle Time (sec)" #End If nextLoop: '' do events - allow for screen update, and event handling Call VBA.DoEvents '' Debug Timing #If DebugMode Then If rad &gt; 0 And rad &lt;= stp Then If t &gt; 0 Then Debug.Print Timer - t Let t = Timer End If #End If '' loop over shapes For iter = 1 To numPnts '' calculate the new position of shape Let iPos = Pi * (iter - 1) / numPnts If rad + iPos &lt; 0 Then GoTo nextIter Let iX = Sin(iPos) Let iY = Cos(iPos) '' set shapes location Let shp(iter).Left = plotCenterX - shpSize / 2 + (iX * plotScale / 2) * Cos(rad + iPos) Let shp(iter).Top = plotCenterY - shpSize / 2 + (iY * plotScale / 2) * Cos(rad + iPos) nextIter: Next iter '' get decimal mod of the rad with respect to tau Let rad = rad + stp Let rad = Round(rad - Fix(rad / Tau) * Tau, 14) GoTo nextLoop End Sub </code></pre> <hr> <h2>Full Commented Code</h2> <pre class="lang-vb prettyprint-override"><code>'' Module Options Option Compare Binary Option Explicit Option Base 1 '' Global Vars Global app As Excel.Application, _ twb As Excel.Workbook, _ cht As Excel.Chart, _ ser As Excel.Series, _ shp() As Excel.Shape, _ dat() As Double, _ rad As Double '' Positioning Vars Global plotCenterX As Double, _ plotCenterY As Double, _ plotScale As Double '' Naming Constants Private Const chtName As String = "Pie Chart" Private Const serName As String = "DataSheet" Private Const numPnts As Integer = 8 '' Shape Constants Private Const shpType As Long = MsoAutoShapeType.msoShapeRectangle Private Const shpSize As Long = 15 '' Math Constants Public Const Pi As Double = 3.14159265358979 Public Const Tau As Double = 6.28318530717959 Public Const stp As Double = 0.03 '' Conditional Compilation Switch for Debug Mode - '' '' When True, shows timing for a complete animation cycle '' ( rad - 0 to rad = 2*pi ) #Const DebugMode = True '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' Public Main Subroutine '' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Public Sub Main() #If DebugMode Then Debug.Print Debug.Print "Initializing" #End If Dim iter As Integer, _ colors As Variant, _ pnt As Excel.Point '' initialize global variables, incl. chart and Data series Call pInit '' To avoid having to upload another module, the output of Scales.HuePalette(8) is hardcoded ' Let colors = scales.HuePalette(numPnts) Let colors = [{7173880,38603,44664,6798848,12893952,16754944,16743623,13394431}] '' Format the chart as desired With ser Let .Name = "Spacers" Let .Values = "={" &amp; Replace(Space(2 * numPnts - 1), " ", "1,") &amp; "1}" With .Format Let .Line.ForeColor.RGB = rgbWhite Let .Line.Visible = True Let .Line.Weight = 1.5 End With: End With Call VBA.DoEvents '' On some machines, the cht.HasTitle '' fails to let if this is not included '' clean up the view Let cht.HasTitle = False Let cht.HasLegend = False Let rad = 0 Dim iPos As Double, _ iX As Double, _ iY As Double '' give each section a nice gradiant, because why not For iter = 1 To 2 * numPnts Set pnt = ser.Points(iter) With pnt.Format.Fill Call .TwoColorGradient(msoGradientVertical, 2) Let .GradientStops(1).Color.RGB = &amp;HFEFEFE Let .GradientStops(2).Color.RGB = &amp;HF2F2F2 Let .GradientAngle = (360 / (2 * numPnts)) * (iter - 0.5) + 90 End With Next iter '' place the shapes on the edges of the circle For iter = 1 To numPnts Let iPos = Pi * (iter - 1) / numPnts Let iX = Sin(iPos) Let iY = Cos(iPos) '' setup the shapes with a nice color With shp(iter) Let .Fill.ForeColor.RGB = colors(iter) Let .Line.ForeColor.RGB = rgbBlack Let .Line.Weight = 0.75 Let .Left = plotCenterX - shpSize / 2 + iX * plotScale / 2 Let .Top = plotCenterY - shpSize / 2 + iY * plotScale / 2 End With Next iter Let rad = -Pi #If DebugMode Then Debug.Print "Initialization Complete. Beginnning Animation" Debug.Print #End If Call animate End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' Private (looping) Animation Subroutine '' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Private Sub animate() '' dim vars Dim iter As Integer, _ iPos As Double, _ iX As Double, _ iY As Double '' Debug Vars #If DebugMode Then Dim t As Long Debug.Print "Animation Cycle Time (sec)" #End If nextLoop: '' do events - allow for screen update, and event handling Call VBA.DoEvents '' Debug Timing #If DebugMode Then If rad &gt; 0 And rad &lt;= stp Then If t &gt; 0 Then Debug.Print Timer - t Let t = Timer End If #End If '' loop oveer shapes For iter = 1 To numPnts '' calculate the new position of shape Let iPos = Pi * (iter - 1) / numPnts If rad + iPos &lt; 0 Then GoTo nextIter Let iX = Sin(iPos) Let iY = Cos(iPos) '' set shapes location Let shp(iter).Left = plotCenterX - shpSize / 2 + (iX * plotScale / 2) * Cos(rad + iPos) Let shp(iter).Top = plotCenterY - shpSize / 2 + (iY * plotScale / 2) * Cos(rad + iPos) nextIter: Next iter '' get decimal mod of the rad with respect to tau Let rad = rad + stp Let rad = Round(rad - Fix(rad / Tau) * Tau, 14) GoTo nextLoop End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' Private Initialization Subroutines '' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' Main Initialization Sub, Calls all following Init Calls Private Sub pInit() ReDim shp(1 To numPnts) ReDim dat(1 To numPnts, 0 To 1) Set app = Excel.Application Set twb = app.ThisWorkbook Let app.Calculation = xlCalculationManual Call pInitChart Call pInitSeries Call pInitShapes Call pInitPlotVars End Sub '' Initialixes the Pie Chart, cht Private Sub pInitChart() If Not cht Is Nothing Then Exit Sub If KeyExists(app.Charts, chtName) Then Set cht = app.Charts(chtName): Exit Sub Set cht = app.Charts.Add Let cht.Name = chtName Let cht.ChartType = xlPie End Sub '' Initialixes Initializes the data series, ser, in cht Private Sub pInitSeries() Dim i As Long With cht For i = .SeriesCollection.Count To 1 Step -1 Call .SeriesCollection(i).Delete Next i Call .SeriesCollection.NewSeries Set ser = .SeriesCollection(1) End With End Sub '' adds array of shapes to the chart workbook object Private Sub pInitShapes() Dim i As Long For i = cht.Shapes.Count To 1 Step -1 Call cht.Shapes(i).Delete Next i For i = 1 To numPnts Step 1 Set shp(i) = cht.Shapes.AddShape(shpType, shpSize * i, shpSize * i, shpSize, shpSize) Next i End Sub '' initializes the ploting vars Private Sub pInitPlotVars() Let plotScale = cht.PlotArea.InsideHeight Debug.Assert plotScale = cht.PlotArea.InsideWidth '' if this fails the chart is not square Let plotCenterX = plotScale / 2 + cht.PlotArea.InsideLeft Let plotCenterY = plotScale / 2 + cht.PlotArea.InsideTop End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' Generic functions '' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' Takes an object, and returns a bool which describes if `key` is a vaild key '' for either the default method of the object or for the `item` method of '' object Public Function KeyExists(ByRef objCol As Object, ByVal key As String) As Boolean Dim var As Variant, _ k As Boolean On Error Resume Next With VBA.Err Let var = objCol(key): Let k = k Or (.Number = 0): Call .Clear '' test let and default Set var = objCol(key): Let k = k Or (.Number = 0): Call .Clear '' test set and default Let var = objCol.Item(key): Let k = k Or (.Number = 0): Call .Clear '' test let and item Set var = objCol.Item(key): Let k = k Or (.Number = 0): Call .Clear '' test set and item End With Let KeyExists = k On Error GoTo 0 End Function </code></pre> <hr> <p>Current System Specs: </p> <ul> <li>Windows 10 Pro, Excel 2016 64-Bit i7-8850H, 80GB Ram, Quadro P2000 4GB, Intel UHD Graphics 630</li> </ul> <p>Average Cycle Times on the above system as reported from <code>DebugMode</code> in the above code </p> <ul> <li>Quadro P2000 4GB <span class="math-container">\$\approx1.99\text{ sec}\$</span></li> <li>Integrated Graphics <span class="math-container">\$\approx8.07\text{ sec}\$</span></li> <li>CPU Rendering <span class="math-container">\$\approx8.33\text{ sec}\$</span></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-20T07:45:01.453", "Id": "469154", "Score": "0", "body": "If performance is key, then it wouldn't hurt to profile your code and determine exactly the source of slowness. Is it the `DoEvents` calls (in which case make this asynchronous using a winapi timer instead of `DoEvents` to avoid unnecessary processing)? Maybe it's the writing to the chart (use an algorithmic change to reduce the number of hits, try doing all your writing at once)? Perhaps there's some kind of caching on Excel's part that slows the animation over time. Or something else entirely. Profile the code using a high performance stopwatch to determine the source of bottlenecks." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T16:54:06.787", "Id": "238319", "Score": "6", "Tags": [ "performance", "vba", "animation" ], "Title": "Chart Based Animations In Excel VBA" }
238319
<p>This program is made, so it graphs a spiral with N steps. What else could I add to this program?</p> <p><strong>Can this code be improved?</strong></p> <pre><code>import matplotlib.pyplot as plt N = 100 arr = [(0, 0)] x = [] y = [] for u in range(1, N): for i in range(1, 5): if i % 4 == 1: # first corner arr.append((u, - u + 1)) elif i % 4 == 2: # second corner (same positive numbers) arr.append((u, u)) elif i % 4 == 3: # third corner (same [one positive and one negative] numbers) arr.append((-u, u)) elif i % 4 == 0: # fourth corner (same negative numbers) arr.append((-u, -u)) print(arr) # just to easily check all coordinates for i in arr: x.append(i[0]) y.append(i[1]) plt.plot(x, y) plt.show() </code></pre>
[]
[ { "body": "<p>Your inside for loop is useless as it loops over 4 values ([1,2,3,4]) and you have 4 <code>if</code> insinde it. you could have:</p>\n\n<pre><code>N = 100\narr = [(0, 0)]\n\nfor u in range(1, N):\n # first corner\n arr.append((u, - u + 1))\n # second corner\n arr.append((u, u))\n # third corner\n arr.append((-u, u))\n # fourth corner\n arr.append((-u, -u))\n\n# Transforms [(x1, y1), (x2, y2)...] in x = (x1, x2...) y = (y1, y2...)\nx, y = zip(*arr)\nplt.plot(x, y)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:35:00.153", "Id": "238324", "ParentId": "238322", "Score": "12" } }, { "body": "<p>Except for what @Cal wrote, you can get rid of the zipping as well:</p>\n\n<pre><code>N=100\nx=[0]\ny=[0]\nfor u in range(1, N):\n x += [u, u, -u, -u]\n y += [1-u, u, u, -u]\n\nplt.plot(x, y)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T04:01:53.857", "Id": "467401", "Score": "0", "body": "Approaching code golf, but if N is fixed it could be written as ```N=100\nx=[0]\ny=[0, 0]\nfor u in range(1, N):\n x += [u, u, -u, -u]``` where `x` would also be `y`. The issue is that there is one too many elements at the end of `y`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T06:51:23.397", "Id": "467406", "Score": "1", "body": "@alexyorke my solution puts stress on readability. Your solution is not at first glance obvious why that is the case. And unless the plot function can ignore the extra y coordinate, it is meaningless. And even if it could, it Is not very smart to rely on such behaviour." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:44:26.757", "Id": "238325", "ParentId": "238322", "Score": "7" } }, { "body": "<p>Instead of redundant traversal and <code>append</code> to multiple lists - use an efficient <em>generator</em> function with further <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a> call to aggregate the needed <strong><code>x</code></strong>, <strong><code>y</code></strong> coords sequences:</p>\n\n<pre><code>import matplotlib.pyplot as plt\n\n\ndef spiral_coords_gen(n=100):\n yield 0, 0\n for i in range(1, n):\n yield i, -i + 1\n yield i, i\n yield -i, i\n yield -i, -i\n\n\nx, y = zip(*spiral_coords_gen())\nplt.plot(x, y)\nplt.show()\n</code></pre>\n\n<p>The output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aC3Tj.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/aC3Tj.jpg\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T20:45:10.633", "Id": "469286", "Score": "0", "body": "hey, sorry for late response. I don't completely understand what does the \"yield\" function do in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-22T10:00:18.433", "Id": "469339", "Score": "0", "body": "@urbanpečoler https://docs.python.org/3/glossary.html#term-generator" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:55:43.447", "Id": "238326", "ParentId": "238322", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T17:16:41.563", "Id": "238322", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "Graphing a spiral" }
238322
<p>Hi I'm fairly new to coding and would appreciate some feedback on the code. This is for a site that has a dynamic login page and infinite scrolling. </p> <p>I wanted to use scrapy not necessarily because it needs the framework, but because I hadn't done infinite scrolling and dynamic content with scrapy. </p> <p>I'm aware that it's essentially one big long list of code. I'm not actually too sure how to split this up because I'm not requesting another page till the end of the code. I've tried an iteration of using a loop and response.follow for each link but the scrapy output was abit messed up. </p> <p>Is there anyway to make this into discrete functions and abit more readable ? I know some people like splash for dynamic content with scrapy. </p> <p>I also think the drop down menu code is abit repetitive. </p> <p>Minor details but I have noticed that the sellersusername and sellerscompany_name come out as a list but the others don't. I cant really account for that! I've tried explicitly defining input processors without too much success! I can also edit this in pandas so not too concerned by it but if there's a more efficient way that would be awesome.</p> <p>Also I feel there's probably a way to drop the column file_url and file from the output after it's been put to the FilePipeLine, but haven't quite worked that out!</p> <p>Appreciate the feedback</p> <pre><code>import scrapy import logging from scrapy.utils.log import configure_logging from selenium import webdriver from selenium.webdriver.support import ui from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from scrape.items import ScrapeItem from scrapy.loader import ItemLoader from scrape.items import MyItemLoader from scrapy.selector import Selector import time class DataSpider(scrapy.Spider): name = 'data' allowed_domains = ['scrapo.com'] start_urls = ['http://scrapo.com/'] custom_settings = { 'LOG_FILE': 'my_log.log', 'LOG_LEVEL': 'ERROR'} logging.getLogger().addHandler(logging.StreamHandler()) def parse(self, response): self.driver = webdriver.Chrome(executable_path = r'C:/Users/Aaron/Downloads/chromedriver_win32/chromedriver.exe') self.driver.get('http://scrapo.com/') self.driver.find_element_by_xpath("/html/body/header/div[2]/div/div[1]/a[2]").clck() time.sleep(1) #login procedure self.driver.find_element_by_id('loginform-email').send_keys('xxxx') self.driver.find_element_by_id('loginform-password').send_keys('xxxxx') self.driver.find_element_by_id('btnSignin').click() time.sleep(10) #Dynamic drop down menu. Waiting for each element before click() x = self.driver wait = ui.WebDriverWait(self.driver,10) action = ActionChains(self.driver) wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[2]/div[1]/div')) firstLevelMenu = self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[2]/div[1]/div') action.move_to_element(firstLevelMenu).perform() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_2_container"]/li[2]/label/span')) secondLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_2_container"]/li[2]/label/span') secondLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[3]/div[1]/div')) menu = self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[3]/div[1]/div') action.move_to_element(menu).perform() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[8]/label/span')) thirdLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[8]/label/span') thirdLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[11]/label/span')) fourthLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[11]/label/span') action.move_to_element(fourthLevelMenu).perform() fourthLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[12]/label/span')) fifthLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[12]/label/span') action.move_to_element(fifthLevelMenu).perform() fifthLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[25]/label/span')) sixthLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[25]/label/span') action.move_to_element(sixthLevelMenu).perform() sixthLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[26]/label/span')) seventhLevelMenu = self.driver.find_element_by_xpath('//*[@id="mCSB_3_container"]/li[26]/label/span') action.move_to_element(seventhLevelMenu).perform() seventhLevelMenu.click() wait.until(lambda x: self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[3]/div[2]/div/div/button')) eigthLevelMenu = self.driver.find_element_by_xpath('//*[@id="form_search_filter"]/div[2]/div[3]/div[2]/div/div/button') eigthLevelMenu.click() #Infinite scroll logic pre_scroll_height = self.driver.execute_script('return document.body.scrollHeight;') run_time, max_run_time = 0, 10 while True: iteration_start = time.time() # Scroll webpage, the 100 allows for a more 'aggressive' scroll self.driver.execute_script('window.scrollTo(0, 1*document.body.scrollHeight);') time.sleep(1) post_scroll_height = self.driver.execute_script('return document.body.scrollHeight;') scrolled = post_scroll_height != pre_scroll_height timed_out = run_time &gt;= max_run_time if scrolled: run_time = 0 pre_scroll_height = post_scroll_height elif not scrolled and not timed_out: run_time += time.time() - iteration_start elif not scrolled and timed_out: self.logger.info('Reached end of page') break #Grab links and store in list after infinite scroll finished scrapy_selector = Selector(text = self.driver.page_source) rel_links_list = scrapy_selector.xpath('.//div[@class="grid_product_header"]/a/@href').extract() self.logger.info('Theres a total of ' + str(len(rel_links_list)) + ' links.') links = ['https://www.scrapo.com' + rel_link for rel_link in rel_links_list] #looping over every link #Item loader for fields given q = 1 for link in links: self.logger.info('Item #' + str(q)) self.driver.get(link) self.driver.implicitly_wait(50) q = q+1 plastic_scrapy_selector = Selector(text = self.driver.page_source) l = MyItemLoader(item = ScrapeItem(),selector = plastic_scrapy_selector) l.add_xpath('Title','.//h1[@class="product-small-info_title"]/@title') l.add_xpath('Category','//div[@class="additional-info"]/div/span[@class="additional-info-item_description"]/@title') l.add_xpath('Condition','.//div[@class="additional-info"]/div[2]/span[@class="additional-info-item_description"]/@title') l.add_xpath('Quantity','.//div[@class="additional-info"]/div[3]//span[@class="additional-info-item_description"]/@title') l.add_xpath('Supply','.//div[@class="additional-info"]/div[4]//span[@class="additional-info-item_description"]/@title') l.add_xpath('Pricingterms','.//div[@class="additional-info"]/div[5]//span[@class="additional-info-item_description"]/@title') l.add_xpath('Location','.//div[@class="additional-info"]/div[6]//span[@class="additional-info-item_description"]/@title') l.add_xpath('Sellersusername','.//div[@class="user-info-name"]/text()') l.add_xpath('Sellerscompany_name','.//p[@class="company-name"]/text()') l.add_xpath('Price', '//span[@class="value price"]/b/text()') l.add_xpath('Price', '//span[@class="value price"]/text()') l.add_xpath('file_urls','//*[@id="app"]/div[1]/div[1]/div[1]/div[1]/div[1]/a/@href') yield l.load_item() self.driver.close() </code></pre> <p>Here is the settings.py</p> <pre><code> import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst, MapCompose class ScrapeItem(scrapy.Item): name = scrapy.Field() Title = scrapy.Field() Category = scrapy.Field() Condition = scrapy.Field() Quantity = scrapy.Field() Supply = scrapy.Field() Pricingterms = scrapy.Field() Location = scrapy.Field() Sellersusername = scrapy.Field() Sellerscompany_name = scrapy.Field() Sellerslocation = scrapy.Field() Price = scrapy.Field() file_urls = scrapy.Field() files = scrapy.Field() class MyItemLoader(ItemLoader): Title_out = TakeFirst() Category_out = TakeFirst() Condition_out = TakeFirst() Quantity_out = TakeFirst() Supply_out = TakeFirst() Pricingterms_out = TakeFirst() Location_out = TakeFirst() Sellerslocation_out = TakeFirst() </code></pre> <p>Here's the settings.py</p> <pre><code>BOT_NAME = 'scrape' SPIDER_MODULES = ['scrape.spiders'] NEWSPIDER_MODULE = 'scrape.spiders' FILES_STORE = 'c:/Users/Aaron/python/output' RANDOMIZE_DOWNLOAD_DELAY = True ROBOTSTXT_OBEY = True CONCURRENT_REQUESTS = 1 DOWNLOAD_DELAY = 5 CONCURRENT_REQUESTS_PER_IP = 3 DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'scrapy_user_agents.middlewares.RandomUserAgentMiddleware': 400 } ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1} AUTOTHROTTLE_ENABLED = True AUTOTHROTTLE_START_DELAY = 2 HTTPCACHE_ENABLED = True HTTPCACHE_DIR = 'httpcache' HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' </code></pre> <p>There are no errors from the scrapy log and it managed to grab all data that is there.</p> <p>Output:</p> <pre><code> {"Title": "LDPE Film", "Category": "LDPE", "Condition": "Other condition", "Quantity": "40,000 lbs", "Supply": "Ongoing", "Pricingterms": "Other", "Location": "Wisconsin, United States", "Sellersusername": ["Fulfilled by Scrapo"], "Sellerscompany_name": ["Scrapo, Inc"], "Price": ["\u00a30.20", "\n ", " / lb "], "file_urls": ["https://d1vpmfwd72pjy6.cloudfront.net/uploads/product/514e36e92b2f.jpeg"], "files": [{"url": "https://d1vpmfwd72pjy6.cloudfront.net/uploads/product/514e36e92b2f.jpeg", "path": "full/c07f35499c3dc329d54c2fd3d85c461a1598a172.jpeg", "checksum": "b20c16f6e99b37ee6e2d9c89d6503def"}]} </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T18:51:15.490", "Id": "238331", "Score": "1", "Tags": [ "python", "web-scraping", "scrapy" ], "Title": "Web scraping dynamic content" }
238331
<p>I have a spinner that it has a custom layout with 5 imageviews and 1 textview. I would like to load it up with 80 rows, so it will display around 300 images (all images are within the app).</p> <p>Is this a really bad idea?</p> <p>All the images are loaded this way:</p> <pre><code> class CustomAdapter : BaseAdapter { private Context Context; private List&lt;ButtonImagesTemplate&gt; ButtonImagesTemplates; private LayoutInflater inflater; public CustomAdapter(Context context, List&lt;ButtonImagesTemplate&gt; ButtonImagesTemplates) { this.Context = context; this.ButtonImagesTemplates = ButtonImagesTemplates; } public override Object GetItem(int position) { return null; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { if (inflater == null) { inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService); } if (convertView == null) { convertView = inflater.Inflate(Resource.Layout.SpinnerTemplateModel, parent, false); } TextView nameTxt = convertView.FindViewById&lt;TextView&gt;(Resource.Id.TemplateNameTextView); ImageView img1 = convertView.FindViewById&lt;ImageView&gt;(Resource.Id.TemplateImageView1); ImageView img2 = convertView.FindViewById&lt;ImageView&gt;(Resource.Id.TemplateImageView2); ImageView img3 = convertView.FindViewById&lt;ImageView&gt;(Resource.Id.TemplateImageView3); ImageView img4 = convertView.FindViewById&lt;ImageView&gt;(Resource.Id.TemplateImageView4); ImageView img5 = convertView.FindViewById&lt;ImageView&gt;(Resource.Id.TemplateImageView5); //BIND nameTxt.Text = ButtonImagesTemplates[position].Name; var drawable = AppCompatResources.GetDrawable(Context, ButtonImagesTemplates[position].Images[0]); img1.SetImageDrawable(drawable); img2.SetImageResource(ButtonImagesTemplates[position].Images[1]); img3.SetImageResource(ButtonImagesTemplates[position].Images[2]); img4.SetImageResource(ButtonImagesTemplates[position].Images[3]); img5.SetImageResource(ButtonImagesTemplates[position].Images[4]); return convertView; } public override int Count { get { return ButtonImagesTemplates.Count; } } } </code></pre> <p>also the layout here:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="122sp"&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="50sp"&gt; &lt;ImageView android:layout_width="50sp" android:layout_height="50sp" android:scaleType="centerInside" android:layout_weight="2" android:padding="10dp" android:layout_gravity="left" android:gravity="left" android:id="@+id/TemplateImageView1" /&gt; &lt;ImageView android:layout_width="50sp" android:layout_height="50sp" android:scaleType="centerInside" android:layout_weight="2" android:padding="10dp" android:layout_gravity="left" android:gravity="left" android:id="@+id/TemplateImageView2" /&gt; &lt;ImageView android:layout_width="50sp" android:layout_height="50sp" android:scaleType="centerInside" android:layout_weight="2" android:padding="10dp" android:layout_gravity="left" android:gravity="left" android:id="@+id/TemplateImageView3" /&gt; &lt;ImageView android:layout_width="50sp" android:layout_height="50sp" android:scaleType="centerInside" android:layout_weight="2" android:padding="10dp" android:layout_gravity="left" android:gravity="left" android:id="@+id/TemplateImageView4" /&gt; &lt;ImageView android:layout_width="50sp" android:layout_height="50sp" android:scaleType="centerInside" android:layout_weight="2" android:padding="10dp" android:layout_gravity="left" android:gravity="left" android:id="@+id/TemplateImageView5" /&gt; &lt;/LinearLayout&gt; &lt;TextView style="@style/MyTextStyle" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="match_parent" android:layout_height="50sp" android:padding="10dp" android:layout_gravity="center" android:textAlignment="textStart" android:gravity="center" android:id="@+id/TemplateNameTextView" /&gt; &lt;View android:layout_width="match_parent" android:layout_height="@dimen/LineHeight" android:layout_marginTop="@dimen/LineMarginTopBottom" android:layout_marginBottom="@dimen/LineMarginTopBottom" android:layout_marginLeft="@dimen/ResourceOptionsMarginFromScreen" android:layout_marginRight="@dimen/ResourceOptionsMarginFromScreen" android:background="@color/dark_grey"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>I have a list with all the Resource Ids, and all the images are vector .xml files. I tried to load the images with ffimageloading but as far as I am concerned XML are not supported. I added ffimageloading.svg nubegt package and do some tests and the image was not displayed.</p> <p>So what I would like to ask: is this a bad idea? Should I find a library to load the images like ffimageloading or picasso? If yes, which one?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T20:44:26.987", "Id": "467380", "Score": "2", "body": "Welcome to CodeReview! Thanks for taking the time to post your code and question. CodeReview is meant for you to post complete, functioning, code for review by other members. Snippets and code that doesn't work as intended aren't reviewable, as we can't look at overall design patterns, etc. Your question is better suited for StackOverflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T20:53:57.353", "Id": "467382", "Score": "0", "body": "i have put the complete code of my custom adapter of the spinner that works, is it still not suitable here? if yes why? its a full functioning code that i want to improve" } ]
[ { "body": "<p>If do you need load big count image i recommend you using libraries for working with images. Example : glide , picasso. Otherwise, you will experience performance problems.\nExample code for gllide : </p>\n\n<pre><code> Glide.With(context)\n.Load(R.drawable.resource_id)\n.Into(imageView);\n</code></pre>\n\n<p>Also here you get the values ​​from the array, but you did not check if the number of values ​​in the array</p>\n\n<pre><code> img2.SetImageResource(ButtonImagesTemplates[position].Images[1]);\n img3.SetImageResource(ButtonImagesTemplates[position].Images[2]);\n img4.SetImageResource(ButtonImagesTemplates[position].Images[3]);\n img5.SetImageResource(ButtonImagesTemplates[position].Images[4]);\n</code></pre>\n\n<p>Here you can see additional information : <a href=\"https://bumptech.github.io/glide/\" rel=\"nofollow noreferrer\">https://bumptech.github.io/glide/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:32:57.890", "Id": "467484", "Score": "0", "body": "i have try glide and i cannot install it, it is 3 years old the latest update in xamarin, and it has incompatibility issues.\nI have also try picasso and FFImageLoading and they don't support vector .xml images" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T00:01:49.310", "Id": "467514", "Score": "0", "body": "https://stackoverflow.com/a/35508121 , take a look maybe it will help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T00:03:46.800", "Id": "467515", "Score": "1", "body": "If nothing succeeds and there are no problems loading so many images, leave it as it is." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:51:21.467", "Id": "238375", "ParentId": "238332", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T19:11:46.407", "Id": "238332", "Score": "3", "Tags": [ "c#", "android", "xamarin" ], "Title": "Loading 300 images on a custom spinner with images" }
238332
<p>I have implemented a custom merge of 2 pandas DataFrames, but only mutates the first.</p> <p>The new columns will be the union of the original columns and the new keys will be union of original keys. Additionally, the second DataFrame values will overwrite the first DataFrame if the keys match.</p> <pre class="lang-py prettyprint-override"><code>def merge_dataframes(df1, df2): for header in set(df2) - (set(df1) &amp; set(df2)): df1[header] = None old_keys = df2.index.isin(df1.index) new_keys = ~old_keys df1.update(df2[old_keys]) df1 = df1.append(df2[new_keys], sort=True) return df1 </code></pre> <p>This is tested as follows:</p> <pre><code> df1 = pandas.DataFrame(data=["Test1", "Test2"]) df2 = pandas.DataFrame(data=["Test3", "Test4"]) # this should simply overwrite df1 with df2 new_df = merge_dataframes(df1, df2) assert (new_df == df2).all()[0] df1 = pandas.DataFrame(data=["Test1", "Test2"]) df2 = pandas.DataFrame(data=["Test3", "Test4"], index=["a", "b"]) # this should simply overwrite df1 with df2 new_df = merge_dataframes(df1, df2) expected_df = pandas.DataFrame(data=["Test1", "Test2", "Test3", "Test4"], index=[0, 1, "a", "b"]) assert (new_df == expected_df).all()[0] </code></pre> <p>Is there a way to accomplish this with less code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T04:20:07.820", "Id": "467920", "Score": "0", "body": "This looks like `df1= pd.concat((df1,df2)).drop_duplicates(keep='last')` let me know If I am wrong also if you can extend the example, that'd be great." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T04:26:17.947", "Id": "467921", "Score": "0", "body": "Also may be you can try `df1 = pd.concat((df1,df2)).groupby(level=0).last()`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T22:18:49.783", "Id": "238334", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Merge two DataFrames with key over-write" }
238334
<p>This is my code to solve the challenge in 100 Days of SwiftUI by Paul Hudson. This is the first challenge in the series and I chose to convert the temperature units from C° -> F°, F° -> C°, C° -> K° and K°-> C°</p> <p>I need to ask, is this code readable by you and if anything needs to be changed/modified in order to make more efficient?</p> <pre><code>import SwiftUI struct ContentView: View { @State private var inputTemp = "" @State private var inputUnit = 0 @State private var outputUnit = 0 let inputUnits = ["C", "F", "K"] let outputUnits = ["C", "F", "K"] var convertedDegreeC2F: Int { guard let inputDegree = Int(inputTemp) else { return 0 } let convertC2F = Int(inputDegree/5*9+32) let convertF2C = Int((inputDegree-32)*5/9) let convertC2K = Double(inputDegree) + 273.15 let convertK2C = Double(inputDegree) - 273.15 if inputUnit == 0 &amp;&amp; outputUnit == 1 { return convertC2F } else if inputUnit == 1 &amp;&amp; outputUnit == 0 { return convertF2C } else if inputUnit == 0 &amp;&amp; outputUnit == 2 { return Int(convertC2K) } else if inputUnit == 2 &amp;&amp; outputUnit == 0 { return Int(convertK2C) } return 0 } var body: some View { NavigationView { Form { Section { TextField("Input Temperature", text: $inputTemp) .keyboardType(.decimalPad) } Section(header: Text("Select input unit:" )) { Picker("Input Unit", selection: $inputUnit) { ForEach(0..&lt;inputUnits.count) { Text("\(self.inputUnits[$0])°") } } .pickerStyle(SegmentedPickerStyle()) } Section(header: Text("Select output unit:" )) { Picker("Output Unit", selection: $outputUnit){ ForEach(0..&lt;outputUnits.count) { Text("\(self.outputUnits[$0])°") } } .pickerStyle(SegmentedPickerStyle()) } Section(header: Text("Temperature after conversion is:")) { Text("\(convertedDegreeC2F)°") } } .navigationBarTitle("UConvert") } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T23:37:58.277", "Id": "467386", "Score": "2", "body": "Including a description of what it is the code is trying to achieve within the question will make it easier for reviewers to compare the purpose with the implementation. Likewise, the title should reflect what the code does, rather than a reference to a non-descriptive coding challenge number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T01:49:58.997", "Id": "467396", "Score": "4", "body": "To future close voters: I think the question is fixed now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:13:31.477", "Id": "467439", "Score": "1", "body": "\"K°\" is wrong - the symbol for kelvins is simply \"K\". The other two units are spelt \"°C\" and \"°F\" (though \"C°\" and \"F°\") are sometimes used for *intervals*, i.e. temperature differences)." } ]
[ { "body": "<p>The names of the measurement units are wrong. Kelvin does not take a degree. It's just K, not °K. Fixing this requires changes to most of the code.</p>\n\n<p>It's a waste of computation time to calculate all possible conversions and then only use one of them. You can be lucky that you are converting temperatures and not ancient lengths, of which there are hundreds.</p>\n\n<p>The conversion function should convert from <code>Double</code> to <code>Double</code>. Otherwise there will be temperatures that change by a large amount when you repeatedly convert them between the units.</p>\n\n<p>Looping over the indexes in the <code>ForEach</code> loops looks overly complicated to me. I'm sure that Swift provides a better way to fill a picker with an array. I've never programmed in Swift though, so I might be wrong.</p>\n\n<p>The <code>return 0</code> is plain wrong and dangerous since converting an unknown temperature must result in an error message, not in a lie.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T04:14:59.887", "Id": "238343", "ParentId": "238336", "Score": "2" } }, { "body": "<p>The conversion function <code>convertedDegreeC2F()</code> handles only four of the nine possible conversions between the three units. In particular, the conversion between identical input/output unit is not handled. Also the function name is misleading because the function is not about conversion from Celsius to Fahrenheit only.</p>\n\n<p>The conversion between temperature units can be greatly simplified using <a href=\"https://developer.apple.com/documentation/foundation/measurement\" rel=\"noreferrer\"><code>Measurement</code></a> from the Foundation framework:</p>\n\n<blockquote>\n <p>A numeric quantity labeled with a unit of measure, with support for unit conversion and unit-aware calculations.</p>\n</blockquote>\n\n<p>Here is a standalone example for demonstration:</p>\n\n<pre><code>let t = Measurement(value: 10.0, unit: UnitTemperature.celsius)\nprint(t.converted(to: .fahrenheit).value) // 49.99999999999585\nprint(t.converted(to: .kelvin).value) // 283.15\n</code></pre>\n\n<p>The Fahrenheit value is not “exact” due to floating point rounding issues. But that does not matter, because <em>displaying</em> the value should be done with a <em>formatter</em> anyway. Here we can use a <a href=\"https://developer.apple.com/documentation/foundation/measurementformatter\" rel=\"noreferrer\"><code>MeasurementFormatter</code></a>:</p>\n\n<blockquote>\n <p>A formatter that provides localized representations of units and measurements.</p>\n</blockquote>\n\n<p>Again a standalone example for demonstration:</p>\n\n<pre><code>let formatter = MeasurementFormatter()\nformatter.unitOptions = .providedUnit\n\nlet t = Measurement(value: 10.0, unit: UnitTemperature.celsius)\nprint(formatter.string(from: t)) //10°C\nprint(formatter.string(from: t.converted(to: .fahrenheit))) // 50°F\nprint(formatter.string(from: t.converted(to: .kelvin))) // 283.15 K\n</code></pre>\n\n<p>The measurement formatter adds the correct unit symbol automatically, and also localizes the output correctly (e.g. “283,15 K” with a comma as fraction separator, where appropriate).</p>\n\n<p>The conversion from the input field value to a floating point number should be done with a <code>NumberFormatter()</code> to handle localized input correctly.</p>\n\n<p>With these preparations, the correct conversion between arbitrary temperature units becomes simple:</p>\n\n<pre><code>func convert(temperature: String, from inputUnit: UnitTemperature, to outputUnit: UnitTemperature) -&gt; String? {\n let inputFormatter = NumberFormatter()\n guard let value = inputFormatter.number(from: temperature) else { return nil }\n\n let inputTemp = Measurement(value: value.doubleValue, unit: inputUnit)\n let outputTemp = inputTemp.converted(to: outputUnit)\n\n let outputformatter = MeasurementFormatter()\n outputformatter.unitOptions = .providedUnit\n return outputformatter.string(from: outputTemp)\n}\n</code></pre>\n\n<p>In your <code>ContentView</code> you can then define the list of available units as</p>\n\n<pre><code>let units: [UnitTemperature] = [.celsius, .fahrenheit, .kelvin]\n</code></pre>\n\n<p>instead of using a list of strings. Both pickers can be created from this list (with the correct symbol for each unit), e.g.</p>\n\n<pre><code>Picker(\"Input Unit\", selection: $inputUnit) {\n ForEach(0..&lt;units.count) {\n Text(self.units[$0].symbol)\n }\n}\n.pickerStyle(SegmentedPickerStyle())\n</code></pre>\n\n<p>Finally, converting the input value and displaying it is now simply done with</p>\n\n<pre><code>Text(convert(temperature: inputTemp, from: units[inputUnit],\n to: units[outputUnit]) ?? \"Invalid input\")\n</code></pre>\n\n<p>A small performance improvement might be to create both formatters only once, e.g. by storing them as private variables in the compilation unit:</p>\n\n<pre><code>import SwiftUI\n\nfileprivate let inputFormatter = NumberFormatter()\nfileprivate let outputformatter: MeasurementFormatter = {\n let fmt = MeasurementFormatter()\n fmt.unitOptions = .providedUnit\n return fmt\n}()\n\nfunc convert(...)\n// ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:46:17.167", "Id": "238359", "ParentId": "238336", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T23:06:00.500", "Id": "238336", "Score": "6", "Tags": [ "swift", "ios", "swiftui" ], "Title": "100DaysofSwiftUI - Project 1 - Challenge 1: Convert temperature units: Celsius, Fahrenheit and Kelvin" }
238336
<p>This is my first attempt at writing a C program, it a generic stack that can grow accordingly. It appears to work correctly, however I am worried that is just a fluke and I could be doing something very wrong.</p> <p>I would greatly appreciate any feedback/criticism.</p> <p>I am aware I should split this out into a .h and .c file but for demonstration purposes I have listed it as one.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; typedef struct Stack { void** data; int capacity; int count; } Stack; void stack_init(Stack *stack, int capacity) { stack-&gt;data = (void**)malloc(capacity * sizeof(void*)); stack-&gt;capacity = capacity; stack-&gt;count = 0; } void stack_push(Stack *stack, void* entry) { if (stack-&gt;count &gt;= stack-&gt;capacity) { stack-&gt;capacity *= 2; stack-&gt;data = (void**)realloc(stack-&gt;data, stack-&gt;capacity * sizeof(void*)); } stack-&gt;data[stack-&gt;count] = entry; stack-&gt;count++; } void* stack_pop(Stack *stack) { stack-&gt;count--; return stack-&gt;data[stack-&gt;count]; } bool stack_is_empty(Stack *stack) { return (stack-&gt;count == 0); } int main() { Stack myStack; stack_init(&amp;myStack, 2); for (int i = 0; i &lt; 2; i++) { stack_push(&amp;myStack, i); } while (!stack_is_empty(&amp;myStack)) { printf("%d\n", (int)stack_pop(&amp;myStack)); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:24:27.177", "Id": "467390", "Score": "0", "body": "Check the warnings [here](https://wandbox.org/permlink/VP6ylzPS9uruZFSp). Passing integers around as casted pointers is probably not what you want there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:57:15.233", "Id": "467392", "Score": "0", "body": "Hint: If you'll try this with other data types like `double` or any kind of `struct` this code will fail spectacularly.. What you're doing is wrong. `void*` looses any type information, including the size of the original type. Thus `sizeof(void*)` for allocation is futile from the beginning. You're allocating space for a pointer size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T01:31:38.897", "Id": "467394", "Score": "1", "body": "@πάνταῥεῖ I guess OP is reusing the `void*` space to store an `int` under the assumption that `sizeof(int) <= sizeof(void*)`. The practice of (ab)using the generic `void*` data itself to store the value instead of pointing to an external data block (and thus worrying about lifetime) is common in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T01:35:04.487", "Id": "467395", "Score": "0", "body": "@L.F. I guess that the OP tries to store generic data types in the stack, and fundamentally failed to do that correctly. _\"store the value instead of pointing to an external data block (and thus worrying about lifetime) is common in C.\"_ That's not necessary if you want to handle `int` values only, and makes the stack interface quite confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T02:02:19.360", "Id": "467398", "Score": "0", "body": "@πάνταῥεῖ That's what C libraries (even some C++ ones) usually do anyway - providing a `void*` slot to store data, and allowing the user to use it the way they like. Not really confusing IMO, as long as the user uses the slot in a consistent way. The C-style generic programming is quite different from the way we usually think in C++, but I don't think it's problematic to stick to C practices in C code :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:13:36.103", "Id": "467490", "Score": "2", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1" } ]
[ { "body": "<p>I suggest that you do more error checking:</p>\n\n<ul>\n<li><p><code>malloc</code> or <code>realloc</code> may fail.</p></li>\n<li><p>I can initialize the stack with negative capacity.</p></li>\n<li><p>I can pop more elements than I pushed.</p></li>\n</ul>\n\n<p>In all these cases, your implementation silently swallows the errors and accesses invalid addresses.</p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/52802\">πάντα ῥεῖ</a> said in comments, if you want to store generic elements that exceed <code>void*</code> in size, you need to allocate memory for them and let the <code>void*</code> point to them, e.g.:</p>\n\n<pre><code>typedef struct {\n // ...\n} BigStruct;\n\n// pushing\nBigStruct* data = malloc(sizeof(BigStruct));\n// initialize *data\nstack_push(&amp;stack, data);\n\n// popping\nBigStruct* data = stack_pop(&amp;stack);\n// use *data\nfree(data);\n</code></pre>\n\n<p>Some small issues:</p>\n\n<ul>\n<li><p>It is not common to cast the result of <code>malloc</code> or <code>realloc</code> in C.</p></li>\n<li><p>If the stack is initialized to capacity 0, then the stack will never grow and elements will be stored at invalid positions. A solution is to adjust the capacity to 1 automatically.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T01:47:49.493", "Id": "238341", "ParentId": "238338", "Score": "10" } }, { "body": "<p>There are two main problems with the code that must be addressed:</p>\n\n<ul>\n<li>You store <em>pointers to data</em> in an array, rather than actual data. This is not useful, since pointers may point to data that goes out of scope or otherwise becomes obsolete. When writing a container class such as a stack/LIFO, one should store so-called \"hard copies\" of the data passed.</li>\n<li><p>The code is not valid C. You implicitly convert from an <code>int</code> which is data, to a <code>void*</code> which is a pointer. Details here: <a href=\"https://stackoverflow.com/questions/52186834/pointer-from-integer-integer-from-pointer-without-a-cast-issues\">“Pointer from integer/integer from pointer without a cast” issues</a>. To prevent non-C from compiling without errors then set gcc/clang/icc to always compile with <code>-std=c11 -pedantic-errors</code>.</p>\n\n<p>Apart from the implicit conversion itself being invalid, there is no guarantee that you can safely convert from <code>int</code> to <code>void*</code> and back even if you use a cast. This conversion relies on poorly specified behavior.</p></li>\n</ul>\n\n<p>Because of these two remarks, the code cannot be fixed, it must be rewritten from scratch. To rewrite this into a proper stack container, it must be rewritten to use bytes of raw data (<code>uint8_t</code>) and make hard copies of the data passed.</p>\n\n<hr>\n\n<p>Other remarks:</p>\n\n<ul>\n<li>When popping from the stack, check <code>count</code> to see if there actually are any items left!</li>\n<li><code>typedef struct Stack { ... } Stack;</code> The \"struct tag in this case is superfluous, you can just write <code>typedef struct { ... } Stack;</code>.</li>\n<li><code>int main()</code> is an obsolete form of main() declaration, always use <code>int main (void)</code> instead (or the version with argv+argc).</li>\n<li>You don't use <em>const correctness</em>. Functions that do not change the passed <code>Stack*</code> should <code>const</code> qualify it: <code>bool stack_is_empty(const Stack *stack)</code>.</li>\n<li>When storing the size of an array, the integer type <code>size_t</code> is more correct to use than <code>int</code>, since <code>int</code> may not be large enough and in addition it is signed.</li>\n<li><code>return (stack-&gt;count == 0);</code> No parenthesis needed here, it's just clutter.</li>\n<li><code>(void**)malloc</code> etc. No cast needed here, it's just clutter.</li>\n<li>When calling malloc and realloc, always check if they succeeded by checking the result against NULL. \n-Calling realloc repeatedly like this is inefficient. That's why a stack is usually implemented as a double linked linked list. You may not have learnt about these yet, but they are the most suitable way to implement containers that often add/remove items at the top or bottom, at the case of slower access time for items located at a random place inside the container. You will not use this stack like that, so a linked list would be more suitable.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T08:13:02.037", "Id": "467414", "Score": "1", "body": "\"Calling realloc repeatedly like this is very inefficient. That's why a stack is usually implemented as a double linked linked list. You may not have learnt about these yet, but they are the most suitable way to implement containers that often add/remove items at the top or bottom.\" Hmm ... C++ vectors do this, and usually outperform linked lists. Am I missing something special about `realloc`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:04:27.020", "Id": "467418", "Score": "1", "body": "C++ vectors *usually* outperform linked lists, but it does depend on the access patterns. I expect the optimum data structure for a stack is more like a *rope*: a linked list of chunks; each chunk big enough to accommodate a decent number of items. No reallocation, but very few allocations, and very little pointer chaining." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:21:56.770", "Id": "467428", "Score": "1", "body": "@L.F. `realloc` or heap allocation in general is slow. Therefore, the implementation of std::vector uses an allocation scheme along the lines of: \"allocate align * n bytes upon creation, when running out of memory reallocate align * 2n\", doubling the size each time. This reduces the amount of calls. Similar algorithms are often used in C too when designing a string ADT or whatever. Of course a std::vector or any array outperforms a linked list in _access time_, since it has random access. Arrays vs linked lists is very basic computer science stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:33:25.697", "Id": "467429", "Score": "2", "body": "Isn't OP doing what you are describing? `stack->capacity *= 2;` Also don't forget that linked lists have space implications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:41:06.077", "Id": "467431", "Score": "0", "body": "@L.F. Oh, they are, actually. I should remove that remark then. Regardless, a linked list would be faster for lots of pushing/popping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T13:06:53.913", "Id": "467454", "Score": "1", "body": "@Lundin Wouldn't linked list perform even worse for lots of pushing and popping, since you need to allocate memory from heap for every push, even if you are not reaching a new maximum size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:06:17.733", "Id": "467488", "Score": "0", "body": "@Lundin, remember that this is a *stack*, so all accesses are to the top of stack, and the penalty for \"access an arbitrary element\" isn't ever paid. Many small allocations is still a performance hit, though." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T08:04:58.483", "Id": "238349", "ParentId": "238338", "Score": "8" } }, { "body": "<p><strong>Ease of clean-up</strong></p>\n\n<p>Consider a function to empty a <code>Stack</code> and free its allocated memory.</p>\n\n<pre><code>void stack_clean_up(Stack *stack) {\n free(stack-&gt;data);\n stack-&gt;data = NULL;\n stack-&gt;capacity = 0;\n stack-&gt;count = 0;\n}\n\n\nint foo() {\n Stack myStack;\n ....\n // Preceding code all done, time to clean up\n stack_clean_up(&amp;myStack);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:15:47.543", "Id": "467556", "Score": "0", "body": "Thanks, on my second revision I did add one like this. https://codereview.stackexchange.com/questions/238380/c-pointer-based-growable-stack-rev2" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T23:40:33.427", "Id": "238393", "ParentId": "238338", "Score": "1" } } ]
{ "AcceptedAnswerId": "238341", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T00:15:22.557", "Id": "238338", "Score": "7", "Tags": [ "c", "stack", "pointers" ], "Title": "C pointer based growable stack" }
238338
<p>I am trying to implement a thread-safe deque in C++. <code>ThreadSafeDeque</code> will be used by a <code>FileLogger</code> class. When threads call the <code>log()</code> function of <code>FileLogger</code> the messages will be <code>push_back()</code>ed to <code>ThreadSafeDeque</code> and return almost immediately. In a separate thread the FileLogger will <code>pop_front()</code> messages and write them to a file in its own pace. Am I doing things correctly and efficient below?</p> <pre><code>#pragma once #include &lt;deque&gt; #include &lt;mutex&gt; template&lt;class T&gt; class ThreadSafeDeque { public: void pop_front_waiting(T &amp;t) { // unique_lock can be unlocked, lock_guard can not std::unique_lock&lt;std::mutex&gt; lock{ mutex }; // locks while(deque.empty()) { condition.wait(lock); // unlocks, sleeps and relocks when woken up } t = deque.front(); deque.pop_front(); } // unlocks as goes out of scope void push_back(const T &amp;t) { std::unique_lock&lt;std::mutex&gt; lock{ mutex }; deque.push_back(t); lock.unlock(); condition.notify_one(); // wakes up pop_front_waiting } private: std::deque&lt;T&gt; deque; std::mutex mutex; std::condition_variable condition; }; </code></pre>
[]
[ { "body": "<p>It's probably worth accepting a second template argument for an Allocator to be passed through to the <code>std::deque</code>:</p>\n\n<pre><code>template&lt;class T, class Allocator = std::allocator&lt;T&gt;&gt;\nclass ThreadSafeDeque {\n std::deque&lt;T, Allocator&gt; deque;\n};\n</code></pre>\n\n<p>Technically, we do need to include <code>&lt;condition_variable&gt;</code>; we're not allowed to assume that <code>&lt;mutex&gt;</code> always pulls it in.</p>\n\n<p>I don't like the interface to <code>pop_front_waiting()</code> - why does the caller have to pass an lvalue reference, instead of simply being returned the value? Return-value optimisation will ensure there's no unnecessary copy.</p>\n\n<p>The locking logic all looks good to me. We can avoid the <code>lock.unlock()</code> by using a simple lock-guard with smaller scope:</p>\n\n<pre><code>void push_back(const T &amp;t)\n{\n {\n std::lock_guard&lt;std::mutex&gt; lock{ mutex }; \n deque.push_back(t);\n }\n condition.notify_one(); // wakes up pop_front_waiting \n}\n</code></pre>\n\n<p>From C++17, we can use constructor deduction and omit the template parameter from <code>std::lock_guard</code> and <code>std::unique_lock</code>, making the code a little easier to read.</p>\n\n<p>It's helpful to show that members are intentionally default-constructed, and it pacifies <code>g++ -Weffc++</code>:</p>\n\n<pre><code>std::deque&lt;T&gt; deque = {};\nstd::mutex mutex = {};\nstd::condition_variable condition = {};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T04:33:42.790", "Id": "467525", "Score": "0", "body": "The `pop_front_waiting` interface is necessary to provide exception safety with types that are not nothrow movable. Named return value optimization is not guaranteed, so there may be a move construction into the return value that could throw, in which case the object would already be removed from the queue and lost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T04:39:25.657", "Id": "467527", "Score": "0", "body": "Arguably move constructors shouldn't throw though, so a `static_assert(std::is_nothrow_move_constructible_v<T>)` test might be preferable to using the weird interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:17:49.793", "Id": "467541", "Score": "0", "body": "Where would there be a non-guaranteed copy elision? AFAICS, that would only be possible in old (pre-C++17) platforms. Problems would be endemic if `T` could throw when moved, as `std::deque` is allowed to move elements (e.g. in `shrink_to_fit()`). As walnut says, probably better to avoid accepting such types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:36:24.120", "Id": "467594", "Score": "0", "body": "Copy elision in a return statement was made mandatory only from prvalues, not from operands naming local variables and you need an intermediate variable to store the copy from `deque.front()`. See [cppreference](https://en.cppreference.com/w/cpp/language/copy_elision). `deque::shrink_to_fit()` does not have strong exception safety guarantees if the move constructor throws, but all the modifiers at the beginning and end of the `deque` are guaranteed to have no effect if any exceptions at all are thrown, see [\\[deque.modifiers\\]](https://timsong-cpp.github.io/cppwp/n4659/deque.modifiers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:37:29.527", "Id": "467595", "Score": "0", "body": "So if the interface was kept the way OP has it, the class would work with strong exception guarantee on both member functions, even with non-nothrow movable types." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:45:55.403", "Id": "238354", "ParentId": "238347", "Score": "8" } }, { "body": "<p>Other answers cover a lot but I also would suggest replacing </p>\n\n<pre><code>while(deque.empty()) {\n condition.wait(lock); // unlocks, sleeps and relocks when woken up \n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>condition.wait(lock, [this]{return !deque.empty();});\n</code></pre>\n\n<p>because it means the same and is more compact (readability being the same or also better).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:32:33.113", "Id": "467483", "Score": "1", "body": "Why would you suggest this change? What improvements does it bring? Can you [edit] your answer to describe the rationale?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:10:53.733", "Id": "238357", "ParentId": "238347", "Score": "3" } } ]
{ "AcceptedAnswerId": "238354", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T07:35:20.660", "Id": "238347", "Score": "8", "Tags": [ "c++", "multithreading", "thread-safety" ], "Title": "A simple thread-safe Deque in C++" }
238347
<p>I have a code that does a loop through a worksheets, if there is a value 2 inside a cell in column S, then I want to insert a row with a specific layout. I have the code, but it takes ages to complete. I've tried replacing .select function, but because I need a specific layout, I don't know how to avoid this. </p> <pre><code>LastRowMatchC = Worksheets("Compliance").Cells(Rows.Count, 1).End(xlUp).Row Dim rngc As Range, rc As Long Set rngc = Range("S8:S" &amp; LastRowMatchC) For rc = rngc.Count To 1 Step -1 If rngc(rc).Value = 2 Then rngc(rc + 1).EntireRow.Insert rngc(rc + 1).EntireRow.Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent1 .TintAndShade = 0.599993896298105 .PatternTintAndShade = 0 End With Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With Selection.Borders(xlInsideVertical).LineStyle = xlNone Selection.Borders(xlInsideHorizontal).LineStyle = xlNone End If Next rch </code></pre>
[]
[ { "body": "<ul>\n<li><p>Always use <a href=\"https://www.excel-easy.com/vba/examples/option-explicit.html\" rel=\"nofollow noreferrer\">Option Explicit</a> and declare your variables as close as possible to their first use.</p></li>\n<li><p>Fully <a href=\"https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/\" rel=\"nofollow noreferrer\">qualify your worksheet references</a> (see #5)</p></li>\n</ul>\n\n<p>When calculating your <code>LastRowMatchC</code>, always make sure to fully qualify ALL worksheet references like this </p>\n\n<pre><code>Worksheets(\"Compliance\").Cells(Worksheets(\"Compliance\").Rows.Count, 1).End(xlUp).Row\n</code></pre>\n\n<p>or</p>\n\n<pre><code>With Worksheets(\"Compliance\")\n LastRowMatchC = .Cells(.Rows.Count, 1).End(xlUp).Row\nEnd With\n</code></pre>\n\n<p>(Notice the dot in front of the <code>Rows</code>) Otherwise, the the <code>Rows.Count</code> is looking at the currently active worksheet and not the one you intended. </p>\n\n<ul>\n<li>Use <code>EnableEvents</code> and <code>ScreenUpdating</code> when you're making changes directly on the worksheet.</li>\n</ul>\n\n<p>You can turn off events and screen updating before and after your loop to give a big speed boost to the reformatting:</p>\n\n<pre><code>Application.EnableEvents = False\nApplication.ScreenUpdating = False\n\nFor rc = rngc.Count To 1 Step -1\n '--- do your thing here\nNext rc\n\nApplication.EnableEvents = True\nApplication.ScreenUpdating = True\n</code></pre>\n\n<p>(More on this in the next comment)</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/10717999/4717755\">Avoid using <code>Select</code></a> and try to define any constant \"magic values\" in an expression. No one knows why you're looking for the value \"2\" here (and you may not remember a year from now). So replace the <code>MAGIC_VALUE</code> name with something meaningful to your application. </li>\n</ul>\n\n<p>A partial example using your code:</p>\n\n<pre><code>Option Explicit\n\nSub InsertRows()\n Dim lastRow As Long\n With Worksheets(\"Compliance\")\n lastRow = .Cells(.Rows.Count, \"S\").End(xlUp).Row\n End With\n\n Dim rngc As Range\n Set rngc = Worksheets(\"Compliance\").Range(\"S8:S\" &amp; lastRow)\n\n AppPerformance SetTo:=False\n\n Const MAGIC_VALUE As Long = 2\n\n Dim rc As Long\n For rc = rngc.Rows.Count To 1 Step -1\n If rngc(rc).Value = MAGIC_VALUE Then\n rngc(rc + 1).EntireRow.Insert\n Dim newRow As Range\n Set newRow = rngc(rc + 1).EntireRow\n With newRow\n With .Interior\n .Pattern = xlSolid\n .PatternColorIndex = xlAutomatic\n .ThemeColor = xlThemeColorAccent1\n .TintAndShade = 0.599993896298105\n .PatternTintAndShade = 0\n End With\n .Borders(xlDiagonalDown).LineStyle = xlNone\n .Borders(xlDiagonalUp).LineStyle = xlNone\n With .Borders(xlEdgeLeft)\n .LineStyle = xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = xlThin\n End With\n '--- keep going with formatting ...\n End With\n End If\n Next rc\n\n AppPerformance SetTo:=True\n\nEnd Sub\n\nPrivate Sub AppPerformance(ByVal SetTo As Boolean)\n With Application\n .EnableEvents = SetTo\n .ScreenUpdating = SetTo\n End With\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:44:50.273", "Id": "467477", "Score": "0", "body": "Thanks for the great answer @PeterT!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T13:44:04.177", "Id": "238368", "ParentId": "238351", "Score": "1" } } ]
{ "AcceptedAnswerId": "238368", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:40:35.797", "Id": "238351", "Score": "2", "Tags": [ "performance", "vba", "excel" ], "Title": "Loop through a worksheet and insert a row with layout when value is true" }
238351
<p>This is my lex code to convert possibly nested for and do while loops into while loops. (Other control flows like <code>if</code> or <code>switch</code> are not supported.) The input program must be in a file called <code>input.c</code> and the output will be saved in a file called <code>out.c</code>. Please review the code and give suggestions regarding improving it.</p> <pre><code>%{ #include &lt;iostream&gt; #include&lt;vector&gt; #include&lt;tuple&gt; using namespace std; string foreword,declaration,condition1,condition2; string loopBody = ""; vector&lt;string&gt; change; vector&lt;tuple&lt;int,int&gt;&gt; stack; int ind=0; int changeNum = -1; int braces=0; void forEnd(); %} %x FOR DOWHILE dec condtn1 condtn2 chng text oneLineFor semicolon forString doWhileString normalString %% &lt;DOWHILE&gt;\" { ECHO; loopBody += yytext; BEGIN doWhileString; } &lt;text&gt;\" { ECHO; loopBody += yytext; BEGIN forString; } &lt;doWhileString&gt;\" { ECHO; loopBody += yytext; BEGIN DOWHILE; } &lt;forString&gt;\" { ECHO; loopBody += yytext; BEGIN text; } &lt;doWhileString&gt;. { ECHO; loopBody += yytext; } &lt;forString&gt;. { ECHO; loopBody += yytext; } do[ ]*\{ { stack.push_back(make_tuple(0,ind)); BEGIN DOWHILE; } &lt;text&gt;do[ ]*\{ { stack.push_back(make_tuple(0,ind)); ind = loopBody.size(); BEGIN DOWHILE; } &lt;DOWHILE&gt;do[ ]*\{ { stack.push_back(make_tuple(0,ind)); ind = loopBody.size(); BEGIN DOWHILE; } &lt;DOWHILE&gt;\} { if(braces){ ECHO; braces--; } } &lt;DOWHILE&gt;for { stack.push_back(make_tuple(2,ind)); ind = loopBody.size(); BEGIN FOR; changeNum++; } &lt;DOWHILE&gt;while[ ]*\( { ECHO; BEGIN condtn2; } &lt;condtn2&gt;[^\)]*\) { condition2 = yytext; condition2 = condition2.substr(0,condition2.size()-1); fprintf(yyout,"%s{\n",yytext); BEGIN semicolon; } &lt;semicolon&gt;; { fprintf(yyout,"%s}",loopBody.substr(ind).c_str()); if(stack.size()==1){ BEGIN 0; loopBody = ""; } else{ loopBody += "while("+condition2+"){" + loopBody.substr(ind) + "}"; ind = get&lt;1&gt;(stack.back()); stack.pop_back(); int s = get&lt;0&gt;(stack.back()); if(s==0) { BEGIN DOWHILE; } else if (s==1){ BEGIN text; } else if(s==2){ forEnd(); } } } &lt;text&gt;for { stack.push_back(make_tuple(2,ind)); ind = loopBody.size(); BEGIN FOR; changeNum++; } for { stack.push_back(make_tuple(2,ind)); ind = loopBody.size(); changeNum++; BEGIN FOR; } &lt;FOR&gt;[ ]*\( { foreword=yytext; BEGIN dec; } &lt;dec&gt;[^\;]*\; { declaration=yytext; BEGIN condtn1; } &lt;condtn1&gt;[^\;]*\; { condition1=yytext; condition1 = condition1.substr(0,condition1.size()-1); BEGIN chng; } &lt;chng&gt;[^\)]*\) { change.push_back(yytext); change[changeNum] = change[changeNum].substr(0, change[changeNum].size()-1); fprintf(yyout, "%s\n", declaration.c_str()); fprintf(yyout, "while%s%s){", foreword.c_str(), condition1.c_str()); BEGIN oneLineFor; } &lt;oneLineFor&gt;\{ { get&lt;0&gt;(stack.back()) = 1; BEGIN text; } &lt;oneLineFor&gt;for { stack.push_back(make_tuple(2,ind)); ind = loopBody.size(); BEGIN FOR; changeNum++; } &lt;oneLineFor&gt;do[ ]*\{ { stack.push_back(make_tuple(0,ind)); ind = loopBody.size(); BEGIN DOWHILE; } &lt;oneLineFor&gt;; { ECHO; forEnd(); } &lt;oneLineFor&gt;\n { ECHO; loopBody+=yytext; } &lt;oneLineFor&gt;. { ECHO; loopBody+=yytext; } &lt;text&gt;\{ { ECHO; braces++; } &lt;text&gt;\} { if(braces){ ECHO; braces--; }else{ forEnd(); } } &lt;text&gt;\n { loopBody+=yytext; ECHO; } &lt;DOWHILE&gt;\n { loopBody+=yytext; ECHO; } &lt;text&gt;. { loopBody+=yytext; ECHO; } &lt;DOWHILE&gt;. { loopBody+=yytext; ECHO; } \" { ECHO; BEGIN normalString; } &lt;normalString&gt;\" { ECHO; BEGIN 0; } &lt;normalString&gt;. { ECHO; } . {ECHO;} %% int yywrap(){return 1;} void forEnd(){ string tempChange = change[changeNum]; change.pop_back(); changeNum--; fprintf(yyout,"%s;}",tempChange.c_str()); if(stack.size()==1){ BEGIN 0; } else{ loopBody = loopBody.substr(0,ind) + declaration + "\nwhile(" + condition1 + "){" + loopBody.substr(ind) + tempChange + ";}"; ind = get&lt;1&gt;(stack.back()); stack.pop_back(); int s = get&lt;0&gt;(stack.back()); if(s==0) { BEGIN DOWHILE; } else if (s==1){ BEGIN text; } else if (s==2){ forEnd(); } } } int main() { extern FILE *yyin, *yyout; yyin = fopen("input.c", "r"); yyout = fopen("out.c", "w"); yylex(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:59:31.703", "Id": "467424", "Score": "2", "body": "why the downvote? at least comment what is wrong so I can improve the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T10:07:11.800", "Id": "467426", "Score": "4", "body": "I think people are falling over the following: \"this currently doesn't work if the loop is inside...\". It is not clear if you're looking for a fix or for a review. If the current behaviour is acceptable, the question is ok. Please clarify, after looking at our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:11:22.757", "Id": "467437", "Score": "1", "body": "@Mast i am not asking for fix. I want a review. I would have posted on Stackoverflow if I wanted a fix" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:11:39.373", "Id": "467438", "Score": "0", "body": "Welcome to Code Review! Asking for advice on code that fails to work properly is off-topic for this site (regardless of whether you are asking for a fix). See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference. Once you have written working code, you're welcome to ask a new question here and we can then help you improve it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:16:27.763", "Id": "467442", "Score": "0", "body": "@L.F. the code is working though. I even said that in the question. I just said it doesn't cover one case of the for loop which I have intentionally ignored. otherwise it is working" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T11:38:30.047", "Id": "467449", "Score": "7", "body": "OK ... That really wasn't apparent. I've reworded the question slightly for you. However, your description is very general - there are many ways to convert for loops to do while loops. Please add some test cases (input, output) to show the intended usage of the program as well as to manifest that your code is really working. After you do this, your question will be on-topic for the site." } ]
[ { "body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\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. </p>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has inconsistent formatting. For example, some places use tabs for indentation and other use four or eight spaces and sometimes there is a space after <code>#include</code> and sometimes not (I prefer the space). Pick a style and apply it consistently. </p>\n\n<h2>Describe your program better</h2>\n\n<p>For code reviewers and for any reader of your code, there should be a clear explanation of the purpose of the code. As one comment noted, the description \"convert do a for loops into while loops\" is quite vague. What transformations are being done and why? What is the expected output? Is it supposed to handle macros, for example?</p>\n\n<h2>Test your code</h2>\n\n<p>There's not much evidence here that the code has been tested, and a test stub is often a good way to both make sure there are fewer errors in the code and also to convey what the program is intended to do. For example, I used this sample input:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n/* This is a comment and shouldn't be touched...\nfor (int i=10; i; --i) {\n*/\n\nint main() {\n int x = 0;\n\n for (int i=10; i; --i) {\n for (int j = i; j; --j, x+=i*j) {\n for (int x=1; x; --x) \n printf(\"%d\\n\", i*j);\n }\n }\n\n while (x &gt; 10000) \n x &gt;&gt;= 1;\n\n printf(\"%d\\n\", x);\n}\n</code></pre>\n\n<p>This results in a program which compiles and runs without error. If we use this software to transform it, it still results in a program which compiles and runs without error, but the output is completely different and never terminates! </p>\n\n<h2>Rethink your approach</h2>\n\n<p>The current lexer works but relies on thirteen different possible states which is a heavy cognitive load for any programmer reading or modifying this code. As an example, there is not really much difference between the <code>FOR</code> state and the <code>oneLineFor</code> state and I strongly suspect they should be combined.</p>\n\n<h2>Eliminate redundant rules</h2>\n\n<p>The code contains these four rules:</p>\n\n<pre><code>&lt;text&gt;\\n {\n loopBody+=yytext;\n ECHO;\n}\n&lt;DOWHILE&gt;\\n {\n loopBody+=yytext;\n ECHO;\n}\n&lt;text&gt;. {\n loopBody+=yytext;\n ECHO;\n}\n&lt;DOWHILE&gt;. {\n loopBody+=yytext;\n ECHO;\n</code></pre>\n\n<p>They can all be reduced to this single rule:</p>\n\n<pre><code>&lt;text,DOWHILE&gt;.|\\n {\n loopBody+=yytext;\n ECHO;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T14:20:46.380", "Id": "238477", "ParentId": "238352", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T09:44:04.470", "Id": "238352", "Score": "1", "Tags": [ "c++", "lex", "flex" ], "Title": "Lex code to convert C for and do while loops into while loops" }
238352
<p>I have created a <a href="https://en.wikipedia.org/wiki/Mastermind_(board_game)" rel="nofollow noreferrer"><em>Master Mind</em></a> <code>BoardSolver</code>. To apply the <code>BoardSolver</code> I have created an app (<code>MasterMind</code>) in which I create a <code>Board</code> with <code>ColorPin</code>s and <code>CheckPin</code>s. <code>ColorPin</code>s and <code>CheckPin</code>s are associated within a <code>PinRow</code>. A <code>Board</code> represents a given <code>PinRow</code> (code) and a List of <code>PinRow</code>s as attempts. </p> <p>Please can you review this code? </p> <h2>Structure</h2> <p><a href="https://i.stack.imgur.com/IZF8O.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IZF8O.jpg" alt="enter image description here"></a></p> <h2>Code</h2> <h3>Board</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.ArrayList; import java.util.List; public class Board { private final int maxAttempts; private final PinRow code; private final List&lt;PinRow&gt; attempts = new ArrayList&lt;&gt;(); public Board(PinRow code, int maxAmountTrials) { this.code = code; this.maxAttempts = maxAmountTrials; } public List&lt;PinRow&gt; getAttempts() { return attempts; } public List&lt;CheckPin&gt; addAttempt(PinRow trial) { attempts.add(trial); trial.check(code); return trial.getCheckResult(); } private List&lt;CheckPin&gt; getLatestResult() { PinRow pinRow = attempts.get(attempts.size() - 1); pinRow.check(code); return pinRow.getCheckResult(); } public boolean isSolved() { return code.getWidth() == getLatestResult().stream().filter(CheckPin.BLACK::equals).count(); } public int getCodeWidth() { return code.getWidth(); } public PinRow getCode() { return code; } public int getMaxAttempts() { return maxAttempts; } public boolean isAttemptLimitReached() { return attempts.size() &lt; maxAttempts; } } </code></pre> <h3>ColorPin</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.*; public enum ColorPin { RED, GREEN, BLUE, YELLOW, PURPLE, WHITE, ORANGE, GRAY, BLACK, CYAN; public static Set&lt;ColorPin&gt; randomSet(int amountColors) { List&lt;ColorPin&gt; all = Arrays.asList(ColorPin.values()); Collections.shuffle(all); return new HashSet&lt;&gt;(all.subList(0, amountColors)); } public static int maxWordLength(){ return Arrays.stream(values()).mapToInt(c -&gt; c.toString().length()).max().orElse(0); } } </code></pre> <h3>CheckPin</h3> <pre><code>package com.github.martinfrank.mastermind; public enum CheckPin { WHITE, //proper color, wrong location BLACK; //proper color, proper location } </code></pre> <h3>PinRow</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.*; import java.util.stream.IntStream; public class PinRow { private final int width; private final ColorPin[] colors; private List&lt;CheckPin&gt; checkResult = new ArrayList&lt;&gt;(); public PinRow(int[] indices, Set&lt;ColorPin&gt; givenColors) { List&lt;ColorPin&gt; sampleColors = new ArrayList&lt;&gt;(givenColors); width = indices.length; colors = new ColorPin[width]; IntStream.range(0, width).forEach(c -&gt; colors[c] = sampleColors.get(indices[c])); } public static PinRow randomPinRow(int codeWidth, Set&lt;ColorPin&gt; colors) { int[] indices = new int[codeWidth]; int amountColors = colors.size(); IntStream.range(0, codeWidth).forEach(c -&gt; indices[c] = new Random().nextInt(amountColors)); return new PinRow(indices, colors); } public List&lt;CheckPin&gt; check(PinRow code) { checkResult.clear(); List&lt;ColorPin&gt; myRemaining = new ArrayList&lt;&gt;(); List&lt;ColorPin&gt; codeRemaining = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; width; i++) { ColorPin current = colors[i]; ColorPin expected = code.colors[i]; if (current == expected) { checkResult.add(CheckPin.BLACK); } else { myRemaining.add(current); codeRemaining.add(expected); } } for (ColorPin mine : myRemaining) { for (ColorPin candidate : codeRemaining) { if (mine.equals(candidate)) { codeRemaining.remove(candidate); checkResult.add(CheckPin.WHITE); break; } } } return checkResult; } @Override public String toString(){ return Arrays.toString(colors); } public List&lt;CheckPin&gt; getCheckResult() { return checkResult; } public List&lt;ColorPin&gt; getColorPins() { return Arrays.asList(colors); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PinRow pinRow = (PinRow) o; return Arrays.equals(colors, pinRow.colors); } @Override public int hashCode() { return Arrays.hashCode(colors); } public int getWidth() { return width; } } </code></pre> <h3>PinChecker</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.List; public class PinChecker { private final List&lt;CheckPin&gt; reference; public PinChecker(List&lt;CheckPin&gt; reference) { this.reference = reference; } public boolean isSuperior(List&lt;CheckPin&gt; candidate){ if( candidate.size() &lt; reference.size()){ return false; } if( candidate.size() == reference.size()){ long baseBlack = reference.stream().filter(cp -&gt; cp==CheckPin.BLACK).count(); long candidateBlack = candidate.stream().filter(cp -&gt; cp==CheckPin.BLACK).count(); return candidateBlack &lt;= baseBlack; } return false; } } </code></pre> <h3>BoardSolver</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.*; import java.util.stream.Collectors; public class BoardSolver { private final Board board; private final Set&lt;ColorPin&gt; colors; private final Random random; public BoardSolver(Board board, Set&lt;ColorPin&gt; colors) { this.board = board; this.colors = colors; random = new Random(); } public void solve() { int codeWidth = board.getCodeWidth(); List&lt;PinRow&gt; combinations = PinRowCombinations.getAll(colors, codeWidth); do { PinRow attempt = removeRandom(combinations); PinChecker pinChecker = new PinChecker(board.addAttempt(attempt)); combinations = combinations.stream().filter(pr -&gt; pinChecker.isSuperior(pr.check(attempt))).collect(Collectors.toList()); } while (!board.isSolved() &amp;&amp; board.isAttemptLimitReached()); } private PinRow removeRandom(List&lt;PinRow&gt; combinations) { return combinations.remove(random.nextInt(combinations.size())); } } </code></pre> <h3>PinRowCombinations</h3> <pre><code>package com.github.martinfrank.mastermind; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.IntStream; public class PinRowCombinations { public static List&lt;PinRow&gt; getAll(Set&lt;ColorPin&gt; colors, int width) { int amountColors = colors.size(); int size = (int)Math.pow( amountColors, width); List&lt;PinRow&gt; result = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; size; i ++){ BigInteger bi = BigInteger.valueOf(i); int[] indices = createIndice(leadingZeros(bi.toString(amountColors), width) ); result.add(new PinRow(indices, colors)); } return result; } private static String leadingZeros(String numberString, int size) { StringBuilder sb = new StringBuilder(); IntStream.range(0,size-numberString.length()).forEach(i -&gt; sb.append("0")); sb.append(numberString); return sb.toString(); } private static int[] createIndice(String numberString) { int length = numberString.length(); int[] indice = new int[length]; IntStream.range(0,length).forEach(i -&gt; indice[i] = createIndex(numberString.charAt(i))); return indice; } private static int createIndex(char charAt) { if (charAt &gt;= '0' &amp;&amp; charAt &lt;= '9'){ return charAt-'0'; }else{ return charAt-'a'+10; } } } </code></pre> <h3>BoardPrinter</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; public class BoardPrinter { public static void print(Board board){ final int columnSize = ColorPin.maxWordLength(); final int codeWidth = board.getCodeWidth(); final PinRow code = board.getCode(); String separator = createSeparator(columnSize+2, codeWidth); String bigSeparator = createSeparator(columnSize+2, codeWidth, '='); System.out.println((board.isSolved()?"":"not ")+"solved in "+board.getAttempts().size()+" turns..."); System.out.println(separator); System.out.println(printRow(code, columnSize)+emptyPins(codeWidth, columnSize)); System.out.println(bigSeparator); for(int i = board.getMaxAttempts()-1; i &gt;= 0; i --){ if(i &lt; board.getAttempts().size() ){ PinRow trial = board.getAttempts().get(i); System.out.println(printRow(trial, columnSize)+printCheck(trial.getCheckResult(), codeWidth, columnSize)); }else{ System.out.println(emptyPins(codeWidth, columnSize)+emptyPins(codeWidth, columnSize)); } System.out.println(separator); } } private static String emptyPins(int codeWidth, int columnSize) { StringBuilder sb = new StringBuilder("|"); IntStream.range(0,codeWidth).forEach(i -&gt; append(sb, " ", centerString("", columnSize), " |")); return sb.toString(); } private static String createSeparator(int columsSize, int codeWidth) { return createSeparator(columsSize, codeWidth, '-'); } private static String createSeparator(int columsSize, int codeWidth, char c) { StringBuilder sb = new StringBuilder("+"); String stroke = createStroke(columsSize, c); IntStream.range(0,codeWidth).forEach(i -&gt; append(sb,stroke,"+")); sb.append("+"); IntStream.range(0,codeWidth).forEach(i -&gt; append(sb,stroke,"+")); return sb.toString(); } private static String createStroke(int strokeLength, char c) { StringBuilder sb = new StringBuilder(); IntStream.range(0,strokeLength).forEach(i -&gt; sb.append(c)); return sb.toString(); } private static void append(StringBuilder sb, String... values){ Arrays.stream(values).forEach(sb::append); } private static String printCheck(List&lt;CheckPin&gt; checkers, int codeWidth, int columnLength) { StringBuilder sb = new StringBuilder("|"); for(int i = 0; i &lt; codeWidth; i++){ String value = i &lt; checkers.size()?checkers.get(i).toString():" "; append(sb, " ",centerString(value, columnLength)," |"); } return sb.toString(); } private static String printRow(PinRow row, int columnLength) { StringBuilder sb = new StringBuilder("|"); row.getColorPins().forEach(cp -&gt; append(sb, " ",centerString(cp.toString(), columnLength)," |")); return sb.toString(); } public static String centerString (String string, int width) { return String.format("%-" + width + "s", String.format("%" + (string.length() + (width - string.length()) / 2) + "s", string)); } } </code></pre> <h3>MasterMind</h3> <pre><code>package com.github.martinfrank.mastermind; import java.util.Set; public class MasterMind { public static void main(String[] args){ final int codeWidth = 4; final Set&lt;ColorPin&gt; colors = ColorPin.randomSet(6); final int maxAmountTrials = 20; final PinRow code = PinRow.randomPinRow(codeWidth, colors); Board board = new Board(code, maxAmountTrials); BoardSolver solver = new BoardSolver(board, colors); solver.solve(); BoardPrinter.print(board); } } </code></pre> <h2>Accepted Answer</h2> <p>I've been sick for a few days so i was not able to react any sooner. It's hard for me to pick the right answer out of these here, they are all really helpful and every answer discovers more improvements on my code. So I can't pick one and accept it without disrespecting the answers of the others. That's why i don't accept <strong>one</strong> but all answer here!!!</p>
[]
[ { "body": "<p>Pretty good code in general. Well formatted and easy to read.</p>\n\n<p><strong>Board</strong></p>\n\n<p>I feel like the game constraints should exist in some common location. In this case the Board should know how many tries there are and how many pins each row may contain. Now it is possible to add different sized PinRows to a Board and no checking is performed. A trial shorter than the code results in an error.</p>\n\n<p>In the <code>addAttempt(...)</code> method the responsibility of checking the code is placed on the incoming PinRow. This provides an opportunity for the caller to inject a subclass of PinRow with an overridden check(...) method that records the code and solve the problem in two tries via cheating. I would move the code checking into a separate class, as I consider the PinRow to be a \"dumb\" data container.</p>\n\n<p>In general, I would make the representation of the board as simple as possible and place the game logic into a separate game engine.</p>\n\n<p><strong>ColorPin</strong></p>\n\n<p>Hard coded UI colours. Allowing unlimited pin row length would logically suggest that unlimited colors are also allowed. Better leave the colours for the UI and just use integers here.</p>\n\n<p><strong>CheckPin</strong></p>\n\n<p>This blends UI code again to the game logic. The enums should just be named \"COLOR_IN_CORRECT_LOCATION\" an \"COLOR_IN_WRONG_LOCATION\" instead of making the programmer remember what the colours actually mean. A command line UI probably wouldn't have colours anyway.</p>\n\n<p><strong>PinRow</strong></p>\n\n<p>The \"colors\" field should be named \"pins\", because it is a row of pins.</p>\n\n<p>Replacing for-loops with IntStreams isn't my cup of tea. The code is not easily understandable at all. I would like to see JavaDocs for the constructor parameters as they are not very intuitive. To create a PinRow I would expect to be required to just provide a number of ColorPin references that matches the size of the row. I assume you chose this constructor to make it easier to create the combinations in the solver. If you're implementing a Master Mind game, it's API should reflect the use cases needed when playing and the solver should adapt to the API, not the other way around.</p>\n\n<p>The <code>randomPinRow()</code> method hard codes the game logic into the data object. For example it is now not very easy to switch to game rules that allow empty pins. This could be extracted into a separate class that implements <code>Supplier&lt;PinRow&gt;</code>. A devious \"code master\" would learn the \"code breaker's\" habits and that could be implemented in the supplier.</p>\n\n<p>Split the <code>PinRow</code> and <code>CheckResult</code> into separate classes to follow single responsibility principle and introduce a new <code>PlayerGuess</code> to connect them.</p>\n\n<p><strong>PinChecker</strong></p>\n\n<p>The <code>PinChecker</code> is essentially a <code>Comparator&lt;CheckResult&gt;</code>. You should use standard library tools when possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T13:27:07.847", "Id": "238366", "ParentId": "238363", "Score": "7" } }, { "body": "<p>This is a very nice project, some suggestions for you:</p>\n\n<h2>Board</h2>\n\n<p>You have the following code:</p>\n\n<blockquote>\n<pre><code>public class Board {\n private final int maxAttempts;\n private final PinRow code;\n private final List&lt;PinRow&gt; attempts = new ArrayList&lt;&gt;();\n public Board(PinRow code, int maxAmountTrials) {\n this.code = code;\n this.maxAttempts = maxAmountTrials;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can put initialization of field <code>attempts</code> inside the constructor:</p>\n\n<pre><code>public class Board {\n\n private final int maxAttempts;\n private final PinRow code;\n private final List&lt;PinRow&gt; attempts;\n\n public Board(PinRow code, int maxAmountTrials) {\n this.code = code;\n this.maxAttempts = maxAmountTrials;\n this.attempts = new ArrayList&lt;&gt;();\n }\n}\n</code></pre>\n\n<h2>PinRow</h2>\n\n<p>You have the following method:</p>\n\n<blockquote>\n<pre><code>public static PinRow randomPinRow(int codeWidth, Set&lt;ColorPin&gt; colors) {\n int[] indices = new int[codeWidth];\n int amountColors = colors.size();\n IntStream.range(0, codeWidth).forEach(c -&gt; indices[c] = new Random().nextInt(amountColors));\n return new PinRow(indices, colors);\n}\n</code></pre>\n</blockquote>\n\n<p>You can reduce method using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-long-int-int-\" rel=\"noreferrer\">Random.ints</a>:</p>\n\n<pre><code> public static PinRow randomPinRow(int codeWidth, Set&lt;ColorPin&gt; colors) {\n int[] indices = new Random().ints(codeWidth, 0, colors.size()).toArray();\n return new PinRow(indices, colors);\n }\n</code></pre>\n\n<h2>PinRowCombinations</h2>\n\n<p>You have the following methods:</p>\n\n<blockquote>\n<pre><code>private static String leadingZeros(String numberString, int size) {\n StringBuilder sb = new StringBuilder();\n IntStream.range(0,size-numberString.length()).forEach(i -&gt; sb.append(\"0\"));\n sb.append(numberString);\n return sb.toString();\n}\nprivate static int[] createIndice(String numberString) {\n int length = numberString.length();\n int[] indice = new int[length];\n IntStream.range(0,length).forEach(i -&gt; indice[i] = createIndex(numberString.charAt(i)));\n return indice;\n}\nprivate static int createIndex(char charAt) {\n if (charAt &gt;= '0' &amp;&amp; charAt &lt;= '9'){\n return charAt-'0';\n } else{\n return charAt-'a'+10;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The methods can be rewritten using <code>Collections</code> and a chars stream:</p>\n\n<pre><code>private static String leadingZeros(String numberString, int size) {\n return String.join(\"\", Collections.nCopies(size - numberString.length(), \"0\")) + numberString;\n}\n\nprivate static int[] createIndice(String numberString) {\n return numberString.chars().map(i -&gt; createIndex((char) i)).toArray();\n}\n\nprivate static int createIndex(char charAt) {\n if (Character.isDigit(charAt)) { return charAt - '0';}\n return charAt - 'a'+ 10; \n}\n</code></pre>\n\n<h2>BoardPrinter</h2>\n\n<p>Again the <code>Collections.nCopies</code> method so you can write:</p>\n\n<pre><code>private static String createStroke(int strokeLength, char c) {\n StringBuilder sb = new StringBuilder();\n IntStream.range(0,strokeLength).forEach(i -&gt; sb.append(c));\n return sb.toString();\n}\n</code></pre>\n\n<p>The new version of the method is:</p>\n\n<pre><code>private static String createStroke(int strokeLength, char c) {\n return String.join(\"\", Collections.nCopies(strokeLength, Character.toString(c)));\n}\n</code></pre>\n\n<p>Probably in the class BoardPrinter the method <code>nCopies</code> could be used to abbreviate some part of the code, and I suspect that in other classes some method about comparison could be deleted maybe implementing some compare interface, anyway the project is well structured and articulate. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T09:28:28.787", "Id": "238409", "ParentId": "238363", "Score": "5" } }, { "body": "<p>The <code>BoardSolver</code> can be initialized with a different set of <code>colors</code> than the code, which would lead in an unsolvable solution which is not correct because the board is solvable:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>final Set&lt;ColorPin&gt; colors = /* red, blue*/;\nfinal Set&lt;ColorPin&gt; otherColors = /* yellow, green */;\n\nfinal PinRow code = PinRow.randomPinRow(codeWidth, colors);\nBoard board = new Board(code, maxAmountTrials);\nBoardSolver solver = new BoardSolver(board, otherColors);\n</code></pre>\n</blockquote>\n\n<p>For each <code>Board</code> a new <code>BoardSolver</code> is needed:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Board board = new Board(/* ... */);\nBoard otherBoard = new Board(/* ... */);\n\nBoardSolver solver = new BoardSolver(board, ...);\nBoardSolver solver = new BoardSolver(otherBoard, ...);\n</code></pre>\n</blockquote>\n\n<p>I think a <code>BoardSolver</code> does not need to depend on a specific <code>Board</code> by its construction. Instead we should pass the board as an argument to <code>solve</code>. Since the <code>Board</code> knows <code>code</code> which knows <code>colors</code> the <code>BoardSolver</code> does not need its own <code>colors</code> because it knows the <code>colors</code> through the <code>Board</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n /* ... */\n BoardSolver solver = new BoardSolver();\n Board board = new Board(code, maxAmountTrials);\n\n solver.solve(board);\n BoardPrinter.print(board);\n}\n</code></pre>\n\n<p>Personally I find it cleaner if <code>solve</code> would return a <code>Board</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n /* ... */\n Board solved = solver.solve(board);\n BoardPrinter.print(solved);\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>check</code> method in <code>PinRow</code> returns a <code>List</code> that contains <code>BLACK</code> and <code>WHITE</code> pins: </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public List&lt;CheckPin&gt; check(PinRow code) {\n\n /* add BLACK to checkreult */\n\n /* add WHITE to checkreult */&gt;\n\n return checkResult;\n}\n</code></pre>\n</blockquote>\n\n<p>To check if you solved the game a loop through the <code>List</code> is needed to check if an attempt is correct:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public boolean isSolved() {\n return code.getWidth() == getLatestResult().stream().filter(CheckPin.BLACK::equals).count();\n}\n</code></pre>\n</blockquote>\n\n<p>When you <code>check</code>, you could store the number of <code>BLACK</code> and <code>WHITE</code> pins instead of instances of them in a <code>List</code>. </p>\n\n<p>For instance when you write a shopping list you do not write it this way:</p>\n\n<pre><code>milk\nmilk\neggs\nmilk\neggs\n</code></pre>\n\n<p>Now you have to count (loop like in <code>isSolved</code>) through the list to find the amount of milk and eggs</p>\n\n<p>We can save directly the amounts of <code>BLACK</code> and <code>WHITE</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Resultcheck(PinRow code) {\n int amountOfBlack;\n int amoutOfWhite;\n for (int i = 0; i &lt; width; i++) {\n /* amountOfBlack++ */\n /* amoutOfWhite++ */\n }\n return new Result(amountOfBlack, amoutOfWhite);\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isSolved() {\n return code.getWidth() == getLatestResult().amountOfBlack;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:34:16.290", "Id": "238413", "ParentId": "238363", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T12:22:16.220", "Id": "238363", "Score": "9", "Tags": [ "java", "object-oriented" ], "Title": "Master Mind implementation" }
238363
<p>I am currently trying to replicate the STL <code>std::list</code> interface with my own list implementation (doubly linked list with sentinel) to learn about all the advanced topics (like iterators, allocators, ...). Before I add the methods from the "operations" section in the <a href="http://www.cplusplus.com/reference/list/list/" rel="nofollow noreferrer">documentation</a>, I'd love to hear your thoughts and feedback to what I've got so far.</p> <pre><code>#ifndef DOUBLY_LINKED_LIST_HH #define DOUBLY_LINKED_LIST_HH #include &lt;stdexcept&gt; // exceptions #include &lt;type_traits&gt; // remove_cv #include &lt;utility&gt; // swap #include &lt;cstddef&gt; // ptrdiff_t #include &lt;cassert&gt; // assert #include &lt;initializer_list&gt; // initializer_list #include &lt;memory&gt; // allocator_traits template&lt;typename T, typename _Alloc = std::allocator&lt;T&gt;&gt; class list { private: #pragma region Node struct Node { Node(Node* prev, Node* next) : prev(prev), next(next) { } Node(Node* prev, Node* next, const T&amp; data) : prev(prev), next(next), data(data) { } Node(Node* prev, Node* next, T&amp;&amp; data) : prev(prev), next(next), data(std::move(data)) { } T data; Node* prev; Node* next; }; #pragma endregion #pragma region Iterator template&lt;typename R&gt; struct Iterator { Node* current; Iterator(Node* node) : current(node) { } Iterator(const list&amp; list, size_t index = 0) : current(list.sentinel-&gt;next) { operator+(index); }; bool operator==(Iterator const&amp; other) const { return current == other.current; } bool operator!=(Iterator const&amp; other) const { return !(*this == other); } Iterator&amp; operator++() { current = current-&gt;next; return *this; } Iterator&amp; operator--() { current = current-&gt;prev; return *this; } Iterator&amp; operator++(int) { Iterator result(*this); ++(*this); return result; } Iterator operator--(int) { Iterator result(*this); --(*this); return result; } Iterator&amp; operator+(size_t offset) { for (size_t i = 0; i &lt; offset; ++i) operator++(); return *this; } Iterator&amp; operator-(size_t offset) { for (size_t i = 0; i &lt; offset; ++i) operator--(); return *this; } R&amp; operator*() const { return current-&gt;data; } R* operator-&gt;() const { return &amp;(current-&gt;data); } }; #pragma endregion Node* sentinel; size_t element_count; public: using allocator_type = _Alloc; using value_type = T; using reference = typename _Alloc::reference; using const_reference = typename _Alloc::const_reference; using pointer = typename _Alloc::pointer; using const_pointer = typename _Alloc::const_pointer; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = Iterator&lt;T&gt;; using const_iterator = Iterator&lt;const T&gt;; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; #pragma region Big Five list() { sentinel = new Node(nullptr, nullptr); sentinel-&gt;next = sentinel; sentinel-&gt;prev = sentinel; } ~list() { clear(); delete sentinel; } list(list&amp;&amp; other) noexcept // move constructor { other.swap(*this); } list(const list&amp; other) // copy constructor { for (auto const&amp; val : other) { push_back(val); } } list&amp; operator=(const list&amp; other) // copy assignment { return *this = list(other); } list&amp; operator=(list&amp;&amp; other) noexcept // move assignment { other.swap(*this); return *this; } #pragma endregion #pragma region Modifiers void swap(list&amp; other) noexcept { std::swap(sentinel-&gt;next-&gt;prev, other.sentinel-&gt;next-&gt;prev); std::swap(sentinel-&gt;prev-&gt;next, other.sentinel-&gt;prev-&gt;next); std::swap(sentinel-&gt;next, other.sentinel-&gt;next); std::swap(sentinel-&gt;prev, other.sentinel-&gt;prev); std::swap(element_count, other.element_count); } void push_back(const T&amp; value) { Node* n = new Node(sentinel-&gt;prev, sentinel, value); sentinel-&gt;prev-&gt;next = n; sentinel-&gt;prev = n; ++element_count; } void push_back(T&amp;&amp; value) { Node* n = new Node(sentinel-&gt;prev, sentinel, std::move(value)); sentinel-&gt;prev-&gt;next = n; sentinel-&gt;prev = n; ++element_count; } void push_back() { Node* n = new Node(sentinel-&gt;prev, sentinel); sentinel-&gt;prev-&gt;next = n; sentinel-&gt;prev = n; ++element_count; } void push_front(const T&amp; value) { Node* n = new Node(sentinel, sentinel-&gt;next, value); sentinel-&gt;next-&gt;prev = n; sentinel-&gt;next = n; ++element_count; } void push_front(T&amp;&amp; value) { Node* n = new Node(sentinel, sentinel-&gt;next, std::move(value)); sentinel-&gt;next-&gt;prev = n; sentinel-&gt;next = n; ++element_count; } void pop_back() { // No exception according to specification: https://timsong-cpp.github.io/cppwp/n3337/container.requirements.general#10 Node* tmp = sentinel-&gt;prev; sentinel-&gt;prev = sentinel-&gt;prev-&gt;prev; sentinel-&gt;prev-&gt;next = sentinel; delete tmp; --element_count; } void pop_front() { Node* tmp = sentinel-&gt;next; sentinel-&gt;next = sentinel-&gt;next-&gt;next; sentinel-&gt;next-&gt;prev = sentinel; delete tmp; --element_count; } void clear() { Node* next; for (Node* n = sentinel-&gt;next; n != sentinel; n = next) { next = n-&gt;next; delete n; } sentinel-&gt;next = sentinel; sentinel-&gt;prev = sentinel; element_count = 0; } template&lt;class InputIterator&gt; void assign(InputIterator first, InputIterator last) { clear(); for (InputIterator it = first; it != last; ++it) { push_back(*it); } } void assign(size_type n, const value_type&amp; val) { clear(); for (size_t i = 0; i &lt; n; i++) { push_back(val); } } void assign (std::initializer_list&lt;value_type&gt; list) { clear(); for (const value_type&amp; i : list) { push_back(i); } } template&lt;class... Args&gt; void emplace(const_iterator position, Args&amp;&amp;... args) { Node* node = new Node(position.current-&gt;prev, position.current); allocator_type alloc; std::allocator_traits&lt;allocator_type&gt;::construct(alloc, &amp;(node-&gt;data), std::forward&lt;Args&gt;(args)...); position.current-&gt;prev-&gt;next = node; position.current-&gt;prev = node; } template &lt;class... Args&gt; void emplace_front (Args&amp;&amp;... args) { emplace(cbegin(), args...); } template&lt;class... Args&gt; void emplace_back(Args&amp;&amp;... args) { emplace(cend(), args...); } template &lt;class InputIterator&gt; iterator insert (const_iterator position, InputIterator first, InputIterator last) { iterator result; Node* prev = position.current-&gt;prev; Node* current = nullptr; size_t count = 0; for (InputIterator it = first; it != last; ++it) { current = new Node(prev, nullptr, *it); if (it == first) result = iterator(current); prev-&gt;next = current; prev = current; ++element_count; } if (current != nullptr) current-&gt;next = position; return result; } iterator insert(const_iterator position, size_type n, const value_type&amp; val) { insert(position, {val, n}); } iterator insert(const_iterator position, std::initializer_list&lt;value_type&gt; il) { insert(position, il.begin(), il.end()); } iterator insert(const_iterator position, const value_type&amp; val) { insert(position, {val}); } void resize(size_type n) { resize(n, T{}); } void resize (size_type n, const value_type&amp; val) { if (size() &lt; n) { iterator first = begin() += n-1; erase(first, end()); } else if (size() &gt; n) { for (size_t i = 0; i &lt; size() - n; ++i) { push_back(val); } } } iterator erase(const_iterator position) { erase(position, const_iterator(position.current-&gt;next)); } iterator erase(const_iterator first, const_iterator last) { iterator result = iterator(last.current-&gt;next); Node* current = first.current; while (current != last.current) { Node* tmp = current; current = current-&gt;next; delete tmp; --element_count; } return result; } #pragma endregion #pragma region Element access reference front() { return sentinel-&gt;next-&gt;data; } const_reference front() const { return sentinel-&gt;next-&gt;data; } reference back() { return sentinel-&gt;prev-&gt;data; } const_reference back() const { return sentinel-&gt;prev-&gt;data; } reference operator[](size_t index) { return *(iterator(*this, index)); } const_reference operator[](size_t index) const { *this[index]; } reference at(size_t index) { if (index &gt;= size()) throw throw std::out_of_range("index out of bounds"); return *this[index]; } const_reference at(size_t index) const { return at(index); } #pragma endregion #pragma region Capacity size_t size() const { return element_count; } bool empty() const { return size() == 0; } #pragma endregion #pragma region Iterators iterator begin() { return iterator(sentinel-&gt;next); } iterator end() { return iterator(sentinel); } const_iterator begin() const { return const_iterator(sentinel-&gt;next); } const_iterator end() const { return const_iterator(sentinel); } const_iterator cbegin() const { return const_iterator(sentinel-&gt;next); } const_iterator cend() const { return const_iterator(sentinel); } reverse_iterator rbegin() { return reverse_iterator(end); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } consse_iterator rend() const { return const_reverse_iterator(begin()); } const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } #pragma endregion }; #endif // !DOUBLY_LINKED_LIST_HH </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T21:35:14.460", "Id": "467507", "Score": "1", "body": "I'm finding numerous little errors in this, including an apparent compilation error in `resize`. How extensively have you tested this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T22:29:19.980", "Id": "467512", "Score": "0", "body": "Fix all the compilation errors, test your code and fix the obvious logical errors, then come back and [edit] the corrected code into the question. As it stands the code is not working and not in a reviewable state. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T01:13:00.120", "Id": "467517", "Score": "0", "body": "Currently does not compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T02:18:17.977", "Id": "467524", "Score": "0", "body": "Compiler errors here: https://wandbox.org/permlink/7yK3xWyGCLoX7idE" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T13:35:26.573", "Id": "238367", "Score": "2", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "c++17", "collections" ], "Title": "Implementation of Doubly Linked List with sentinel in C++ trying to replicate the stl std::list" }
238367
<p>I've been recently fooling around with Go(lang) and ended up doing a (very) simple pig Latin parser. I'm pretty sure this is not the best solution out there (no punctuation and only lowercase letters) but it does its job.</p> <p>However, I'd be delighted to learn how this could be improved, as I'm still pretty new to Go.</p> <p>Here's the code and at the bottom some test cases.</p> <pre><code>package igpay import "strings" const pigTail = "ay" func PigIt(input string) string { if len(input) == 0 { return "" } words := strings.Fields(strings.ToLower(input)) result := make([]string, len(words)) for _, word := range words { if len(word) &lt; 3 { result = append(result, piggify(word, 1)) continue } switch word[:3] { case "squ", "sch", "thr": result = append(result, piggify(word, 3)) continue } switch word[:2] { case "ch", "qu", "th", "rh": result = append(result, piggify(word, 2)) continue case "ye", "xe": result = append(result, piggify(word, 1)) continue } switch word[:1] { case "a", "e", "o", "u", "i", "y", "x": result = append(result, word+pigTail) continue } result = append(result, piggify(word, 1)) } return strings.TrimLeft(strings.Join(result, " "), " ") } func piggify(word string, index int) string { return word[index:]+word[:index]+pigTail } </code></pre> <p><strong>Test cases:</strong></p> <pre><code>package igpay var testCases = []struct { description string input string expected string }{ { description: "word beginning with a", input: "apple", expected: "appleay", }, { description: "word beginning with e", input: "ear", expected: "earay", }, { description: "word beginning with i", input: "igloo", expected: "iglooay", }, { description: "word beginning with o", input: "object", expected: "objectay", }, { description: "word beginning with u", input: "under", expected: "underay", }, { description: "word beginning with a vowel and followed by a qu", input: "equal", expected: "equalay", }, { description: "word beginning with p", input: "pig", expected: "igpay", }, { description: "word beginning with k", input: "koala", expected: "oalakay", }, { description: "word beginning with x", input: "xenon", expected: "enonxay", }, { description: "word beginning with q without a following u", input: "qat", expected: "atqay", }, { description: "word beginning with ch", input: "chair", expected: "airchay", }, { description: "word beginning with qu", input: "queen", expected: "eenquay", }, { description: "word beginning with qu and a preceding consonant", input: "square", expected: "aresquay", }, { description: "word beginning with th", input: "therapy", expected: "erapythay", }, { description: "word beginning with thr", input: "thrush", expected: "ushthray", }, { description: "word beginning with sch", input: "school", expected: "oolschay", }, { description: "word beginning with yt", input: "yttria", expected: "yttriaay", }, { description: "word beginning with xr", input: "xray", expected: "xrayay", }, { description: "y is treated like a consonant at the beginning of a word", input: "yellow", expected: "ellowyay", }, { description: "y is treated like a vowel at the end of a consonant cluster", input: "rhythm", expected: "ythmrhay", }, { description: "y as second letter in two letter word", input: "my", expected: "ymay", }, { description: "a whole phrase", input: "quick fast run", expected: "ickquay astfay unray", }, } </code></pre> <p><strong>Test:</strong></p> <pre><code>package igpay import ( "fmt" "testing" ) func TestPigLatin(t *testing.T) { for _, test := range test cases { if pl := PigIt(test.input); pl != test.expected { t.Fatalf("FAIL: Sentence(%q) = %q, want %q.", test.input, pl, test.expected) } fmt.Printf("PASS: %s\n", test.description) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T14:18:47.783", "Id": "467468", "Score": "0", "body": "Your definition of consonant clusters is a bit ad-hoc and confusing. For instance, why is `thr` treated as a consonant cluster but not `tr`, `str`, `chr`, etc.?" } ]
[ { "body": "<p><strong>UPDATE: Second Review</strong></p>\n\n<p>In my first review I said that your code may not be correct because you did not provide a pig latin specification, the algorithm used looked peculiar. I asked the you to post your pig latin specification. You did not do so. I found your pig latin specification anyway. Your code is not correct.</p>\n\n<p>The pig latin specification rules say that consonant sounds can be made up of a consonant cluster. Your code does not identify consonant clusters. Instead, you hard-code consonant clusters which occur in the test suite as string literals, for example, \"thr\", and so on.</p>\n\n<p>For example, if you add this test to the test suite, it will fail.</p>\n\n<pre><code>{\n description: \"spl consonant cluster\",\n input: \"split\",\n expected: \"itsplay\",\n},\n</code></pre>\n\n<hr>\n\n<p><strong>First Review</strong></p>\n\n<hr>\n\n<p>This is a real-world code review: Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.</p>\n\n<hr>\n\n<p>Your code fails the correctness test. </p>\n\n<p>Pig (hog) latin is not well-defined. There are several variations. For example, <a href=\"https://en.wikipedia.org/wiki/Pig_Latin\" rel=\"nofollow noreferrer\">Pig Latin - Wikipedia</a>. Without a link to the pig latin rules that you used for your code, we have no way to verify that your interpretation and code are correct.</p>\n\n<p>Post a link in your question to the pig latin rules that you used for your code.</p>\n\n<hr>\n\n<p>Writing tests is pointless if you don't run them. <code>Sentence</code> is undefined.</p>\n\n<pre><code>if pl := Sentence(test.input); pl != test.expected {\n\nigpay$ go test\n./igpay_test.go: undefined: Sentence\nigpay$ \n</code></pre>\n\n<hr>\n\n<p>You write:</p>\n\n<pre><code>result := make([]string, len(words))\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>result := make([]string, len(words, len(words))\n</code></pre>\n\n<p>Then you execute statements like</p>\n\n<pre><code>result = append(result, piggify(word, 1))\n</code></pre>\n\n<p>Then you ignore the bug with <code>strings.TrimLeft()</code></p>\n\n<pre><code>return strings.TrimLeft(strings.Join(result, \" \"), \" \")\n</code></pre>\n\n<p>Don't ignore bugs; fix bugs.</p>\n\n<p>Write</p>\n\n<pre><code>result := make([]string, 0, len(words))\n</code></pre>\n\n<p>and</p>\n\n<pre><code>return strings.Join(result, \" \")\n</code></pre>\n\n<p>Read the relevant documentation:</p>\n\n<p><a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language Specification</a> : </p>\n\n<p><a href=\"https://golang.org/ref/spec#Making_slices_maps_and_channels\" rel=\"nofollow noreferrer\">Making slices, maps and channels</a></p>\n\n<p><a href=\"https://golang.org/ref/spec#Appending_and_copying_slices\" rel=\"nofollow noreferrer\">Appending to and copying slices</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T07:53:14.580", "Id": "467536", "Score": "0", "body": "Thanks for the review. A bit painful, but useful. Although, I know nothing about real-world programming I sure get the feeling now. I will work on the code more." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T23:02:48.157", "Id": "238392", "ParentId": "238370", "Score": "3" } } ]
{ "AcceptedAnswerId": "238392", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T14:06:02.490", "Id": "238370", "Score": "2", "Tags": [ "programming-challenge", "go", "pig-latin" ], "Title": "Go pig Latin translator" }
238370
<p><a href="https://projecteuler.net/problem=11" rel="nofollow noreferrer">Project Euler 11 &mdash; Largest product in a grid</a>:</p> <blockquote> <p>In the <span class="math-container">\$20 × 20\$</span> grid below, four numbers along a diagonal line have been marked in red.</p> <pre><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 </code></pre> <p>The product of these numbers is <span class="math-container">\$26 × 63 × 78 × 14 = 1788696\$</span>.</p> <p>What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?</p> </blockquote> <p>I'm doing the <a href="https://www.freecodecamp.org/news/projecteuler100-coding-challenge-competitive-programming/" rel="nofollow noreferrer">#ProjectEuler100 challenge</a> to learn Rust. I still have lots of places where the borrow checker slaps me in the face, but that is expected; generally I just do whatever the compiler says and it's happy. I think I'm slowly working my way to understanding there.</p> <p>One thing that's been a constant unexpected pain is integer typing. It isn't clear to me how you're actually supposed to deal with integer types in practice, and what I'm doing right now is so ugly that it must be wrong.</p> <p>It was at the point where I was making my own function just to do addition that I began to suspect I'd gone off the rails. There must be a better way.</p> <p>What's the preferred way of doing this? Is there some better way than <code>as</code> to convert basic integer types?</p> <p>Here are the guts to my solution of <a href="https://projecteuler.net/problem=11" rel="nofollow noreferrer">Project Euler problem 11</a>: (The <a href="https://github.com/fizbin/pe100challenge/tree/master/problem11/src" rel="nofollow noreferrer">full solution</a> is in my GitHub repo)</p> <pre><code>fn find_elem(grid: &amp;[Vec&lt;u64&gt;], locx: usize, locy: usize) -&gt; u64 { if locx &lt; grid.len() { if locy &lt; grid[locx].len() { return grid[locx][locy]; } } 0 } fn add(lft: usize, rgt: i32) -&gt; usize { // Returns 999 on negative let ret1: i64 = (lft as i64) + (rgt as i64); if ret1 &lt; 0 { return 999; } ret1 as usize } fn search_grid(grid: &amp;[Vec&lt;u64&gt;]) -&gt; u64 { let mut max_found = 0; for direction in [(1, 0), (1, 1), (0, 1), (-1, 1)].iter() { for startx in 0..grid.len() { for starty in 0..grid[startx].len() { let result = find_elem(grid, startx, starty) * find_elem(grid, add(startx, direction.0), add(starty, direction.1)) * find_elem( grid, add(startx, 2 * direction.0), add(starty, 2 * direction.1), ) * find_elem( grid, add(startx, 3 * direction.0), add(starty, 3 * direction.1), ); if result &gt; max_found { max_found = result; } } } } max_found } </code></pre> <p>Also, if anyone could tell me how to properly pass around a two-dimensional array in Rust (I could change the outer layer to <code>&amp;[]</code>, but couldn't figure out how to change the inner layer away from being a <code>Vec</code>), that'd be good.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:57:46.670", "Id": "467480", "Score": "0", "body": "It would probably be good to expand on *how you're actually supposed to deal with integer types in practice, and what I'm doing right now is so ugly that it must be wrong* with more specifics: what exactly feels wrong, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:27:25.837", "Id": "467481", "Score": "0", "body": "What's ambiguous about \"It was at the point where I was making my own function just to do addition that I began to suspect I'd gone off the rails. There must be a better way.\" ? That, there, felt wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:29:38.297", "Id": "467482", "Score": "0", "body": "@DanielMartin Fix you meaningless question title in 1st place please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:38:30.850", "Id": "467485", "Score": "1", "body": "I'm following the explicit advice that's in the \"how to ask a question\" guide. They say that the title should say what the code is supposed to do. The purpose of the code is to solve that particular problem.\n\nI initially had \"A mess of integer types (in Rust)\", which is my actual problem (to much integer type conversion/confusion) and got downvoted for it.\n\nI'm really confused about what I'm supposed to do to satisfy the codereview SE community." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:03:41.560", "Id": "467486", "Score": "0", "body": "*and got downvoted for it* — did someone specifically state that in a previous comment? It's risky to assume connections between downvotes and anything specific otherwise. *What's ambiguous about* — I'm not saying it's ambiguous, just trying to find parts of your post that might be leading to the downvotes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:04:19.257", "Id": "467487", "Score": "1", "body": "@πάνταῥεῖ it'd be useful to point to meta guidance on post titles (if there is any) and/or say specifically what could be improved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:08:45.873", "Id": "467489", "Score": "0", "body": "That's true, I'm trying to debug the post by random changes, because I don't have any other idea why it's being downvoted. I don't know that it's the title, but I went over the guidelines after asking and getting downvoted, and according to them my initial title was bad and I couldn't find anything else against the guidelines, so..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:35:59.723", "Id": "467491", "Score": "0", "body": "But I'm now truly confused by @Shepmaster 's changes. If his changes help, then the advice given in the meta content for title is EXPLICITLY WRONG. An actual example of a good title given in that advice is \"Project Euler #18 - Max path in a triangle\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:44:57.673", "Id": "467492", "Score": "2", "body": "I assume you are referring to this [meta post](https://codereview.meta.stackexchange.com/a/2438/32521)? That makes sense, and I'll undo my changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:58:32.417", "Id": "467494", "Score": "0", "body": "Yes, that's the meta post; also, that's that's the meta post that's linked to from \"Ask Question\" -> \"Guide to asking questions\" -> \"When you ask\". Maybe the meta post is out of date? Maybe community tastes have changed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T01:45:38.933", "Id": "467522", "Score": "1", "body": "The name of the challenge does not automatically reflect the contents of the challenge. I've added the problem description for you. In the future please do this yourself to prevent DVs and CVs." } ]
[ { "body": "<p>Code review:<br>\n1. You don't need to use <code>u64</code>, since the input data is all <code>u8</code>, so use <code>Vec&lt;u8&gt;</code> like the following code and parse all the input data in one line:</p>\n\n<pre><code>fn main() {\n let s = \"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\";\n let grid: Vec&lt;u8&gt; = s.split_whitespace().map(|v| v.parse().unwrap()).collect();\n let mut max = 0;\n for row in 0..20 {\n for col in 0..20 {\n for direction in &amp;[(0, 1), (1, 0), (1, -1), (1, 1)] {\n max = std::cmp::max(max, mul_4_adj(&amp;grid, row, col, direction));\n }\n }\n }\n println!(\"max={}\", max); // 70600674\n}\n// Calculate the product of four adjacent numbers in the same direction:\nfn mul_4_adj(grid: &amp;[u8], mut r: usize, mut c: usize, direction: &amp;(i8, i8)) -&gt; u32 {\n let mut f = 1;\n for _ in 0..4 {\n f *= grid[20 * r + c] as u32;\n let (row, col) = (r as i8 + direction.0, c as i8 + direction.1);\n if row &lt; 0 || row &gt;= 20 || col &lt; 0 || col &gt;= 20 {\n return 0;\n }\n r = row as usize;\n c = col as usize;\n }\n f\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>Using <a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.chunks\" rel=\"nofollow noreferrer\">chunks</a> with the <code>CHUNK_SIZE</code> of 20, instead of <code>grid: &amp;[Vec&lt;u64&gt;]</code> use <code>grid: &amp;[&amp;[u8]]</code>:</li>\n</ol>\n\n<pre><code>fn main() {\n let s = \"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\";\n let v: Vec&lt;u8&gt; = s.split_whitespace().map(|v| v.parse().unwrap()).collect();\n let grid: Vec&lt;_&gt; = v.chunks(20).collect();\n let mut max = 0;\n for row in 0..grid.len() {\n for col in 0..grid[row].len() {\n for direction in &amp;[(0, 1), (1, 0), (1, -1), (1, 1)] {\n max = std::cmp::max(max, mul_4_adj(&amp;grid, row, col, direction));\n }\n }\n }\n println!(\"max={}\", max); // 70600674\n}\n// Calculate the product of four adjacent numbers in the same direction:\nfn mul_4_adj(grid: &amp;[&amp;[u8]], mut r: usize, mut c: usize, direction: &amp;(i8, i8)) -&gt; u32 {\n let mut f = 1;\n for _ in 0..4 {\n f *= grid[r][c] as u32;\n let (row, col) = (r as i8 + direction.0, c as i8 + direction.1);\n r = row as usize;\n c = col as usize;\n if row &lt; 0 || col &lt; 0 || r &gt;= grid.len() || c &gt;= grid[r].len() {\n return 0;\n }\n }\n f\n}\n\n</code></pre>\n\n<hr>\n\n<ol start=\"3\">\n<li>Also instead of <code>Vec&lt;Vec&lt;u64&gt;&gt;</code> you may use a two-dimensional array in Rust:</li>\n</ol>\n\n<pre><code>let mut grid = [[0_u8; 20]; 20];\n</code></pre>\n\n<p>Then simply find and print the max:</p>\n\n<pre><code>fn main() {\n let gridstr = r#\"\n08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\n\"#;\n let mut grid = [[0_u8; 20]; 20];\n let lines: Vec&lt;_&gt; = gridstr.trim().split(\"\\n\").collect();\n for row in 0..20 {\n let line: Vec&lt;_&gt; = lines[row].trim().split_whitespace().collect();\n for col in 0..20 {\n grid[row][col] = line[col].parse().unwrap();\n }\n }\n\n let mut max = 0;\n for row in 0..20 {\n for col in 0..20 {\n for direction in &amp;[(0, 1), (1, 0), (1, -1), (1, 1)] {\n max = std::cmp::max(max, mul_4_adj(&amp;grid, row, col, direction));\n }\n }\n }\n println!(\"max={}\", max); // 70600674\n}\n// Calculate the product of four adjacent numbers in the same direction:\nfn mul_4_adj(grid: &amp;[[u8; 20]; 20], mut r: usize, mut c: usize, direction: &amp;(i8, i8)) -&gt; u32 {\n let mut f = 1;\n for _ in 0..4 {\n f *= grid[r][c] as u32;\n let (row, col) = (r as i8 + direction.0, c as i8 + direction.1);\n if row &lt; 0 || row &gt;= 20 || col &lt; 0 || col &gt;= 20 {\n return 0;\n }\n r = row as usize;\n c = col as usize;\n }\n f\n}\n\n</code></pre>\n\n<ol start=\"4\">\n<li>Also you may use grid directly:</li>\n</ol>\n\n<pre><code>let grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08, ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00, ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65, ], [ 52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91, ], [ 22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80, ], [ 24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50, ], [ 32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70, ], [ 67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21, ], [ 24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72, ], [ 21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95, ], [ 78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92, ], [ 16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57, ], [ 86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58, ], [ 19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40, ], [ 04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66, ], [ 88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69, ], [ 04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36, ], [ 20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16, ], [ 20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54, ], [ 01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48, ], ];\n</code></pre>\n\n<ol start=\"5\">\n<li>You don't need extra parenthesis and <code>: i64</code> here:</li>\n</ol>\n\n<pre><code>let ret1: i64 = (lft as i64) + (rgt as i64);\n</code></pre>\n\n<p>This works:</p>\n\n<pre><code>let ret1 = lft as i64 + rgt as i64;\n</code></pre>\n\n<ol start=\"6\">\n<li><p>Use <code>for _ in 0..4</code> instead of four <code>find_elem(...)</code> as the above examples.</p></li>\n<li><p>You may use <code>u32</code> instead of <code>u64</code>, since <code>255 * 255 * 255 * 255 = 4_228_250_625 = 0xfc05_fc01</code> for the product of four adjacent numbers.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T01:19:30.957", "Id": "467519", "Score": "0", "body": "I don't think you want `break` s in `mul_4_adj`, but rather `return 0` - imagine a 3x3 block in the corner with very large values but surrounded by zeros on all sides." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T01:22:36.070", "Id": "467520", "Score": "0", "body": "Is there any way to not refer to `Vec`s after I finish parsing without hard coding the size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:19:00.290", "Id": "467542", "Score": "0", "body": "Yes, see the new edit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T22:01:32.587", "Id": "238389", "ParentId": "238374", "Score": "1" } }, { "body": "<p>I accepted the answer that gave me a bunch of good ideas; here's the final form I ended up with. I'm mostly happy with it, except for the use of the <code>move</code> keyword. I don't understand what that's doing and only added it when the compiler told me to. Specifically, I don't understand why it's needed with this code, but wasn't needed with some simple variants. Maybe I'll ask about that on stackoverflow.</p>\n\n<p>Anyway:</p>\n\n<pre><code>fn parse_grid(gridstr: &amp;str) -&gt; Vec&lt;Vec&lt;u8&gt;&gt; {\n gridstr\n .trim()\n .split(\"\\n\")\n .map(|line| {\n line.trim()\n .split_whitespace()\n .map(|numstr| numstr.parse().expect(\"Expected a u8\"))\n .collect()\n })\n .collect()\n}\n\nfn main() {\n let gridstr = r#\"\n08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\n\"#;\n let gridholder = parse_grid(gridstr);\n let grid: Vec&lt;&amp;[u8]&gt; = gridholder.iter().map(|x| &amp;x[..]).collect();\n\n println!(\"{}\", search_grid(&amp;grid));\n}\n\nfn find_elem(grid: &amp;[&amp;[u8]], locx: isize, locy: isize) -&gt; u64 {\n if locx &gt;= 0 &amp;&amp; (locx as usize) &lt; grid.len() {\n if locy &gt;= 0 &amp;&amp; (locy as usize) &lt; grid[locx as usize].len() {\n return u64::from(grid[locx as usize][locy as usize]);\n }\n }\n 0\n}\n\nfn prod_4(grid: &amp;[&amp;[u8]], startx: usize, starty: usize, dirx: isize, diry: isize) -&gt; u64 {\n let mut istartx = startx as isize;\n let mut istarty = starty as isize;\n let mut prod: u64 = 1;\n for _ in 0..4 {\n prod *= find_elem(grid, istartx, istarty);\n istartx += dirx;\n istarty += diry;\n }\n prod\n}\n\nfn search_grid(grid: &amp;[&amp;[u8]]) -&gt; u64 {\n let directions = [(1, 0), (1, 1), (0, 1), (-1, 1)];\n directions\n .iter()\n .flat_map(move |dir| {\n (0..grid.len()).flat_map(move |startx| {\n (0..grid[startx].len())\n .map(move |starty| prod_4(grid, startx, starty, dir.0, dir.1))\n })\n })\n .max()\n .unwrap_or(0)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T01:37:51.727", "Id": "238462", "ParentId": "238374", "Score": "0" } } ]
{ "AcceptedAnswerId": "238389", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T15:22:10.923", "Id": "238374", "Score": "0", "Tags": [ "programming-challenge", "rust" ], "Title": "Largest product in a grid: Project Euler 11" }
238374
<p>I'm very new to Entity Framework Core, so I'm concerned about whether I've done this query in the most efficient way possible.</p> <p>The database I'm querying looks like this:</p> <p><a href="https://i.stack.imgur.com/DPQ4x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DPQ4x.png" alt="enter image description here"></a></p> <p>Basically, <code>UserRoles</code> is a a "linking table" between the <code>User</code> and the <code>Roles</code> in order to create a one-to-many relationship. If a user exists at all, they will always have at least one role, but they could have several roles.</p> <p>I want to get the role name based on the NT ID of the user.</p> <p>This is something I plan to do fairly often, so I separated it out into a separate utility (rather than having it in the controller).</p> <p>In SQL, I'd just do two <code>inner join</code>s. However, what I did here is to query <code>UserRoles</code> (rather than using <code>Join</code>).</p> <pre><code>public class UserUtilities { public static List&lt;Roles&gt; GetRoles(string ntid) { var ctx = new MyLiveDocsContext(); List&lt;Roles&gt; roles = (from ur in ctx.UserRoles where ur.User.Ntid == ntid select ur.Role).ToList(); return roles; } } </code></pre> <p>Ive tested this and it does what I want, but I'm wondering if this is the best way to do this. For example, would it be better to use an explicit <code>join</code> instead?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T06:17:06.477", "Id": "467530", "Score": "1", "body": "Did you check what SQL queries are produced by this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:07:58.693", "Id": "467584", "Score": "0", "body": "Also note: [\"The lifetime of the context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use `using` if you want all the resources that the context controls to be disposed at the end of the block.\"](https://docs.microsoft.com/en-us/ef/ef6/fundamentals/working-with-dbcontext)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:52:40.007", "Id": "467610", "Score": "0", "body": "@BCdotWEB Is the new title better?" } ]
[ { "body": "<p>For this isolated piece of code, this is the way to go. Generally, in ORMs that support LINQ, navigation properties (like <code>ur.Roles</code>) should be used wherever possible. Using<code>join</code> should be reserved for custom joins where no navigation properties exist.</p>\n\n<p>Reasons: </p>\n\n<ol>\n<li><p>Joins are far more verbose than navigation properties, making code harder to read and causing repetitive code.</p></li>\n<li><p>Joins are error-prone. It's easy to match the wrong fields. A navigation property, once configured correctly, will always generate a correct SQL join.</p></li>\n<li><p>Navigation properties, if well-named, are more expressive. In a <code>join</code> the cardinality of a relationship isn't always obvious. In navigation properties it is. You know what you're looking at when reading <code>Role</code> vs <code>Roles</code>. Unfortunately, sometimes people tend to be sloppy in this area and they just use the generated class and property names as an ORM generated them, which may result in any mixture of plural class names, plural reference property names, and singular collection property names.</p></li>\n</ol>\n\n<p>One exception to this rule is when you want to overrule the ORM's SQL generation. Entity Framework will generate an <code>OUTER JOIN</code> for non-required navigation properties (i.e. where the \"1\"-side is optional, 0..1-n, 0..1-1). There may be cases where <code>INNER JOIN</code> performs better and the results with <code>null</code> navigation properties aren't interesting anyway. In those cases, using a manual <code>join</code>, overriding a navigation property, could be considered.</p>\n\n<p>Side note: as said in a comment, it's recommended to use disposable objects, like a <code>DbContext</code>, in a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\"><code>using</code> statement</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T09:28:28.383", "Id": "238816", "ParentId": "238376", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T17:50:40.823", "Id": "238376", "Score": "1", "Tags": [ "c#", "beginner", "asp.net-core", ".net-core", "entity-framework-core" ], "Title": "Three-way join in Entity Framework Core to retrieve all roles that a user has" }
238376
<p>This piece of code is supposed to walk through a TLV string and print out its contents. For this particular example, tag field length is 2, size field length is 3.</p> <p>As a mostly C programmer, this is what I came up with. I know I can parametrize the tag and length field sizes, but I don't care about that right now. Just interested to know the more pythonic way of parsing the string.</p> <pre><code>tlv = "01011Lorem ipsum02014dolor sit amet03027consectetur adipiscing elit" temp = tlv[:] while len(temp): print('tag: {}'.format(temp[0:2])) print('length: {}'.format(temp[2:2+3])) tam = int(temp[2:2+3]) print('value: \'{}\'\n'.format(temp[5:5+tam])) temp = temp[5+tam:] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T07:55:47.653", "Id": "467537", "Score": "0", "body": "I'm assuming we're talking about the TLV as in the 802.1AB standard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:27:34.327", "Id": "467592", "Score": "0", "body": "@Mast, no. In this case it is just a string with tag, length and value fields represented in ascii." } ]
[ { "body": "<p>Some initial comments:</p>\n\n<ul>\n<li>Good use of string slicing to extract each field, though ideally we should not need to make a copy of the string. I propose a different way of doing this below.</li>\n<li><code>while len(temp):</code> works, but a more Pythonic way of writing this would be <code>while temp:</code> because <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"nofollow noreferrer\">any object can be tested for a truth value in Python, and non-empty strings evaluate to true</a>.</li>\n<li>A popular new way of string interpolation introduced in Python 3.6 is the <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals\" rel=\"nofollow noreferrer\">f-string</a>. So instead of <code>'tag: {}'.format(temp[0:2])</code> you could do <code>f'tag: {temp[0:2]}'</code> which I personally find much easier to read.</li>\n</ul>\n\n<p>To avoid copying the string <code>tlv</code> we can instead work with an iterator over the characters in the string, i.e. <code>iter(tlv)</code>. Then we can use <code>itertools</code>, a nice built-in library for working with iterators, specifically <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> to extract/consume chunks of arbitrary length from the iterator:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from itertools import islice\n\nTAG_FIELD_LENGTH = 2\nLENGTH_FIELD_LENGTH = 3\n\ndef tlv_parser(tlv_string):\n it = iter(tlv_string)\n while tag := \"\".join(islice(it, TAG_FIELD_LENGTH)):\n length = int(\"\".join(islice(it, LENGTH_FIELD_LENGTH)))\n value = \"\".join(islice(it, length))\n yield (tag, length, value)\n</code></pre>\n\n<p>Notes on the above:</p>\n\n<ul>\n<li>The strategy of parsing is very similar to yours, with the only difference being that we're working with an iterator of characters, and we're consuming from the iterator chunk by chunk so we don't need to calculate indices for field boundaries.</li>\n<li>We're concatenating the characters in each iterator to a string with <code>\"\".join(...)</code>, i.e. <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\">str.join</a>.</li>\n<li><code>:=</code> is the <a href=\"https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions\" rel=\"nofollow noreferrer\">\"walrus operator\"</a> (introduced in Python 3.8) that binds values to variables as part of a larger expression, so we're binding the value of <code>\"\".join(islice(it, TAG_FIELD_LENGTH))</code> to <code>tag</code> and at the same time testing its truth value.</li>\n<li>The <code>yield</code> keyword makes <code>tlv_parser</code> a <a href=\"https://docs.python.org/3/glossary.html#term-generator\" rel=\"nofollow noreferrer\">generator</a> of 3-tuples of (tag, length, value).</li>\n</ul>\n\n<p>Example usage:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>&gt;&gt;&gt; tlv = \"01011Lorem ipsum02014dolor sit amet03027consectetur adipiscing elit\"\n\n&gt;&gt;&gt; for t in tlv_parser(tlv):\n... print(t)\n... \n('01', 11, 'Lorem ipsum')\n('02', 14, 'dolor sit amet')\n('03', 27, 'consectetur adipiscing elit')\n\n&gt;&gt;&gt; for tag, length, value in tlv_parser(tlv):\n... print(f\"tag: {tag}\")\n... print(f\"length: {length}\")\n... print(f\"value: {value!r}\\n\")\n... \ntag: 01\nlength: 11\nvalue: 'Lorem ipsum'\n\ntag: 02\nlength: 14\nvalue: 'dolor sit amet'\n\ntag: 03\nlength: 27\nvalue: 'consectetur adipiscing elit'\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:14:15.367", "Id": "238412", "ParentId": "238377", "Score": "3" } } ]
{ "AcceptedAnswerId": "238412", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:04:24.567", "Id": "238377", "Score": "2", "Tags": [ "python", "python-3.x", "parsing" ], "Title": "Parsing a TLV string" }
238377
<p><strong>Following on from my previous question:</strong> <a href="https://codereview.stackexchange.com/q/238338">C pointer based growable stack</a></p> <p>I have made some improvements (<em>hopefully!</em>) based on the very helpful comments and suggestions. I have checked that the stack can push and pop doubles now, so hopefully it will also be OK with structs.</p> <p>I have a could of questions regarding the changes I have made:</p> <ol> <li>I noticed <code>memcpy()</code> didn't work with <code>void *</code> so I switched to using <code>uin8_t</code>; is that recommended/necessary or could I have cast to <code>uint8_t</code> for <code>memcpy()</code>? Not sure which approach is the best...</li> <li>How should a failed <code>malloc()</code>/<code>realloc()</code> be handled? Return an error code? Exit? Return NULL?</li> </ol> <p>Again, I would greatly appreciate any suggestions/criticism:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #define MAX_ITEMS 16 typedef struct { uint8_t *data; size_t itemSize; unsigned count; unsigned capacity; } Stack; void stack_init(Stack *stack, size_t itemSize, unsigned capacity); bool stack_is_empty(const Stack *stack); void stack_push(Stack *stack, void *item); void* stack_pop(Stack *stack); void stack_destroy(Stack *stack); void stack_init(Stack *stack, size_t itemSize, unsigned capacity) { unsigned initialCapacity = capacity == 0 ? 1 : capacity; size_t size = initialCapacity * itemSize; stack-&gt;count = 0; stack-&gt;capacity = initialCapacity; stack-&gt;itemSize = itemSize; stack-&gt;data = (uint8_t *)malloc(size); if (stack-&gt;data == NULL) { // TODO } memset(stack-&gt;data, 0, size); } bool stack_is_empty(const Stack *stack) { return stack-&gt;count == 0; } void stack_push(Stack *stack, void *item) { if (stack-&gt;count &gt;= stack-&gt;capacity) { stack-&gt;capacity *= 2; stack-&gt;data = (uint8_t *)realloc(stack-&gt;data, stack-&gt;capacity * stack-&gt;itemSize); if (stack-&gt;data == NULL) { // TODO } } unsigned offset = stack-&gt;count * stack-&gt;itemSize; memcpy(stack-&gt;data + offset, item, stack-&gt;itemSize); stack-&gt;count++; } void* stack_pop(Stack *stack) { if (stack_is_empty(stack) == true) { // TODO } uint8_t *item = (uint8_t *)malloc(stack-&gt;itemSize); if (item == NULL) { // TODO } stack-&gt;count--; unsigned offset = stack-&gt;count * stack-&gt;itemSize; memcpy(item, stack-&gt;data + offset, stack-&gt;itemSize); return (void *)item; } void stack_destroy(Stack *stack) { free(stack-&gt;data); stack-&gt;count = 0; } int main(void) { Stack stack; stack_init(&amp;stack, sizeof(int), 0); for (int i = 0; i &lt; MAX_ITEMS; i++) { stack_push(&amp;stack, (void *)&amp;i); } while (!stack_is_empty(&amp;stack)) { int value; value = *((int *)stack_pop(&amp;stack)); printf("%d\n", value); } stack_destroy(&amp;stack); } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code> stack-&gt;data = (uint8_t *)realloc(stack-&gt;data, stack-&gt;capacity * stack-&gt;itemSize);\n</code></pre>\n</blockquote>\n\n<p>This is wrong, because if <code>realloc()</code> failed, then there's now no way to access the memory previously pointed to by <code>stack-&gt;data</code>. The correct pattern for <code>realloc()</code> is:</p>\n\n<pre><code>void *newData = realloc(stack-&gt;data, stack-&gt;capacity * stack-&gt;itemSize);\nif (!newData) {\n // Insert error handling - you'll want to restore the old stack-&gt;capacity here\n // or (better) wait until we're okay before updating.\n return FAILURE:\n}\nstack-&gt;data = newData;\n</code></pre>\n\n<hr>\n\n<p>I recommend against casting the result of <code>malloc()</code> family when assigning - these functions return <code>void*</code>, which is assignable to any pointer type without a cast. The unnecessary cast just distracts the reader (because casts generally indicate danger areas in code). The same is true for conversions from pointer types to <code>void*</code>, such as this one:</p>\n\n<blockquote>\n<pre><code>return (void *)item;\n</code></pre>\n</blockquote>\n\n<p>That can simply be</p>\n\n<pre><code>return item;\n</code></pre>\n\n<hr>\n\n<p>The <code>stack_pop</code> interface is difficult to use - callers have to deal with possible null pointer return, and must remember to <code>free()</code> the result. Instead, consider having the caller provide memory to write into:</p>\n\n<pre><code>void stack_pop(Stack *stack, void *target);\n</code></pre>\n\n<p>The caller should already know the size required for <code>target</code>, and can now get results in local (<code>auto</code>) storage:</p>\n\n<pre><code>int foo;\nstack_pop(&amp;stack, &amp;foo);\n// no need to check for null, or to call free()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:49:28.493", "Id": "238381", "ParentId": "238380", "Score": "5" } } ]
{ "AcceptedAnswerId": "238381", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T18:35:17.610", "Id": "238380", "Score": "4", "Tags": [ "c", "stack", "pointers" ], "Title": "C pointer based growable stack rev2" }
238380
<p>I'm new to Java8 and I must find an elegant solution to a problem. The problem goes I have a List of letters (of any size) that could contain any letter such as "A", "B", "C", "D", etc. I must check if I have an pair of "A" and "B". So, if I have something like ["A", "A", "C", "Z"], since I don't have both "A" and "B" the code should throw an error. I need to refactor something like this in java8...</p> <pre><code>import java.util.Arrays; import java.util.List; public class atest { public static void checkForABPair(List&lt;String&gt; letters) { int iA = 0; int iB = 0; for (String letter : letters) { if (letter.equals("A")) { iA = 1; } if (letter.equals("B")) { iB = 1; } } if ((1 == iA || 1 == iB) &amp;&amp; (1 != iA || 1 != iB)) { System.out.println(letters + " - ERROR! The pair of letters [A - B] must be present at least once, or not at all!"); } else { System.out.println(letters + " - Everything fine!"); } } public static void main(String[] args) { List&lt;String&gt; letters = Arrays.asList("B", "A", "C"); checkForABPair(letters); letters = Arrays.asList("A", "A", "C"); checkForABPair(letters); letters = Arrays.asList("M", "S", "C"); checkForABPair(letters); } } </code></pre> <p>This must return the following:</p> <pre><code>[B, A, C] - Everything fine! [A, A, C] - ERROR! The pair of letters [A - B] must be present at least once, or not at all! [M, S, C] - Everything fine! </code></pre> <p>I need it done in a more elegant way. Anyone have a more elegant solution? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:36:33.443", "Id": "467495", "Score": "1", "body": "For clarification: Does the list `[\"A\", \"C\", \"B\"]` contain a pair of A and B?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:39:14.413", "Id": "467496", "Score": "0", "body": "yes, it has one A and one B. it should have at least one A and one B. If it doesn't have any of them it shouldn't throw any error..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:42:20.210", "Id": "467498", "Score": "5", "body": "Also, \"I solved it something like this\" almost makes your question off-topic. This site is about reviewing real-life code, not hypothetic code. It's better to post the _complete_ code you wrote, including any `class` declarations and `import` directives." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:49:03.490", "Id": "467499", "Score": "0", "body": "ok, I'll post the complete code in some minutes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T21:23:05.560", "Id": "467503", "Score": "1", "body": "What about `[A, A, B]`? It contains both A and B, but their counts are not equal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:10:37.660", "Id": "467567", "Score": "0", "body": "Was this part of a programming challenge of sorts? Since this doesn't make much sense otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:56:03.487", "Id": "467572", "Score": "0", "body": "No, I'm really using this, and the one who is doing the code review is quite pretentious. I isolated the code with a small example, of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T16:28:11.687", "Id": "467613", "Score": "0", "body": "Wouldn't it be simpler to ask <List>.contains('A') and <List>.contains('B') and comparing said booleans results to be true ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T16:29:38.997", "Id": "467614", "Score": "0", "body": "`letters.containsAll(Set.of(\"A\", \"B\"))` works and will have performance comparable to the other solutions here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T16:30:57.077", "Id": "467615", "Score": "0", "body": "was about to point to containsAll too @JoeLee-Moyet after looking at the List docu at oracle\n\nbut I guess he is scared if they occur more than once in the list which means an error too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T16:35:04.320", "Id": "467616", "Score": "0", "body": "Hmm, looking again, it looks like the desired logic is `letters.contains(\"A\") == letters.contains(\"B\")` (which is basically what you said above!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T18:54:47.540", "Id": "467629", "Score": "0", "body": "Well, @AJNeufeld solution with the two allOrNone methods is the best fit for me. Thank you all for your answers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T19:41:40.950", "Id": "467640", "Score": "0", "body": "Why does `[M, S, C]` works in your example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T06:43:38.320", "Id": "467683", "Score": "0", "body": "Because has none of A and B. I'm using this to test if I configured both A and B for some filtering into an XML. A and B are in fact two attributes, let's say you cannot configure Name without Surname, but you can configure Address or other available attributes. As I have separate Name and Surname, I have to check that both are configured for my filter to work properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T09:16:55.353", "Id": "467690", "Score": "0", "body": "@WDrgn: I would suggest that you add all the relevant information to your question itself, with an [edit]. The question can be reopened if it *clear* and has *sufficient context.*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T10:17:51.740", "Id": "467697", "Score": "0", "body": "well, but I have my answer (marked as the accepted one). Thank you very much for all the answers!" } ]
[ { "body": "<p><code>iA</code> and <code>iB</code> can only take the values <code>0</code> and <code>1</code>, so that</p>\n\n<pre><code>if ((1 == iA || 1 == iB) &amp;&amp; (1 != iA || 1 != iB)) { ... }\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>if (iA != iB) { ... }\n</code></pre>\n\n<p>Boolean variables would be more appropriate for this purpose, and the variable names can be improved, e.g.</p>\n\n<pre><code>boolean containsA = false;\nboolean containsB = false;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T21:12:38.537", "Id": "238386", "ParentId": "238382", "Score": "12" } }, { "body": "<p>I have some suggestions for you.</p>\n\n<ol>\n<li><p>Instead of using list, I suggest that you use <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html\" rel=\"nofollow noreferrer\"><code>varargs</code></a>; this will remove the need to put the item in list and pass them to the method.</p></li>\n<li><p>Instead of using <code>String</code>, you can use the <code>Character</code> to reduce, by a bit, the memory footprint.</p></li>\n<li><p>In the <code>for</code> loop, I highly suggest that you use the <code>if-else-if</code> pattern or a <code>switch</code> instead of the <code>if-if</code> since you can only have one choice each time. </p></li>\n</ol>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char letter : letters) {\n if (letter == 'A') {\n iA = 1;\n }\n if (letter == 'B') {\n iB = 1;\n }\n}\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char letter : letters) {\n if (letter == 'A') {\n iA = 1;\n } else if (letter == 'B') {\n iB = 1;\n }\n}\n</code></pre>\n\n<p><em>or</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char letter : letters) {\n switch (letter) {\n case 'A':\n iA = 1;\n break;\n case 'B':\n iB = 1;\n break;\n }\n}\n</code></pre>\n\n<ol start=\"4\">\n<li>When printing arrays, you can use the <code>java.util.Arrays#toString</code> method.</li>\n</ol>\n\n<h3>Refactored Code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n checkForABPair('B', 'A', 'C');\n checkForABPair('A', 'A', 'C');\n checkForABPair('M', 'S', 'C');\n}\n\npublic static void checkForABPair(char... letters) {\n int iA = 0;\n int iB = 0;\n\n for (char letter : letters) {\n switch (letter) {\n case 'A':\n iA = 1;\n break;\n case 'B':\n iB = 1;\n break;\n }\n }\n\n if ((1 == iA || 1 == iB) &amp;&amp; (1 != iA || 1 != iB)) {\n System.out.println(Arrays.toString(letters) + \" - ERROR! The pair of letters [A - B] must be present at least once, or not at all!\");\n } else {\n System.out.println(Arrays.toString(letters) + \" - Everything fine!\");\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T22:49:24.037", "Id": "238391", "ParentId": "238382", "Score": "4" } }, { "body": "<p>Are you searching for letters (<code>'A'</code> and <code>'B'</code>) or strings (<code>\"A\"</code> and <code>\"B\"</code>)? You title says \"pair of Strings in a List\", but your code's variables are <code>letter</code> and <code>letters</code>.</p>\n\n<hr>\n\n<p>You have hard-coded the search for the strings <code>\"A\"</code> and <code>\"B\"</code>. Are these the only two you will look for? Might you want to search for <code>\"C\"</code> and <code>\"D\"</code>? Is the condition \"all\" or \"none\", in which case, you could also test for all or none of <code>\"X\"</code>, <code>\"Y\"</code> and <code>\"Z\"</code>!</p>\n\n<hr>\n\n<p>You have no early termination. If you have 1,000,000,000 entries in the list, and both <code>\"A\"</code> and <code>\"B\"</code> are found in the first dozen entries, your <code>for (String letter : letters)</code> loop will still continue to the bitter end of the list. This is wasting time.</p>\n\n<p>You could break out of the loop if, when one of the letters is found it is determined the other has already been found:</p>\n\n<pre><code> for (String letter : letters) {\n if (letter.equals(\"A\")) {\n iA = 1;\n if (iB == 1)\n break;\n } else if (letter.equals(\"B\")) {\n iB = 1;\n if (iA == 1)\n break;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Here is an \"Elegant\"(?) stream solution for an \"all\" or \"none\" search in a list of strings for a given search set of two or more strings:</p>\n\n<pre><code>public static boolean allOrNone(Collection&lt;String&gt; strings, String... search_set) {\n return allOrNone(strings, new HashSet&lt;&gt;(Arrays.asList(search_set)));\n}\n\npublic static boolean allOrNone(Collection&lt;String&gt; strings, Set&lt;String&gt; search_set) {\n long all = search_set.size();\n long occurrences = strings.stream().filter(search_set::contains)\n .distinct()\n .limit(all)\n .count();\n return occurrences == 0 || occurrences == all;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>The <code>.filter(search_set::contains)</code> stage will only pass on <code>strings</code> which are in the <code>search_set</code> to the next stage of the pipeline.</li>\n<li>The <code>.distinct()</code> stage will prevent duplicates from continuing down the pipeline.</li>\n<li>The <code>.limit(all)</code> stage allows for early termination of the stream. If <code>search_set</code> contains 2 items, when 2 items have made it past the <code>filter</code> &amp; <code>distinct</code> stages, we must have encountered all of the search items.</li>\n<li>The <code>.count()</code> totals the number of strings which made it through all stages of the pipeline ... the unique strings found in the search set.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T00:03:43.653", "Id": "238395", "ParentId": "238382", "Score": "10" } } ]
{ "AcceptedAnswerId": "238395", "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T19:23:03.983", "Id": "238382", "Score": "6", "Tags": [ "java", "strings" ], "Title": "Elegant solution to find a pair of Strings in a List" }
238382
<p>Tried this leetcode question Hands of Straights. <a href="https://leetcode.com/problems/hand-of-straights/" rel="nofollow noreferrer">https://leetcode.com/problems/hand-of-straights/</a> Description is Alice has a hand of cards, given as an array of integers.</p> <p>Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.</p> <p>Return true if and only if she can.</p> <pre><code>Example 1. Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]. Example 2 Input: hand = [1,2,3,4,5], W = 4 Output: false Explanation: Alice's hand can't be rearranged into groups of 4. </code></pre> <p>My attempt to solve it using Haskell is here. Can someone review it. The code returns the correct values for most of the test cases that I have tried.</p> <pre><code>import Data.List {- solve 3 [1,1,2,2,2,3,3,3,4] True solve 3 [1,1,2,2,2,3,3,3] False solve 4 [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4] True -} solve::Int -&gt; [Int] -&gt; Bool solve v xss = helper v $ group $ sort xss helper::Int -&gt;[[Int]] -&gt; Bool helper v [] = True helper v xss = let (a, b) = splitAt v xss in case verify a &amp;&amp; ((length a) `mod` v == 0) of True -&gt; helper v $ (removeHead a []) ++ b False -&gt; False verify::[[Int]] -&gt; Bool verify [] = True verify (x:[]) = True verify (x:y:zx) | head y == succ (head x) = verify $ y:zx | otherwise = False removeHead::[[Int]] -&gt; [[Int]]-&gt; [[Int]] removeHead [] acc = acc removeHead (x:xss) acc = case null (tail x) of True -&gt; removeHead xss acc False -&gt; removeHead xss (acc ++ [tail x]) </code></pre>
[]
[ { "body": "<p>Lines like <code>False -&gt; False</code> indicate that there is a better way.</p>\n\n<pre><code>helper :: Int -&gt; [[Int]] -&gt; Bool\nhelper v [] = True\nhelper v xss = let (a, b) = splitAt v xss \n in verify a &amp;&amp; length a `mod` v == 0 -- length a &lt;= v, so why not just length a == v?\n &amp;&amp; helper v (removeHead a [] ++ b)\n\nremoveHead :: [[Int]] -&gt; [[Int]] -&gt; [[Int]]\nremoveHead [] acc = acc\nremoveHead (x:xss) acc = removeHead xss\n $ acc ++ [tail x | not $ null $ tail x]\n</code></pre>\n\n<p>Left folds like <code>removeHead</code> can often be turned into right folds:</p>\n\n<pre><code>removeHead :: [[Int]] -&gt; [[Int]]\nremoveHead [] = []\nremoveHead (x:xss) = [tail x | not $ null $ tail x] ++ removeHead xss\n</code></pre>\n\n<p><code>removeHead</code> needs no explicit recursion. <code>Data.List.NonEmpty</code> lets us avoid partial functions (and giving verify a name :) ).</p>\n\n<pre><code>import Data.List.NonEmpty\n\nsolve :: Int -&gt; [Int] -&gt; Bool\nsolve v = helper v . NE.group . sort\n\nhelper :: Int -&gt; [NE.NonEmpty Int] -&gt; Bool\nhelper v [] = True\nhelper v xss =\n let (a, b) = splitAt v xss\n (straight, a') = unzip $ map NE.uncons a\n in all (==1) (zipWith subtract straight (tail straight))\n &amp;&amp; length a == v\n &amp;&amp; helper v (catMaybes a' ++ b)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T04:37:51.273", "Id": "467526", "Score": "0", "body": "Thanks Gurkenglas. Can you explain how `[x | _:x@(_:_) <- a]` works" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T07:57:56.157", "Id": "467538", "Score": "0", "body": "I guess line 4 should be in it's own function `verify xss = let k = map head xss in\n all (==1) (zipWith subtract k (tail k))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:03:33.233", "Id": "467561", "Score": "0", "body": "`[x | _:x@(_:_) <- a]` is the tail of each element of `a` that has length at least two. That said, pattern matches that logically can't fail but by the types can are smelly. Edited." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T03:02:40.123", "Id": "238398", "ParentId": "238390", "Score": "1" } } ]
{ "AcceptedAnswerId": "238398", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-04T22:22:58.393", "Id": "238390", "Score": "1", "Tags": [ "haskell" ], "Title": "Hands of Straights (LeetCode) Arrange the card" }
238390
<p>I'm trying to write a class that simplifies the most common operations with arrays and then I want to distribute... Maybe it can help someone... </p> <p>But I'm facing some problems in make the object simple to use and intuitive.</p> <p>Here a summary of the public methods:</p> <ul> <li><strong>Array to range</strong></li> <li><strong>Array to string</strong></li> <li><strong>Array to text file</strong></li> <li><strong>Array Filter</strong></li> <li><strong>Merge Arrays</strong></li> <li><strong>Range to array</strong></li> <li><strong>Array Sort</strong></li> <li><strong>String to array</strong></li> <li><strong>Text file to array</strong></li> <li><strong>Transpose</strong></li> </ul> <p><strong>Array Filter:</strong> Here I have to allow the user to set the filters he needs and that means allow public methods that mean nothing outside the filter method.</p> <p>Those are the methods:</p> <ul> <li>FilterIncludeEquals</li> <li>FilterExcludeEquals</li> <li>FilterIncludeIfBetween</li> <li>FilterIncludeIfContains</li> </ul> <p>and then:</p> <ul> <li>FilterApplyTo</li> </ul> <p>How To use (complete code on class module named ArrayManipulation): </p> <pre><code>Public Sub Test() Dim testObject As ArrayManipulation Set testObject = New ArrayManipulation Dim arrayOfNumbers As Variant ReDim arrayOfNumbers(12) Dim numbers As Long For numbers = 0 To 11 arrayOfNumbers(numbers) = numbers Next With testObject ' setup filters .FilterExcludeEquals 3, 0 'column is not considered for 1d arrays .FilterIncludeIfBetween 1, 4, 0 ' filter the array .FilterApplyTo arrayOfNumbers ' this create a txt file storing the array .ArrayToTextFile arrayOfNumbers, Environ("USERPROFILE") &amp; "\Desktop\Test.txt" ' this read the array from the just created file .TextFileToArray Environ("USERPROFILE") &amp; "\Desktop\Test.txt", arrayOfNumbers ' this write the array on activesheet of you activeworkbook, starting from D3 .ArrayToRange arrayOfNumbers, Cells(3, 4) End With End Sub </code></pre> <p>I think the best solution would be to create a second object and then compose the two class and expose a property that returns the "filter" object. But I'm concerned that two modules are less immediate and maybe a person that is not familiar with the IDE can find it more difficult.. So I've decided to put an "Filter" suffix on all filter-related methods.</p> <p>Do you have any advice?</p> <p><strong>Sort</strong>: At the moment the sort use merge sort but I want to try to write also insertion sort and introsort (as soon as I'll understand it) but more importantly, how can I understand how to sort by multiple columns? I can't find examples that I can understand... How did you do?</p> <p><strong>Results</strong>: All the methods require byRef arguments and the results of the routine overwrite the arguments. Is this approach acceptable? Or is necessary or good practice to use functions?</p> <p>I would like to have a feedback on the code and on the idea.. Thank you!</p> <pre><code>Option Explicit Private pColumnsToReturn As Variant Private pFiltersCollection As Collection Private pPartialMatchColl As Collection Private Enum filterType negativeMatch = -1 exactMatch = 0 isBetween = 1 contains = 2 End Enum Public Property Let ColumnsToReturn(arr As Variant) pColumnsToReturn = arr End Property ' FILTER METHODS ****************************************************************** Public Sub FilterIncludeEquals(ByRef equalTo As Variant, ByRef inColumn As Long, _ Optional ByRef isCaseSensitive As Boolean = False) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = exactMatch With thisFilter .Add thisFilterType .Add inColumn .Add IIf(isCaseSensitive, equalTo, LCase(equalTo)) .Add isCaseSensitive End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub FilterExcludeEquals(ByRef equalTo As Variant, ByRef inColumn As Long, _ Optional ByRef isCaseSensitive As Boolean = False) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = negativeMatch With thisFilter .Add thisFilterType .Add inColumn .Add IIf(isCaseSensitive, equalTo, LCase(equalTo)) .Add isCaseSensitive End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub FilterIncludeIfBetween(ByRef lowLimit As Variant, ByRef highLimit As Variant, ByRef inColumn As Long) If inColumn &gt; -1 Then Dim thisFilter As Collection Dim thisFilterType As filterType Set thisFilter = New Collection thisFilterType = isBetween With thisFilter .Add thisFilterType .Add inColumn .Add lowLimit .Add highLimit End With If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection pFiltersCollection.Add thisFilter Set thisFilter = Nothing End If End Sub Public Sub FilterIncludeIfContains(ByRef substring As String, Optional ByRef inColumns As Variant = 1) If IsArray(inColumns) Or IsNumeric(inColumns) Then Dim thisFilterType As filterType Set pPartialMatchColl = New Collection thisFilterType = contains With pPartialMatchColl .Add thisFilterType .Add inColumns .Add substring End With End If End Sub Public Sub FilterApplyTo(ByRef originalArray As Variant) If Not IsArray(originalArray) Then Exit Sub If isSingleDimensionalArray(originalArray) Then filterOneDimensionalArray originalArray Else filterTwoDimensionalArray originalArray End If End Sub Private Sub filterTwoDimensionalArray(ByRef originalArray As Variant) Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long Dim row As Long Dim col As Long Dim arrayOfColumnToReturn As Variant Dim partialMatchColumnsArray As Variant Dim result As Variant result = -1 arrayOfColumnToReturn = pColumnsToReturn If Not pPartialMatchColl Is Nothing Then partialMatchColumnsArray = pPartialMatchColl(2) ' If the caller don't pass the array of column to return ' create an array with all the columns and preserve the order If Not IsArray(arrayOfColumnToReturn) Then ReDim arrayOfColumnToReturn(LBound(originalArray, 2) To UBound(originalArray, 2)) For col = LBound(originalArray, 2) To UBound(originalArray, 2) arrayOfColumnToReturn(col) = col Next col End If ' If the caller don't pass an array for partial match ' check if it pass the special value 1, if true the ' partial match will be performed on values in columns to return If Not IsArray(partialMatchColumnsArray) Then If partialMatchColumnsArray = 1 Then partialMatchColumnsArray = arrayOfColumnToReturn End If firstRow = LBound(originalArray, 1) lastRow = UBound(originalArray, 1) ' main loop Dim keepCount As Long Dim filter As Variant Dim currentFilterType As filterType ReDim arrayOfRowsToKeep(lastRow - firstRow + 1) As Variant keepCount = 0 For row = firstRow To lastRow ' exact, excluse and between checks If Not pFiltersCollection Is Nothing Then For Each filter In pFiltersCollection currentFilterType = filter(1) Select Case currentFilterType Case negativeMatch If filter(4) Then If originalArray(row, filter(2)) = filter(3) Then GoTo Skip Else If LCase(originalArray(row, filter(2))) = filter(3) Then GoTo Skip End If Case exactMatch If filter(4) Then If originalArray(row, filter(2)) &lt;&gt; filter(3) Then GoTo Skip Else If LCase(originalArray(row, filter(2))) &lt;&gt; filter(3) Then GoTo Skip End If Case isBetween If originalArray(row, filter(2)) &lt; filter(3) _ Or originalArray(row, filter(2)) &gt; filter(4) Then GoTo Skip End Select Next filter End If ' partial match check If Not pPartialMatchColl Is Nothing Then If IsArray(partialMatchColumnsArray) Then For col = LBound(partialMatchColumnsArray) To UBound(partialMatchColumnsArray) If InStr(1, originalArray(row, partialMatchColumnsArray(col)), pPartialMatchColl(3), vbTextCompare) &gt; 0 Then GoTo Keep End If Next GoTo Skip End If End If Keep: arrayOfRowsToKeep(keepCount) = row keepCount = keepCount + 1 Skip: Next row ' create results array If keepCount &gt; 0 Then firstRow = LBound(originalArray, 1) lastRow = LBound(originalArray, 1) + keepCount - 1 firstColumn = LBound(originalArray, 2) lastColumn = LBound(originalArray, 2) + UBound(arrayOfColumnToReturn) - LBound(arrayOfColumnToReturn) ReDim result(firstRow To lastRow, firstColumn To lastColumn) For row = firstRow To lastRow For col = firstColumn To lastColumn result(row, col) = originalArray(arrayOfRowsToKeep(row - firstRow), arrayOfColumnToReturn(col - firstColumn + LBound(arrayOfColumnToReturn))) Next col Next row End If originalArray = result If IsArray(result) Then Erase result End Sub Private Sub filterOneDimensionalArray(ByRef originalArray As Variant) Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long Dim row As Long Dim col As Long Dim arrayOfColumnToReturn As Variant Dim partialMatchColumnsArray As Variant Dim result As Variant result = -1 firstRow = LBound(originalArray) lastRow = UBound(originalArray) ' main loop Dim keepCount As Long Dim filter As Variant Dim currentFilterType As filterType ReDim arrayOfRowsToKeep(lastRow - firstRow + 1) As Variant keepCount = 0 For row = firstRow To lastRow ' exact, excluse and between checks If Not pFiltersCollection Is Nothing Then For Each filter In pFiltersCollection currentFilterType = filter(1) Select Case currentFilterType Case negativeMatch If filter(4) Then If originalArray(row) = filter(3) Then GoTo Skip Else If LCase(originalArray(row)) = filter(3) Then GoTo Skip End If Case exactMatch If filter(4) Then If originalArray(row) &lt;&gt; filter(3) Then GoTo Skip Else If LCase(originalArray(row)) &lt;&gt; filter(3) Then GoTo Skip End If Case isBetween If originalArray(row) &lt; filter(3) _ Or originalArray(row) &gt; filter(4) Then GoTo Skip End Select Next filter End If ' partial match check If Not pPartialMatchColl Is Nothing Then If InStr(1, originalArray(row), pPartialMatchColl(3), vbTextCompare) &gt; 0 Then GoTo Keep End If GoTo Skip End If Keep: arrayOfRowsToKeep(keepCount) = row keepCount = keepCount + 1 Skip: Next row ' create results array If keepCount &gt; 0 Then firstRow = LBound(originalArray, 1) lastRow = LBound(originalArray, 1) + keepCount - 1 ReDim result(firstRow To lastRow) For row = firstRow To lastRow result(row) = originalArray(arrayOfRowsToKeep(row - firstRow)) Next row End If originalArray = result If IsArray(result) Then Erase result End Sub ' TRANSPOSE ARRAY ****************************************************************** Public Sub Transpose(ByRef originalArray As Variant) If Not IsArray(originalArray) Then Exit Sub If isSingleDimensionalArray(originalArray) Then Exit Sub Dim row As Long Dim column As Long Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long firstRow = LBound(originalArray, 1) firstColumn = LBound(originalArray, 2) lastRow = UBound(originalArray, 1) lastColumn = UBound(originalArray, 2) ReDim tempArray(firstColumn To lastColumn, firstRow To lastRow) As Variant For row = firstColumn To lastColumn For column = firstRow To lastRow tempArray(row, column) = originalArray(column, row) Next column Next row originalArray = tempArray Erase tempArray End Sub Private Function isSingleDimensionalArray(myArray As Variant) As Boolean Dim testDimension As Long testDimension = -1 On Error Resume Next testDimension = UBound(myArray, 2) On Error GoTo 0 isSingleDimensionalArray = (testDimension = -1) End Function ' ARRAY TO STRING ****************************************************************** Public Sub ArrayToString(ByRef originalArray As Variant, ByRef stringToReturn As String, _ Optional colSeparator As String = ",", Optional rowSeparator As String = ";") Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long Dim row As Long Dim col As Long If Not IsArray(originalArray) Then Exit Sub ' Join single dimension array If isSingleDimensionalArray(originalArray) Then stringToReturn = Join(originalArray, colSeparator) Exit Sub End If firstRow = LBound(originalArray, 1) lastRow = UBound(originalArray, 1) firstColumn = LBound(originalArray, 2) lastColumn = UBound(originalArray, 2) ReDim rowArray(firstRow To lastRow) As Variant ReDim tempArray(firstColumn To lastColumn) As Variant For row = firstRow To lastRow ' fill array with values of the entire row For col = firstColumn To lastColumn tempArray(col) = originalArray(row, col) Next col rowArray(row) = Join(tempArray, colSeparator) Next row ' convert rowArray to string stringToReturn = Join(rowArray, rowSeparator) Erase rowArray Erase tempArray End Sub ' STRING TO ARRAY ****************************************************************** Public Sub StringToArray(ByRef myString As String, ByRef arrayToReturn As Variant, _ Optional colSeparator As String = ",", Optional rowSeparator As String = ";") If myString = vbNullString Then Exit Sub Dim rowArr As Variant ReDim tempArr(0, 0) As Variant Dim colArr As Variant Dim firstRow As Long Dim lastRow As Long Dim firstColumn As Long Dim lastColumn As Long Dim row As Long Dim col As Long ' get the dimensions of the resulting array rowArr = Split(myString, rowSeparator) firstRow = LBound(rowArr) lastRow = UBound(rowArr) colArr = Split(rowArr(firstRow), colSeparator) firstColumn = LBound(colArr) lastColumn = UBound(colArr) ' return one dimension array If firstColumn = lastColumn Then arrayToReturn = rowArr Exit Sub End If ' dim result array ReDim tempArr(firstRow To lastRow, firstColumn To lastColumn) For row = firstRow To lastRow ' split each row colArr = Split(rowArr(row), colSeparator) For col = firstColumn To lastColumn ' fill result array If IsDate(colArr(col)) Then tempArr(row, col) = CDate(colArr(col)) Else tempArr(row, col) = colArr(col) End If Next col Next row arrayToReturn = tempArr Erase tempArr Erase rowArr Erase colArr End Sub ' ARRAY TO TEXT FILE ****************************************************************** Public Sub ArrayToTextFile(ByRef originalArray As Variant, ByRef fullPath As String, _ Optional colSeparator As String = ",", Optional rowSeparator As String = ";") Dim fso As FileSystemObject Dim resultingString As String Set fso = New FileSystemObject Me.ArrayToString originalArray, resultingString, colSeparator, rowSeparator With fso.CreateTextFile(fullPath) .Write resultingString End With Set fso = Nothing End Sub ' TEXT FILE TO ARRAY ****************************************************************** Public Sub TextFileToArray(ByRef fullPath As String, ByRef arrayToReturn As Variant, _ Optional colSeparator As String = ",", Optional rowSeparator As String = ";") Dim fso As FileSystemObject Dim resultingString As String Set fso = New FileSystemObject If fso.FileExists(fullPath) Then With fso.OpenTextFile(fullPath) resultingString = .ReadAll End With Me.StringToArray resultingString, arrayToReturn, colSeparator, rowSeparator End If Set fso = Nothing End Sub ' ARRAY TO RANGE ****************************************************************** Public Sub ArrayToRange(ByRef myArray As Variant, ByRef TopLeftCell As Range) Dim totRows As Long Dim totColumns As Long If Not IsArray(myArray) Then Exit Sub If isSingleDimensionalArray(myArray) Then totRows = 1 totColumns = UBound(myArray) - LBound(myArray) + 1 Else totRows = UBound(myArray, 1) - LBound(myArray, 1) + 1 totColumns = UBound(myArray, 2) - LBound(myArray, 2) + 1 End If TopLeftCell.Resize(totRows, totColumns).value = myArray End Sub ' RANGE TO ARRAY ******************************************************************* Public Sub RangeToArray(ByRef TopLeftCell As Range, ByRef ResultingArray As Variant) ResultingArray = TopLeftCell.CurrentRegion.value End Sub ' MERGE ***************************************************************************** Public Sub MergeArrays(ByRef MainArray As Variant, ByRef ArrayOfArrays As Variant) If isSingleDimensionalArray(MainArray) Then MergeArrays1D MainArray, ArrayOfArrays Else MergeArrays2D MainArray, ArrayOfArrays End If End Sub Private Sub MergeArrays2D(ByRef MainArray As Variant, ByRef ArrayOfArrays As Variant) Dim arrayOfColumnToReturn As Variant Dim totRows As Long Dim row As Long Dim column As Long Dim resultRow As Long Dim currentArray As Variant Dim i As Long If Not IsArray(MainArray) Then Exit Sub arrayOfColumnToReturn = pColumnsToReturn ' If the caller don't pass the array of column to return ' create an array with all the columns and preserve the order If Not IsArray(arrayOfColumnToReturn) Then ReDim arrayOfColumnToReturn(LBound(MainArray, 2) To UBound(MainArray, 2)) For column = LBound(MainArray, 2) To UBound(MainArray, 2) arrayOfColumnToReturn(column) = column Next column End If ' calculate dimensions of the result array totRows = UBound(MainArray) For row = LBound(ArrayOfArrays) To UBound(ArrayOfArrays) totRows = totRows + UBound(ArrayOfArrays(row)) - LBound(ArrayOfArrays(row)) + 1 Next row ReDim tempArray(LBound(MainArray) To totRows, LBound(arrayOfColumnToReturn) To UBound(arrayOfColumnToReturn)) As Variant ' fill result array from main array For row = LBound(MainArray) To UBound(MainArray) For column = LBound(arrayOfColumnToReturn) To UBound(arrayOfColumnToReturn) tempArray(row, column) = MainArray(row, column) Next column Next row resultRow = row ' fill result array from ArrayOfArrays For i = LBound(ArrayOfArrays) To UBound(ArrayOfArrays) If IsArray(ArrayOfArrays(i)) Then currentArray = ArrayOfArrays(i) For row = LBound(currentArray) To UBound(currentArray) For column = LBound(arrayOfColumnToReturn) To UBound(arrayOfColumnToReturn) tempArray(resultRow, column) = currentArray(row, column) Next column resultRow = resultRow + 1 Next row End If Next i MainArray = tempArray End Sub Private Sub MergeArrays1D(ByRef MainArray As Variant, ByRef ArrayOfArrays As Variant) Dim totRows As Long Dim row As Long Dim resultRow As Long Dim currentArray As Variant Dim i As Long If Not IsArray(MainArray) Then Exit Sub ' calculate dimensions of the result array totRows = UBound(MainArray) For row = LBound(ArrayOfArrays) To UBound(ArrayOfArrays) totRows = totRows + UBound(ArrayOfArrays(row)) - LBound(ArrayOfArrays(row)) + 1 Next row ReDim tempArray(LBound(MainArray) To totRows) As Variant ' fill result array from main array For row = LBound(MainArray) To UBound(MainArray) tempArray(row) = MainArray(row) Next row resultRow = row ' fill result array from ArrayOfArrays For i = LBound(ArrayOfArrays) To UBound(ArrayOfArrays) If IsArray(ArrayOfArrays(i)) Then currentArray = ArrayOfArrays(i) For row = LBound(currentArray) To UBound(currentArray) tempArray(resultRow) = currentArray(row) resultRow = resultRow + 1 Next row End If Next i MainArray = tempArray End Sub ' SORT **************************************************************************************** Public Sub Sort(ByRef myArray As Variant, Optional ByVal columnToSort As Long, _ Optional Ascending As Boolean = True) If Not IsArray(myArray) Then Exit Sub If isSingleDimensionalArray(myArray) Then Divide1D myArray, Ascending Else Divide2D myArray, columnToSort, Ascending End If End Sub Private Sub Divide1D(thisArray As Variant, _ Optional Ascending As Boolean = True) Dim Length As Long Dim i As Long Length = UBound(thisArray) - LBound(thisArray) If Length &lt; 1 Then Exit Sub Dim Pivot As Long Pivot = Length / 2 ReDim leftArray(Pivot) As Variant ReDim rightArray(Length - Pivot - 1) As Variant Dim Index As Long For Index = LBound(thisArray) To Pivot + LBound(thisArray) leftArray(i) = thisArray(Index) i = i + 1 Next Index i = 0 For Index = Index To UBound(thisArray) rightArray(i) = thisArray(Index) i = i + 1 Next Index Divide1D leftArray Divide1D rightArray Merge1D leftArray, rightArray, thisArray, Ascending End Sub Private Sub Merge1D(leftArray As Variant, rightArray As Variant, _ arrayToSort As Variant, Ascending As Boolean) Dim lLength As Long Dim rLength As Long Dim leftLowest As Long Dim rightLowest As Long Dim resultIndex As Long resultIndex = IIf(Ascending, LBound(arrayToSort), UBound(arrayToSort)) lLength = UBound(leftArray) rLength = UBound(rightArray) Do While leftLowest &lt;= lLength And rightLowest &lt;= rLength If leftArray(leftLowest) &lt;= rightArray(rightLowest) Then arrayToSort(resultIndex) = leftArray(leftLowest) leftLowest = leftLowest + 1 Else arrayToSort(resultIndex) = rightArray(rightLowest) rightLowest = rightLowest + 1 End If resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop Do While leftLowest &lt;= lLength arrayToSort(resultIndex) = leftArray(leftLowest) leftLowest = leftLowest + 1 resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop Do While rightLowest &lt;= rLength arrayToSort(resultIndex) = rightArray(rightLowest) rightLowest = rightLowest + 1 resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop End Sub Private Sub Divide2D(thisArray As Variant, ByRef columnToSort As Long, _ Optional Ascending As Boolean = True) Dim Length As Long Dim firstColumn As Long Dim lastColumn As Long Dim column As Long Dim i As Long firstColumn = LBound(thisArray, 2) lastColumn = UBound(thisArray, 2) Length = UBound(thisArray) - LBound(thisArray) If Length &lt; 1 Then Exit Sub Dim Pivot As Long Pivot = Length / 2 ReDim leftArray(0 To Pivot, firstColumn To lastColumn) As Variant ReDim rightArray(0 To Length - Pivot - 1, firstColumn To lastColumn) As Variant Dim Index As Long For Index = LBound(thisArray) To Pivot + LBound(thisArray) For column = firstColumn To lastColumn leftArray(i, column) = thisArray(Index, column) Next column i = i + 1 Next Index i = 0 For Index = Index To UBound(thisArray) For column = firstColumn To lastColumn rightArray(i, column) = thisArray(Index, column) Next column i = i + 1 Next Index Divide2D leftArray, columnToSort Divide2D rightArray, columnToSort Merge2D leftArray, rightArray, thisArray, Ascending, columnToSort End Sub Private Sub Merge2D(leftArray As Variant, rightArray As Variant, _ arrayToSort As Variant, Ascending As Boolean, ByRef columnToSort As Long) Dim lLength As Long Dim rLength As Long Dim leftLowest As Long Dim rightLowest As Long Dim resultIndex As Long Dim firstColumn As Long Dim lastColumn As Long Dim column As Long resultIndex = IIf(Ascending, LBound(arrayToSort), UBound(arrayToSort)) firstColumn = LBound(arrayToSort, 2) lastColumn = UBound(arrayToSort, 2) leftLowest = LBound(leftArray) rightLowest = LBound(rightArray) lLength = UBound(leftArray) rLength = UBound(rightArray) Do While leftLowest &lt;= lLength And rightLowest &lt;= rLength If leftArray(leftLowest, columnToSort) &lt;= rightArray(rightLowest, columnToSort) Then For column = firstColumn To lastColumn arrayToSort(resultIndex, column) = leftArray(leftLowest, column) Next column leftLowest = leftLowest + 1 Else For column = firstColumn To lastColumn arrayToSort(resultIndex, column) = rightArray(rightLowest, column) Next column rightLowest = rightLowest + 1 End If resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop Do While leftLowest &lt;= lLength For column = firstColumn To lastColumn arrayToSort(resultIndex, column) = leftArray(leftLowest, column) Next column leftLowest = leftLowest + 1 resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop Do While rightLowest &lt;= rLength For column = firstColumn To lastColumn arrayToSort(resultIndex, column) = rightArray(rightLowest, column) Next column rightLowest = rightLowest + 1 resultIndex = resultIndex + IIf(Ascending, 1, -1) Loop End Sub </code></pre> <p>EDIT: Correct an error on filter 1D subroutine</p>
[]
[ { "body": "<p>The first comment has to do with your question about <strong>Results</strong>. IMO you are far better off to implement your ArrayToX and XToArray subroutines as functions. Also, I tried to use your module (<code>Class Module</code> or <code>Standard Module</code>? => recommend <code>ClassModule</code>) and had difficulty understanding how to use the Filters. In fact, I never did figure it out. I wrote a test subroutine in a <code>Standard Module</code> to try and use the code. (I would suggest you could improve your question by providing a similar example of how the class is intended to be used.)</p>\n\n<p>Here's the test subroutine I was working with:</p>\n\n<pre><code>Option Explicit \n\nPublic Sub Test()\n Dim testObject As ArrayOps\n Set testObject = New ArrayOps\n\n Dim arrayOfNumbers(12)\n Dim numbers As Long\n For numbers = 0 To 11\n arrayOfNumbers(numbers) = numbers\n Next\n\n Dim result As String\n testObject.ArrayToString arrayOfNumbers, result\n\n Dim result2 As String\n result2 = testObject.ArrayToString2(arrayOfNumbers)\n\n Dim result3 As String\n result3 = testObject.ArrayToString2(arrayOfNumbers, testObject.FilterIncludeEquals2(3, 0))\n\nEnd Sub\n</code></pre>\n\n<p>The first use of <code>ArrayToString</code> is the version in the posted code. I've added some functions to your module to support the code for <code>result2</code> and <code>result3</code>. </p>\n\n<p>To my eye, the code reads easier using <code>Functions</code> rather than <code>Subroutines</code>. Also, using <code>ByRef</code> to allow passed-in values to change is probably not the best practice - especially for arrays. As the user, I probably do not want to pass in an array and get back a modified version. The user might have wanted to retain the original array for other downstream logic. Using a <code>Function</code> will make the input versus output very clear. </p>\n\n<p>The code for the added <code>ArrayToString2</code> and <code>FilterIncludeEquals2</code> are basically copies of the original Subroutine with some edits and comments. They are:</p>\n\n<pre><code> Public Function ArrayToString2(ByRef originalArray As Variant, Optional filter As Collection = Nothing, _\n Optional colSeparator As String = \",\", Optional rowSeparator As String = \";\") As String\n\n Dim firstRow As Long\n Dim lastRow As Long\n Dim firstColumn As Long\n Dim lastColumn As Long\n Dim row As Long\n Dim col As Long\n\n If Not IsArray(originalArray) Then Exit Function\n\n ' Join single dimension array\n If isSingleDimensionalArray(originalArray) Then\n ArrayToString2 = Join(originalArray, colSeparator)\n If Not filter Is Nothing Then\n ArrayToString2 = FilterApplyTo2(ArrayToString2)\n End If\n\n Exit Function\n End If\n\n firstRow = LBound(originalArray, 1)\n lastRow = UBound(originalArray, 1)\n firstColumn = LBound(originalArray, 2)\n lastColumn = UBound(originalArray, 2)\n\n 'No need to use module variables - locals would be better\n Dim rowArray As Variant\n ReDim rowArray(firstRow To lastRow) As Variant\n\n Dim tempArray As Variant\n ReDim tempArray(firstColumn To lastColumn)\n\n For row = firstRow To lastRow\n ' fill array with values of the entire row\n For col = firstColumn To lastColumn\n tempArray(col) = originalArray(row, col)\n Next col\n rowArray(row) = Join(tempArray, colSeparator)\n Next row\n\n ' convert rowArray to string\n ArrayToString2 = Join(rowArray, rowSeparator)\n\n If Not filter Is Nothing Then\n ArrayToString2 = FilterApplyTo2(ArrayToString2)\n End If\n\n 'Now using local variables\n 'Erase rowArray\n 'Erase tempArray\n\n End Function\n\n Public Function FilterIncludeEquals2(ByRef equalTo As Variant, ByRef inColumn As Long, _\n Optional ByRef isCaseSensitive As Boolean = False) As Collection\n 'Declaring thisFilter outside the If block so that the function always returns a\n 'collection (possibly empty) rather than nothing \n Dim thisFilter As Collection\n Set thisFilter = New Collection\n 'There's an upper limit to check for as well since only 1 and 2 dimensional\n 'arrays are handled?\n If inColumn &gt; -1 And inColumn &lt; 2 Then\n\n 'Dim thisFilter As Collection\n 'Dim thisFilterType As filterType\n\n 'Set thisFilter = New Collection\n 'thisFilterType = exactMatch\n\n With thisFilter\n .Add exactMatch\n .Add inColumn\n .Add IIf(isCaseSensitive, equalTo, LCase(equalTo))\n .Add isCaseSensitive\n End With\n\n 'To use this filter as a parameter in ArrayToString2 I return it directly.\n 'This is different than the original design...just an example to consider \n 'If pFiltersCollection Is Nothing Then Set pFiltersCollection = New Collection\n\n 'pFiltersCollection.Add thisFilter\n 'Set thisFilter = Nothing\n End If\n Set FilterIncludeEquals2 = thisFilter\n\n End Function\n</code></pre>\n\n<p>Based on your update, I better understand what you are working toward - thanks! After looking at your example, I would suggest that there is a definite advantage to creating a class module for the filter operations. Establish a \"Filter\" Property in the ArrayManipulation class. You mention concerns that adding a second module would possibly confusing to the user. IMO it creates less confusion.</p>\n\n<p>Below is another version of the test module with a revised Test Subroutine using the <code>ArrayManipulation</code> class with an <code>ArrayManipulationFilter</code> class member available as <code>Public Property Get Filter()</code>.</p>\n\n<pre><code> Option Explicit\n\n Public Sub Test()\n\n Dim testObject As ArrayManipulation\n Set testObject = New ArrayManipulation\n\n Dim arrayOfNumbers As Variant\n ReDim arrayOfNumbers(12)\n Dim numbers As Long\n For numbers = 0 To 11\n arrayOfNumbers(numbers) = numbers\n Next\n\n Dim arrayReturned As Variant\n With testObject\n ' setup filters\n .Filter.ExcludeEquals 3, 0\n .Filter.IncludeIfBetween 1, 4, 0\n\n ' this create a txt file storing the array\n\n ' The filter can now be applied inline or separately.\n ' Or, \"applyFilters As Boolean\" can also be added as a parameter to the ArrayToX subroutine signatures\n .ArrayToTextFile .Filter.ApplyTo(arrayOfNumbers), Environ(\"USERPROFILE\") &amp; \"\\Desktop\\Test.txt\"\n\n ' this read the array from the just created file\n .TextFileToArray Environ(\"USERPROFILE\") &amp; \"\\Desktop\\Test.txt\", arrayReturned\n\n ' this write the array on activesheet of you activeworkbook, starting from D3\n 'arrayOfNumbers is still the original set of numbers\n .ArrayToRange arrayOfNumbers, Cells(3, 4)\n .ArrayToRange arrayReturned, Cells(5, 4)\n End With\n\n End Sub\n</code></pre>\n\n<p>Below is the ArrayManipulationFilter class which was a copy of the filter subroutines from the original class (with the \"Filter\" prefix removed from the subroutine names) plus the additional code below.</p>\n\n<pre><code> Private Sub Class_Initialize()\n Set pFiltersCollection = New Collection\n End Sub\n\n Public Function ApplyTo(ByRef originalArray As Variant) As Variant\n\n If Not IsArray(originalArray) Then Exit Function\n\n Dim result As Variant\n If isSingleDimensionalArray(originalArray) Then\n ApplyTo = filter1DArray(originalArray)\n Else\n ApplyTo = filter2DArray(originalArray)\n End If\n\n End Function\n\n Private Function isSingleDimensionalArray(myArray As Variant) As Boolean\n\n Dim testDimension As Long\n\n testDimension = -1\n On Error Resume Next\n testDimension = UBound(myArray, 2)\n On Error GoTo 0\n isSingleDimensionalArray = (testDimension = -1)\n\n End Function\n\n Private Function filter2DArray(ByRef originalArray As Variant) As Variant\n\n Dim firstRow As Long\n Dim lastRow As Long\n Dim firstColumn As Long\n Dim lastColumn As Long\n Dim row As Long\n Dim col As Long\n Dim arrayOfColumnToReturn As Variant\n Dim partialMatchColumnsArray As Variant\n Dim result As Variant\n\n result = -1\n arrayOfColumnToReturn = pColumnsToReturn\n If Not pPartialMatchColl Is Nothing Then partialMatchColumnsArray = pPartialMatchColl(2)\n\n ' If the caller don't pass the array of column to return\n ' create an array with all the columns and preserve the order\n If Not IsArray(arrayOfColumnToReturn) Then\n ReDim arrayOfColumnToReturn(LBound(originalArray, 2) To UBound(originalArray, 2))\n For col = LBound(originalArray, 2) To UBound(originalArray, 2)\n arrayOfColumnToReturn(col) = col\n Next col\n End If\n\n ' If the caller don't pass an array for partial match\n ' check if it pass the special value 1, if true the\n ' partial match will be performed on values in columns to return\n If Not IsArray(partialMatchColumnsArray) Then\n If partialMatchColumnsArray = 1 Then partialMatchColumnsArray = arrayOfColumnToReturn\n End If\n\n firstRow = LBound(originalArray, 1)\n lastRow = UBound(originalArray, 1)\n\n ' main loop\n Dim keepCount As Long\n Dim Filter As Variant\n Dim currentFilterType As filterType\n\n ReDim arrayOfRowsToKeep(lastRow - firstRow + 1) As Variant\n keepCount = 0\n\n For row = firstRow To lastRow\n\n ' exact, excluse and between checks\n If Not pFiltersCollection Is Nothing Then\n For Each Filter In pFiltersCollection\n currentFilterType = Filter(1)\n Select Case currentFilterType\n Case negativeMatch\n If Filter(4) Then\n If originalArray(row, Filter(2)) = Filter(3) Then GoTo Skip\n Else\n If LCase(originalArray(row, Filter(2))) = Filter(3) Then GoTo Skip\n End If\n Case exactMatch\n If Filter(4) Then\n If originalArray(row, Filter(2)) &lt;&gt; Filter(3) Then GoTo Skip\n Else\n If LCase(originalArray(row, Filter(2))) &lt;&gt; Filter(3) Then GoTo Skip\n End If\n Case isBetween\n If originalArray(row, Filter(2)) &lt; Filter(3) _\n Or originalArray(row, Filter(2)) &gt; Filter(4) Then GoTo Skip\n End Select\n Next Filter\n End If\n\n ' partial match check\n If Not pPartialMatchColl Is Nothing Then\n If IsArray(partialMatchColumnsArray) Then\n For col = LBound(partialMatchColumnsArray) To UBound(partialMatchColumnsArray)\n If InStr(1, originalArray(row, partialMatchColumnsArray(col)), pPartialMatchColl(3), vbTextCompare) &gt; 0 Then\n GoTo Keep\n End If\n Next\n GoTo Skip\n End If\n End If\n Keep:\n arrayOfRowsToKeep(keepCount) = row\n keepCount = keepCount + 1\n Skip:\n Next row\n\n ' create results array\n If keepCount &gt; 0 Then\n\n firstRow = LBound(originalArray, 1)\n lastRow = LBound(originalArray, 1) + keepCount - 1\n firstColumn = LBound(originalArray, 2)\n lastColumn = LBound(originalArray, 2) + UBound(arrayOfColumnToReturn) - LBound(arrayOfColumnToReturn)\n\n ReDim result(firstRow To lastRow, firstColumn To lastColumn)\n\n For row = firstRow To lastRow\n For col = firstColumn To lastColumn\n result(row, col) = originalArray(arrayOfRowsToKeep(row - firstRow), arrayOfColumnToReturn(col - firstColumn + LBound(arrayOfColumnToReturn)))\n Next col\n Next row\n\n End If\n\n filter2DArray = result\n If IsArray(result) Then Erase result\n\n End Function\n\n Private Function filter1DArray(ByRef originalArray As Variant) As Variant\n\n Dim firstRow As Long\n Dim lastRow As Long\n Dim firstColumn As Long\n Dim lastColumn As Long\n Dim row As Long\n Dim col As Long\n Dim arrayOfColumnToReturn As Variant\n Dim partialMatchColumnsArray As Variant\n Dim result As Variant\n\n result = -1\n\n firstRow = LBound(originalArray)\n lastRow = UBound(originalArray)\n\n ' main loop\n Dim keepCount As Long\n Dim Filter As Variant\n Dim currentFilterType As filterType\n\n ReDim arrayOfRowsToKeep(lastRow - firstRow + 1) As Variant\n keepCount = 0\n\n For row = firstRow To lastRow\n\n ' exact, excluse and between checks\n If Not pFiltersCollection Is Nothing Then\n For Each Filter In pFiltersCollection\n currentFilterType = Filter(1)\n Select Case currentFilterType\n Case negativeMatch\n If Filter(4) Then\n If originalArray(row) = Filter(3) Then GoTo Skip\n Else\n If LCase(originalArray(row)) = Filter(3) Then GoTo Skip\n End If\n Case exactMatch\n If Filter(4) Then\n If originalArray(row) &lt;&gt; Filter(3) Then GoTo Skip\n Else\n If LCase(originalArray(row)) &lt;&gt; Filter(3) Then GoTo Skip\n End If\n Case isBetween\n If originalArray(row) &lt; Filter(3) _\n Or originalArray(row) &gt; Filter(4) Then GoTo Skip\n End Select\n Next Filter\n End If\n\n ' partial match check\n If Not pPartialMatchColl Is Nothing Then\n If InStr(1, originalArray(row), pPartialMatchColl(3), vbTextCompare) &gt; 0 Then\n GoTo Keep\n End If\n GoTo Skip\n End If\n Keep:\n arrayOfRowsToKeep(keepCount) = row\n keepCount = keepCount + 1\n Skip:\n Next row\n\n ' create results array\n If keepCount &gt; 0 Then\n\n firstRow = LBound(originalArray, 1)\n lastRow = LBound(originalArray, 1) + keepCount - 1\n\n ReDim result(firstRow To lastRow)\n\n For row = firstRow To lastRow\n result(row) = originalArray(arrayOfRowsToKeep(row - firstRow))\n Next row\n\n End If\n\n filter1DArray = result\n If IsArray(result) Then Erase result\n\n End Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T14:07:14.957", "Id": "467598", "Score": "0", "body": "Hey BZngr! Thank you for your feedback.. You're right I'll modify all the routine to function... I've modified your test code to show how to use filter and other function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T04:05:41.780", "Id": "467680", "Score": "0", "body": "I've modified the answer content based on your test code example. Thanks for providing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T14:16:49.210", "Id": "467720", "Score": "0", "body": "Thanks to you for the effort! I've seen your update, and I'm working to rewrite the code for the best result.. I'll wait 2 more days for other answers and then I'll accept your. Thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T07:47:08.810", "Id": "238403", "ParentId": "238397", "Score": "3" } } ]
{ "AcceptedAnswerId": "238403", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T02:22:04.827", "Id": "238397", "Score": "3", "Tags": [ "object-oriented", "array", "vba" ], "Title": "Array manipulation object" }
238397
<p>can you please provide some advice on my codes below? There is 7 categorical features and 1 categorical target. This is a classification problem and I'm using RandomForest to train the data. </p> <p>I have used columnTransformer() to transform the categorical data through OneHotEncoder and put them in the pipeline. Then I will pickle the pipeline for API use through the def predict() that I build. </p> <p>Would be good to have another pair of eyes to review my code. Thanks! </p> <pre><code>X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) numeric_features = df.select_dtypes(include=['int64', 'float64']).columns categorical_features = df.select_dtypes(include=['object']).drop(['Severity_Level'], axis=1).columns preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features)]) rf = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', RandomForestClassifier())]) rf.fit(X_train, y_train) pickle.dump(rf,open('model3.pkl','wb')) </code></pre> <h1>Load model</h1> <pre><code>model = pickle.load(open('model3.pkl','rb')) </code></pre> <h1>Function for API use:</h1> <pre><code>def predict(Project_Sector, IncidentType, Parent_Child_Type, Project_Lifecycle_Phase, LL_BU, Project_Size, HeadContractType): result = model.predict(x) # send back to browser output = {'results': (result[0])} print(output) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:46:42.077", "Id": "467559", "Score": "0", "body": "I've updated to use ColumnTransformer in the line as I realized that the OneHotEncoder didn't work in the pipeline as the data didn't get transformed. I have deleted the post. Thanks" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T05:49:21.587", "Id": "238400", "Score": "1", "Tags": [ "python", "pandas" ], "Title": "ML Pipeline with OneHotEncoder and model" }
238400
<p>I've written the code below to compare the two columns of choice of two different excel files (new data and a reference file). If a value in the new data file is present in the reference file, "yes" is added in a new column behind the value in the new data file and "no" if not. The columns to compare can be anything you want and can be specified in the top of the script.</p> <p>The script does the trick for small datasets (few 100 to few 1000 rows). However, I'm currently comparing two files where each files has ~300 000 columns. It has currently analysed +/- 56% of the new data file rows in ~18 hours. So the script needs to run nearly 36 hours to complete. It appears that Python only processes ~2 rows per second, hence the time.</p> <p>Is there a way to speed up this process? I was thinking that perhaps a list comprehension could add a little bit to the speed, but it seems complex to write this as a list comprehension. Any other suggestions?</p> <p>PS: The error raises perhaps seem redundant but as I'm no Python expert I was experimenting with error raising.</p> <pre><code>#======SPECIFY COLUMNS TO COMPARE======# data_column = "column name" ref_column ="column name" #=====================================# import os basedir = r'C:\path' datadir = os.path.join(basedir, "data") refdir = os.path.join(basedir, "ref_db") exportdir = os.path.join(basedir, "export") import pandas as pd #select the excel file (with any name) in the data folder data_list = [os.path.join(datadir,file) for file in os.listdir(datadir) if file.endswith(".xlsx")] if len(data_list) == 0: raise ImportError("There is no excel file in the data folder") elif len(data_list) &gt; 1: raise ImportError("There is more than 1 excel file in the data folder") #data_list is a list of excel files in the folder. Select the one with index 0 as this should be the only one present. new_data = pd.read_excel(data_list[0]) new_data[str("Comparison"+"_"+data_column)] = "" #load the reference database in the export folder ref_list = [os.path.join(refdir,file) for file in os.listdir(refdir) if file.endswith(".xlsx")] if len(ref_list) == 0: raise ImportError("There is no excel file in the ref_db folder") elif len(ref_list) &gt; 1: raise ImportError("There is more than 1 excel file in the ref_db folder") ref_db = pd.read_excel(ref_list[0]) #check if specified columns occur in the excel files if not data_column in new_data.columns: raise KeyError("specified data_column does not exist in the input data file") if not ref_column in ref_db.columns: raise KeyError("specified ref_column does not exist in the input data file") warn = [] for i,col in enumerate(new_data[data_column]): #iterate over each row in the specified column + save the index "i" if col in ref_db[ref_column].values: #check if the value col at index i of new_data occurs in the reference database: new_data[str("Comparison"+"_"+data_column)][i] = "yes" count = ref_db.groupby(ref_column).size() if count[col] &gt; 1: warn.append(["WARNING: value",col,"occurs multiple times in column",ref_column,"of the ref_db excel file"]) #if no: else: #assign "no" to the column new_data[str("Comparison"+"_"+data_column)][i] = "no" #print("Processing sequence",i,"of",len(new_data["sequence"])) #print the progress of the matching process print(round((i/len(new_data[data_column]))*100,2),"% of entries processed") for i,j in enumerate(warn): print(*warn[i]) new_data.to_excel(os.path.join(exportdir, "compare_export.xlsx")) #save the file to the export folder </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:52:26.147", "Id": "467543", "Score": "1", "body": "Without a deeper look at your code: The usual advice is [don't](https://www.youtube.com/watch?v=EEUXKG97YRw) [loop](https://www.youtube.com/watch?v=zQeYx87mfyw)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:54:10.100", "Id": "467544", "Score": "0", "body": "Also please have a look at [ask], especially *\"[s]tate what your code does in your title, not your main concerns about it. Be descriptive and interesting, and you'll attract more views to your question.\"*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T09:20:14.157", "Id": "467548", "Score": "0", "body": "thank you for the youtube links, I will check them out. And thanks for the tip!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:01:48.003", "Id": "467580", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:30:10.657", "Id": "467587", "Score": "0", "body": "thank you. I've edited the title. I hope this one is more suitable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T17:28:44.780", "Id": "467622", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title*\", rather than its implementation details. Please check that I haven't misrepresented your code, and correct it if I have." } ]
[ { "body": "<p>Unfortunately I am not experienced with Pandas especially on large files. But I would have tried a more 'native' solution like VBA but it is because I have some experience with it. There is a chance that VBA (in the form of a macro) would perform faster.</p>\n\n<p>Perhaps you can try a hybrid approach, for example add some temporary columns to the files you are processing in Python, and fill those columns with formulae like COUNTIF etc.\nThe aim is to <strong>let Excel do the computationally-intensive stuff</strong>. And then you let your script loop row by one using the precalculations made by Excel.</p>\n\n<p>When you are done, you remove the temporary columns or simply close the file discarding changes.\nThis may not be the more elegant approach, but I am not surprised that an interpreted language like Python with all the middleware involved is slow for this kind of task.</p>\n\n<p>Another option is to dump the sheets to a database, MS Access or SQLite, add some indexes where appropriate and use SQL to fill out the gaps and then re-import the result to Excel.</p>\n\n<p>This is more a hack than a real solution. My considerations would be:</p>\n\n<ul>\n<li>is this a one-shot operation or a process that you will have to repeat ? This is to answer the question: how much time and energy are you willing to invest in this ?</li>\n<li>You have not mentioned the <strong>purpose</strong> of the Excel files, and you've not shared the structure or a data sample. 300K columns for an Excel file is very big. I am wondering if by any change you are on assignment with some corporate client where clerks <strong>use Excel like a database</strong>. This is a very common scenario unfortunately. Then I would advise them to use a better solution. The whole process and usage is flawed and the solution can hardly be elegant.</li>\n</ul>\n\n<p>Probably there are solutions already available on the market, including free and open source software. From experience there is little added value trying to patch a flawed process.</p>\n\n<p>Everybody uses Excel, so Excel files proliferate everywhere and the result is poorly-structured data that is hard to exploit.\nUsing Excel is often the problem and the solution is to move away from Excel.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T17:27:21.417", "Id": "238442", "ParentId": "238404", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:09:43.483", "Id": "238404", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Spreadsheet column membership test" }
238404
<p>I'm new to development (I'm self Taught I got a job recently as an"app Developer") and this is my first real big project. In essence, it's an e-commerce store that uses a very awkward API. My Checkout process is taking 6 seconds per item and you can imagine if I let a user checkout 50+ items, they will think something's wrong.</p> <p>I'm going to share my whole checkout process along with a question. What are my bottlenecks? Too many loops to make checks? How do I improve something like this?</p> <p>A few things to note, I have a variable and a single Product. Sometimes the API returns the Stock Quantity of <code>null</code>, which just means that it's unlimited.</p> <pre><code> private async void Checkout_clicked(object sender, EventArgs e) { try { await Navigation.PushPopupAsync(new LoadingPopup()); } catch (Exception ex) { Crashes.TrackError(ex); } try { if (FullCart.CartList == null || FullCart.CartList.Count &lt;= 0 || !FullCart.CartList.Any()) { var yx = await DisplayAlert("Whoops", "Cart seem's to be empty, We cant checkout nothing", "Back to Cart", "Supplier"); if (yx) { } else { var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Suppliers()); Application.Current.MainPage = masterDetailPage; } } else { await BeginCheckout(); } } catch (Exception ex) { Crashes.TrackError(ex); } try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } } </code></pre> <pre><code> private async Task BeginCheckout() { try { //You cant checkout if your not logged in There are no Guest Checkouts(I can But would rather not) if (Users.LoggedIn &amp;&amp; _spamClick == false) { if (_orderlineitems == null) _orderlineitems = new List&lt;OrderLineItem&gt;(); RestAPI rest = new RestAPI("http://xxxxx/wp-json/wc/v2/", "xxxxxxxxxxxxxxxxxxxxxxxxx", "cs_xxxxxxxxxxxxxxxxxxxxxxxx"); var wc = new WCObject(rest); await IsInStock(); var order = new Order { status = "on-hold", customer_id = Users.CId }; foreach (var item in _simpleCartlist) if (_simpleCartlist.Any(i =&gt; i.InStock == false)) { try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } } else if (_simpleCartlist.All(i =&gt; i.InStock)) { if (item.StockStatus == "instock" || item.StockStatus is string stringValue &amp;&amp; string.IsNullOrWhiteSpace(stringValue) || item.StockStatus == null) { var a = Convert.ToInt32(item.ProductQuantity); if (item.VariationId &lt;= 0) item.VariationId = item.PId; if (item.StockQuantity == 0) { _productBoughtOut = true; _productnames.Add(item.ProductName); } order.line_items = order.line_items ?? new List&lt;OrderLineItem&gt;(); order.line_items.Add(new OrderLineItem { product_id = item.PId, variation_id = item.VariationId, quantity = a }); } else { try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } var yx = await DisplayAlert("Order Cant be Placed", $"{item.ProductName} is out of stock", "Back to Cart", "Home"); if (yx) { } else { var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Home()); Application.Current.MainPage = masterDetailPage; } } } if (_productBoughtOut) { try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } var yx = await DisplayAlert("Order Cant be Placed", $"Not enough stock for {_productnames}", "Back to Cart", "Home"); if (yx) { } else { var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Home()); Application.Current.MainPage = masterDetailPage; } } else if (_simpleCartlist.All(i =&gt; i.InStock)) { if (FullCart.CartList != null &amp;&amp; _spamClick == false || _items.Items != null &amp;&amp; _spamClick == false) { _spamClick = true; await wc.Order.Add(order); Preferences.Clear("Cart"); Preferences.Remove("Cart"); FullCart.CartList.Clear(); _items.Items.Clear(); var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Checkedout()); Application.Current.MainPage = masterDetailPage; } _spamClick = true; } } else { if (_spamClick) { await DisplayAlert("Woops", "Your trying to order twice", "Ok"); } else { var y = await DisplayAlert("Woops", "Please Login to check Out", "Login", "Home"); if (y) { var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Login()); Application.Current.MainPage = masterDetailPage; } else { await Navigation.PushAsync(new Home()); } } } } catch (Exception ex) { Crashes.TrackError(ex); } } </code></pre> <pre><code>private async Task SingleCheck() { try { foreach (var CartItem in _simpleCartlist) if (_currentListItem == CartItem.PId) { if (_singleProduct.stock_quantity == null) { //CartItem.InStock = true; _singleProduct.stock_quantity = 999999; } if (CartItem.ProductQuantity == 0) { CartItem.ErrorMsg = "Item requires a Quantity of atleast 1" + System.Environment.NewLine + "Quantity Cannot be 0!"; await DisplayAlert("Oops", "Whe can't checkout nothing See if a products quantity isnt 0", "Ok"); return; } if (_singleProduct.stock_quantity == 0 || _singleProduct.stock_status == "outofstock" || CartItem.ProductQuantity &gt; _singleProduct.stock_quantity) { try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } CartItem.InStock = false; var AlertResult = await DisplayAlert("Not Enough Products", $"There is this much Stock left: {_singleProduct.stock_quantity} for {_singleProduct.name}", "Back to Cart", "Keep Shopping"); CartItem.ErrorMsg = "Product shortage " + $" There is this much Stock left: {_singleProduct.stock_quantity} for {_singleProduct.name}"; if (AlertResult) { CartItem.InStock = false; CartItem.StockQuantity = Convert.ToInt32(_singleProduct.stock_quantity); _items = new ItemList(FullCart.CartList); cartView.BeginRefresh(); CartItem.StockStatus = _singleProduct.stock_status; cartView.EndRefresh(); return; } var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Home()); Application.Current.MainPage = masterDetailPage; } else if (_singleProduct.stock_quantity != 0 &amp;&amp; _singleProduct.stock_status == "instock" &amp;&amp; CartItem.ProductQuantity &lt;= _singleProduct.stock_quantity) { CartItem.ErrorMsg = ""; CartItem.InStock = true; } } } catch (Exception ex) { Crashes.TrackError(ex); } } </code></pre> <pre><code> private async Task VariableCheck() { //TODO if your seeing this, Your probably Developing on this now, if you're... Run! Honestly Run... try { foreach (var CartItem in _simpleCartlist) if (_currentListItem == CartItem.PId) { if (_varProduct.stock_quantity == null) { _varProduct.stock_quantity = 999999; } if (CartItem.ProductQuantity == 0) { CartItem.ErrorMsg = "Item requires a Quantity of atleast 1" + System.Environment.NewLine + "Quantity Cannot be 0!"; await DisplayAlert("Oops", "Whe can't checkout nothing See if a products quantity isnt 0", "Ok"); return; } if (_varProduct.stock_quantity == 0 || _varProduct.stock_status == "outofstock" || CartItem.ProductQuantity &gt; _varProduct.stock_quantity) { try { await Navigation.PopPopupAsync(); } catch (Exception ex) { Crashes.TrackError(ex); } CartItem.InStock = false; var AlertResult = await DisplayAlert("Not Enough Products", $"There is this much Stock left: {_varProduct.stock_quantity} for {CartItem.ProductName} {_varProduct.attributes[2].option}", "Back to Cart", "Keep Shopping"); CartItem.ErrorMsg = "Not Enough Products" + $"There is this much Stock left: {_varProduct.stock_quantity} for {CartItem.ProductName} {_varProduct.attributes[2].option}"; if (AlertResult) { CartItem.InStock = false; CartItem.StockQuantity = Convert.ToInt32(_varProduct.stock_quantity); _items = new ItemList(FullCart.CartList); cartView.BeginRefresh(); CartItem.StockStatus = _varProduct.stock_status; cartView.EndRefresh(); return; } var masterDetailPage = new Home(); masterDetailPage.Detail = new NavigationPage(new Home()); Application.Current.MainPage = masterDetailPage; } else if (_varProduct.stock_quantity != 0 &amp;&amp; _varProduct.stock_status == "instock" &amp;&amp; CartItem.ProductQuantity &lt;= _varProduct.stock_quantity) { CartItem.ErrorMsg = ""; CartItem.InStock = true; } } } catch (Exception ex) { Crashes.TrackError(ex); } } </code></pre> <pre><code> private readonly List&lt;CartList&gt; _simpleCartlist; private int _currentId; private int _currentListItem; private ItemList _items; private List&lt;OrderLineItem&gt; _orderlineitems; private bool _productBoughtOut; private List&lt;string&gt; _productnames; private Product _singleProduct; private bool _spamClick; private Variation _varProduct; private bool _loading; public bool loading { get =&gt; _loading; set { if (_loading == value) return; _loading = value; RaisePropertyChanged(); } } private bool _running; public bool running { get =&gt; _running; set { if (_running == value) return; _running = value; RaisePropertyChanged(); } } </code></pre> <p>The idea with spam-click is to avoid Double orders. I can definitely understand the frustration with all my if's. Any suggestions in regards to that would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:04:14.313", "Id": "467582", "Score": "0", "body": "Noted thank you" } ]
[ { "body": "<p>Too many <code>try/catch</code> blocks, and it's redundant and misplaced. For instance <code>Checkout_clicked</code> method can be done this way : </p>\n\n<pre><code>private async void Checkout_clicked(object sender, EventArgs e)\n{\n try\n {\n await Navigation.PushPopupAsync(new LoadingPopup());\n\n // what is happning here ? \n // when Cart is NULL OR Does not have any elements OR Count is less than zero ? \n if (FullCart.CartList == null || FullCart.CartList.Count &lt;= 0 || !FullCart.CartList.Any())\n {\n var yx = await DisplayAlert(\"Whoops\",\"Cart seem's to be empty, We cant checkout nothing\", \"Back to Cart\", \"Supplier\");\n\n if (!yx)\n {\n var masterDetailPage = new Home();\n masterDetailPage.Detail = new NavigationPage(new Suppliers());\n Application.Current.MainPage = masterDetailPage;\n }\n }\n else\n {\n await BeginCheckout();\n }\n\n await Navigation.PopPopupAsync();\n\n }\n catch (Exception ex)\n {\n Crashes.TrackError(ex);\n }\n}\n</code></pre>\n\n<p>same thing can applied to the other blocks. This is a must do modification as nested <code>try/catch</code> is a bad practice, ugly, and it would impact the performance. So, it must be avoided.</p>\n\n<p>Secondly, when using <code>if</code> statements to validate, don't put your method validation in <code>else</code> clause. Take <code>BeginCheckout</code> as an example :</p>\n\n<pre><code>/*\n Part 1 : Validations \n*/\n\n//You cant checkout if your not logged in There are no Guest Checkouts(I can But would rather not)\nif (_spamClick)\n{\n await DisplayAlert(\"Woops\", \"Your trying to order twice\", \"Ok\");\n return; \n}\n\nif (!Users.LoggedIn)\n{\n // User is not logged in it should display this message immediately, and return it back to login screen or give the user the choice to go there \n await DisplayAlert(\"Woops\", \"Please Login to check Out\", \"Login\", \"Home\");\n return;\n}\n\n// this is okay\nif (_orderlineitems == null) { _orderlineitems = new List&lt;OrderLineItem&gt;(); }\n\n// outside the loop since it's not releated to the loop \nif (!_simpleCartlist.Any(i =&gt; i.InStock == false) || _productBoughtOut) \n{ \n await Navigation.PopPopupAsync(); \n return;\n} \n\nif(FullCart.CartList == null || _items.Items == null) { return; /* what should happen if the cart is null ? */ }\n\n\n/*\n Part 2 : Process \n*/\nforeach (var item in _simpleCartlist)\n{ \n //if out of stock\n if (item.StockStatus != \"instock\" || !string.IsNullOrWhiteSpace(item.StockStatus)) { continue; } // skip this and go to the next item\n\n ... //rest of the loop \n var a = Convert.ToInt32(item.ProductQuantity);\n if (item.VariationId &lt;= 0) item.VariationId = item.PId;\n if (item.StockQuantity == 0)\n {\n _productBoughtOut = true;\n _productnames.Add(item.ProductName);\n }\n\n order.line_items = order.line_items ?? new List&lt;OrderLineItem&gt;();\n order.line_items.Add(new OrderLineItem\n { product_id = item.PId, variation_id = item.VariationId, quantity = a }); \n}\n\n_spamClick = true;\nawait wc.Order.Add(order);\nPreferences.Clear(\"Cart\");\nPreferences.Remove(\"Cart\");\nFullCart.CartList.Clear();\n_items.Items.Clear();\nvar masterDetailPage = new Home();\nmasterDetailPage.Detail = new NavigationPage(new Checkedout());\nApplication.Current.MainPage = masterDetailPage;\n</code></pre>\n\n<p><em>FOR DEMONSTRATION PURPOSE ONLY</em> </p>\n\n<p>Refactoring the <code>if</code> statements, to put the main validations at the top of the code, then go to the process. This way, the code would execute the validation part first, then if it passed this part it would go and execute the process part. This is a common used methodology since it's readable, easy to follow, and also follow the execution workflow. </p>\n\n<p>The main idea is, whenever you see that the if condition would have a long executable logic or will include nested <code>if</code>s, you should think of inverting it to make it simpler and extract the actual code outside it. Like the example above. </p>\n\n<p>Also, in the example you will notice that I've used <code>return;</code> which is something I don't recommend to be used often in a work environment. But for testing and examples would be okay. The reason for that it would not handle anything, while you should handle every expected condition that happens in your logic to be more maintainable and understandable for other developers. </p>\n\n<p>Another thing, braces exist for a reason. So, try to use them, as it would make things much easier to follow and maintainable. Even in Visual Studio, with braces, you could collapse or expand any part you want in the source. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T14:59:39.523", "Id": "467604", "Score": "0", "body": "I see this makes alot of sense\nMy only Qeustion is how I Do prevent access to the \n\norder.add ect If a items out of stock, I'd need them to remove that item before I can Properly place the Order(Without using returns ofcourse, as you mentioned its not something youd recommend in a work environment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:19:33.810", "Id": "467606", "Score": "0", "body": "@Azurry this is where dividing the code into small portions would come in handy. For instance, in the example of `BeginCheckout` put part 1 & 2 into methods named them something like `CheckoutValidate()` and `CheckoutProcess()` then in the `BeginCheckout` put the validate first, and make it returns a boolean, if true execute the `CheckoutProcess()` if false, it won't be executed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:47:22.850", "Id": "238423", "ParentId": "238405", "Score": "0" } }, { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Why do <code>FullCart.CartList.Count &lt;= 0 || !FullCart.CartList.Any()</code>? That's the same check twice.</p></li>\n<li><p>Use proper variable names: <code>var yx</code> is meaningless.</p></li>\n<li><p>Do not hardcode these kind of things: <code>new RestAPI(\"http://xxxxx/wp-json/wc/v2/\", \"xxxxxxxxxxxxxxxxxxxxxxxxx\", \"cs_xxxxxxxxxxxxxxxxxxxxxxxx\");</code>. API urls etc. should be in config files.</p></li>\n<li><p>Do not use magic strings: <code>\"on-hold\"</code> in <code>var order = new Order { status = \"on-hold\", customer_id = Users.CId };</code> should really be an <code>enum</code>, or at least a centrally configured <code>const string</code>. Same for <code>item.StockStatus == \"instock\"</code> and other such items.</p></li>\n<li><p>Why is a single user represented by the object <code>Users</code> (as in <code>Users.LoggedIn</code> and <code>Users.CId</code>)?</p></li>\n<li><p>Do not leave out braces around large <code>foreach</code> sections etc.</p></li>\n<li><p>Where did you learn this: <code>item.StockStatus is string stringValue &amp;&amp; string.IsNullOrWhiteSpace(stringValue) || item.StockStatus == null</code>? Why use this elaborate way when all you need is <code>string.IsNullOrWhiteSpace(item.StockStatus)</code>? (And again: <code>StockStatus</code> should be an <code>enum</code>.)</p></li>\n<li><p>Besides the meaningless variable name, what bothers me most about <code>var a = Convert.ToInt32(item.ProductQuantity);</code> is that <code>ProductQuantity</code> isn't an <code>int</code> to begin with.</p></li>\n<li><p><code>order.line_items</code>: <code>line_items</code> should be Pascalcased. Moreover, property names and variable names etc. should only contain alphanumeric characters (exception: private class-wide variables can have an underscore at the start). Ditto <code>product_id</code> etc.</p></li>\n<li><p>Please get a native English speaker to spellcheck your messages. They often contain spelling errors and incorrect capitalization (e.g. <code>\"Order Cant be Placed\"</code>, <code>\"Cart seem's to be empty, We cant checkout nothing\"</code>,...). Also, <code>\"Woops\"</code> is not a word I expect to see in a e-commerce application.</p></li>\n<li><p>Split your methods into smaller ones. For instance, <code>BeginCheckout()</code> is 140 lines and mixes UI logic with business logic. Every call to <code>Navigation</code> is wrapped in a <code>try...catch</code> block which makes things hard to follow. To me that whole method should be a class of its own.</p></li>\n<li><p>Looking at <code>SingleCheck()</code> I'm baffled that you halt execution inside a foreach to wait for the user to respond in case of a lack of stock. Why not build a report instead and then bother the user only if one or more items cannot be fulfilled?</p></li>\n<li><p><code>foreach (var CartItem in _simpleCartlist)</code>: variables should be camelCased.</p></li>\n<li><p>Some of the business logic is just incomprehensible: <code>if (_varProduct.stock_quantity == null) { _varProduct.stock_quantity = 999999; }</code> How does that even make sense?</p></li>\n<li><p>How does this code even hang together? I don't see where <code>_currentListItem</code> is set. I don't see why you should need \"6 seconds per item\". I don't see calls to the APIs.</p></li>\n</ul>\n\n<hr>\n\n<p>My main recommendation: split these large methods up into small ones, so the program flow becomes much clearer. Do not constantly bounce between business logic and UI calls. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T14:49:42.847", "Id": "467600", "Score": "0", "body": "Just wanna start and say I really appreciate the input This why id love to have a senior to work under The Double check is redundant dint notice that the quick Var xy are for debugging should get rid of those 1000% agree, So Separate class for API Urls? so isntead of saying = \"in stock\" I should have a const string thats = to \"in stock\"? The missing Braces is due to rider going a little nuts I represent the Users as UserS instead of user because I have a list of users i check threw in the login, This sounds dumb from my side typing this ," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T14:53:50.033", "Id": "467601", "Score": "0", "body": "Thank you for showing me the shorthand for isNullorWhite dint know that. The Line_items naming is due to the wrappers naming conventions, Im not sure what its even called ( Extending a wrappers classes so I can use my own classes instead type of thing) Separation of concern for ui and business, Noted. So let the process finish then display a report of \"Failure this and this is out of stock\" ? instead The stock_quantity being null is the api's way of saying \"Unlimited\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T14:55:09.600", "Id": "467603", "Score": "0", "body": "So I set a high value, would int.maxvalue be better? I dont understand my self it shouldnt take 6 seconds to clear this , The only api calls are await wc.Order.Add(order);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:22:42.737", "Id": "467607", "Score": "0", "body": "IMHO you shouldn't set a max value, you should know the amount of stock. Assuming there are a million items in stock seems arbitrary to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:29:47.587", "Id": "467608", "Score": "0", "body": "Some Items are produced on site so they can basically make a order of 2 billion if someone wanted that The api returns null for infinity basically I dont know why But its not my api" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:46:45.817", "Id": "467609", "Score": "0", "body": "https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products Check the docs its really silly look at list all products Stock-Q = null is tech unlimited" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:47:32.093", "Id": "238424", "ParentId": "238405", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T08:34:39.767", "Id": "238405", "Score": "2", "Tags": [ "c#", "xamarin" ], "Title": "Checkout Process for Xamarin E commerce application" }
238405
<p><a href="https://qutebrowser.org" rel="nofollow noreferrer">Qutebrowser</a> uses search engines similar to <a href="https://duckduckgo.com/bang" rel="nofollow noreferrer">DuckDuckGo's Bangs</a> to facilitate searching. The <code>config.py</code> file for the browser contains a search engine Python dictionary. Each key is a search engine, and the corresponding value is a template string. When a search engine is used, every <code>{}</code> in its template is replaced by the search term, and the resulting url is visited.</p> <p>A dictionary with identical keys can be defined anywhere in <code>config.py</code>, so it's important for me to get only the key-value pairs in the <code>c.url.searchengines</code> dictionary. The relevant section of my <code>config.py</code> looks like this:</p> <pre><code>## Search engines which can be used via the address bar. Maps a search ## engine name (such as `DEFAULT`, or `ddg`) to a URL with a `{}` ## placeholder. The placeholder will be replaced by the search term, use ## `{{` and `}}` for literal `{`/`}` signs. The search engine named ## `DEFAULT` is used when `url.auto_search` is turned on and something ## else than a URL was entered to be opened. Other search engines can be ## used by prepending the search engine name to the search term, e.g. ## `:open google qutebrowser`. ## Type: Dict # c.url.searchengines = {'DEFAULT': 'https://duckduckgo.com/?q={}'} c.url.searchengines = { 'DEFAULT': 'https://duckduckgo.com/?q={}', 'ddg' : 'https://duckduckgo.com/?q={}', 'gh' : 'https://github.com/search?q={}', 'w' : 'https://en.wikipedia.org/?search={}', } ## Page(s) to open at the start. </code></pre> <p>I wrote this script to mimic the behavior of Qutebrowser's search engines in the terminal:</p> <pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash set -eu search_engine_file="$HOME/.config/qutebrowser/config.py" search_engine_start="c.url.searchengines = {" # use $1 if available; otherwise use default search engine search_engine=${1:-"DEFAULT"} # rest of the arguments are the search term. search_term="${@:2}" # add surrounding single quotes if not there if [[ $search_engine != "'*" ]]; then search_engine="'$search_engine" fi if [[ $search_engine != "*'" ]]; then search_engine="$search_engine'" fi # get lines after start of search engines until empty line raw_search_engines=$(awk "/$search_engine_start/,/^$/" $search_engine_file) if [[ $raw_search_engines == *$search_engine* ]]; then # get lines containing the search engine in single quotes search_engine_lines=$(echo "$raw_search_engines" | grep $search_engine) # isolate line with search engine definition definition=$(echo "$search_engine_lines" | grep --basic-regexp ',$') # extract template from single quotes template=$(echo $definition | awk --field-separator "'" '{print $4}') else echo &gt;&amp;2 Search engine not found. exit 1 fi # print template if no search term is given if [[ -z $search_term ]]; then echo $template exit 0 fi # replace all {}'s with search term echo $template | sed "s/{}/$search_term/g" </code></pre> <p>I'm not familiar with code style conventions and best practices in Bash scripts. <code>sed</code> and <code>awk</code> look very powerful, but I don't know when their use is appropriate. I also want to know how I can change the script to be POSIX-compliant.</p> <p>Any suggestions for improving my script are very welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T09:03:47.930", "Id": "238408", "Score": "2", "Tags": [ "bash" ], "Title": "Qutebrowser Searchengine Script" }
238408
<p>I have a function called <code>postprocess</code> that applies while loop condition to find for <code>-</code> and <code>alphabets</code> to each dataframe row. <code>postprocess</code> looks like this:</p> <pre><code>def postprocess(description, start_index, end_index): if (start_index &gt; 0) &amp; (start_index &lt; len(description)): while bool(re.match(r"\w|\'|-", description[start_index - 1])) &amp; bool( re.match(r"\w|\'|-", description[start_index]) ): start_index = start_index - 1 if new_start == 0: break description = description[new_start:new_end] return description </code></pre> <p>For example the <code>description</code> is <code>credit payment velvet-burger</code> and the <code>start_index</code> is 7 and <code>end_index</code> is 12. So <code>description[start_index]</code> will be <code>b</code> Which is the <code>b</code> in <code>burger</code> will be run in a while loop by tracing backwards to return the target substring we want to see because <code>burger</code> is not complete as we want the word <code>velvet-</code> also. After running <code>postprocess</code> we will get <code>velvet-burger</code>. The complete code looks like this:</p> <pre><code>df["target_substring"] = df.apply(lambda x: postprocess( x["description"], x["start_index"], x["end_index"]+1), axis=1) </code></pre> <p>Is there a better way to write this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T10:22:45.617", "Id": "467557", "Score": "0", "body": "Why using *bitwise and* `&` instead of explicit **`and`** ?? Also, fix indentations in your code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:01:04.737", "Id": "467578", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T03:04:20.200", "Id": "467679", "Score": "0", "body": "@RomanPerekhrest `bitwise and &` is used instead of `and` is because both operators gives expected results thus no second thought has been put into this. I applied black formatting to my code and it is hard to adjust indentations to what it is in real python format while grouping the code in the ``` section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T11:40:01.683", "Id": "473257", "Score": "0", "body": "I don't quite understand your question but it sounds interesting. Can you please give a self-contained example program that I can run that demonstrates the expected output?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T09:38:03.900", "Id": "238410", "Score": "1", "Tags": [ "python", "performance", "algorithm", "pandas" ], "Title": "Using pandas .apply to while loop through every row of the dataframe to get to intended substring given starting and ending index of a string" }
238410
<h2>A Brief Context</h2> <p>I recently gave an interview in a company where I was asked this particular question. After the interview was over, the HR gave the feedback that my solution (is correct programmatically) but is monolithic and not scalable. <strong>The interview was for frontend developer 2</strong>.</p> <hr> <h2>Question</h2> <p>Suppose there is a company which does some analytics work and returns data. The company (let's say X) gets a stream of numbers and it calculates average at that instant for all numbers received and returns the average. There could be other companies (let's say Y) which can ask for the average.</p> <blockquote> <p>Data:&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;5&nbsp;&nbsp;7&nbsp;&nbsp;9<br> Avg:&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5</p> </blockquote> <p>So, in the above example, the average are calculated by company X. </p> <ul> <li>After first no, average is 1, </li> <li>After second no (i.e. 3), average is 2 ((3+1)/2) and so on </li> </ul> <p>At any point in time, companies are only concerned about average at that time (basically, if average is asked after data value 5, you only need to return 3) </p> <p>The <em>geeksforgeeks</em> link for problem is <a href="https://www.geeksforgeeks.org/average-of-a-stream-of-numbers/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/average-of-a-stream-of-numbers/</a></p> <h3>Complexity</h3> <p>The solution needs to be O(1) time and O(1) space</p> <hr> <h2>My solution:</h2> <p>I wrote a <code>closure in Javascript</code> to save the current average and total number of values encountered so far. Then wrote another function to call it by passing some parameters. The parameters decide whether I should be updating the average or returning it.</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>function analytics() { const data = { avg: 0, //the average at that instant totalPoints: 0 //total number of values encountered till that point } return function(value) { //if value is not present, return the avg if (!value) { return data.avg } const newTotal = data.avg * data.totalPoints + value const newTotalP = data.totalPoints + 1 //update the value for next usage data.avg = newTotal / newTotalP data.totalPoints = newTotalP return data.avg } } fn = analytics() /* param = { type: //Company Names value: //Value to update } */ function y({ type, value }) { if (["Y"].indexOf(type) &gt;= 0) { return fn() } else if (["X"].indexOf(type) &gt;= 0) { return fn(value) } } console.log("get avg", y({ type: "Y" })) console.log("update avg", y({ type: "X", value: 1 })) console.log("update avg", y({ type: "X", value: 3 })) console.log("update avg", y({ type: "X", value: 5 })) console.log("get avg", y({ type: "Y" })) console.log("update avg", y({ type: "X", value: 7 })) console.log("update avg", y({ type: "X", value: 9 })) console.log("get avg", y({ type: "Y" }))</code></pre> </div> </div> </p> <h3>My concerns/doubts:</h3> <ul> <li>What did I miss here so that solution is not scalable</li> <li>Any use cases when it might cause issues</li> <li>How can it be re-written to make it scalable</li> </ul> <h3>Things the can be assumed won't cause any issues</h3> <ul> <li>Need not worry about precision issues while calculating the average</li> <li>Need not worry about issues due to Number datatype not able to accomodate very large values</li> <li>Data validation issues</li> <li>Variable names etc (I re-wrote the solution again for codereview, so some names are not correct)</li> </ul> <p>Hope, I am able to explain the situation properly and would like to get more insights here. Also, let me know if anyone needs any further explanation or something is missing</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:56:34.153", "Id": "467611", "Score": "1", "body": "I've got 2 concerns about your current solution:\n1. It doesn't handle 0 at all, the spec says \"all numbers\" not \"all positive integers\", you should try to accommodate any valid number.\n2. There's nothing saying the average is always a whole number, which could given sufficient inputs cause you serious problems. It's still constant time to store the total and `return total/numEntries`." } ]
[ { "body": "<p>This is a good first-cut solution to the functional requirement of stated question. However, when you look at it as production code related to two companies (<code>X</code> and <code>Y</code>) these points arise:</p>\n\n<ol>\n<li><p><strong>Monolithic</strong>: The code should be well demarcated across <code>X</code> and <code>Y</code> company logic. A single <code>analytics</code> <code>function</code> is processing all of the logic with an (admittedly, nice) <code>value</code> control. This has merged the implementation into one piece of code. Say, <code>Y</code> no longer needs the average or, maybe needs something else. Change in code for <code>Y</code> will need to engage with the primary logic of <code>X</code>'s code.</p></li>\n<li><p><strong>Scaling</strong>: Imagine a new company <code>Z</code> wants to get not just the average but also the number of data points seen by <code>X</code> (the <code>totalPoints</code>). Changing this monolithic <code>analytics</code> code would engage with all of the existing logic.</p></li>\n</ol>\n\n<p>These are probably not the only points (and they are also both associated with monolithic and scaling issues). I am just trying to imagine some scaling paths and outline the monolithic-nature of this solution.</p>\n\n<p>To get a fair view of this, consider some changes in the requirements and attempt to modify the code to incorporate them. The complexity required in the edit should be reasonably comparable to the requirement (not higher). Contact of the edit with other parts of the implementation should be minimal.</p>\n\n<p>From a different standpoint, this code would be called a prototype of the logic. The production version would need to handle aspects beyond functionality (like: maintainability, scaling, business-logic separation, readability too).</p>\n\n<p>I wonder if you were asked further questions by the interviewer after reading this program. Were they alluding towards these points.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T09:04:27.453", "Id": "468538", "Score": "0", "body": "A lot of this makes sense and now I am able to understand the interviewer's view point. There was not a lot of time remaining during interview, so we didn't have much discussion. I recently got the detailed feedback where interviewer was expecting class based approach exposing 2 different methods (one to update and one to return value) which clearly aligns with your explanation also. Thanks for help!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-11T17:24:23.097", "Id": "238723", "ParentId": "238416", "Score": "2" } }, { "body": "<p>After getting detailed feedback from the company, below given is the solution which company expected. This also matched with all the points which <code>nik</code> has explained (the accepted answer above).</p>\n\n<ul>\n<li><p>Create a class with 2 different methods. One to update the average (setAverage here) used by company X and other to get the average (getAverage here) which can be used by companies such as Y.</p></li>\n<li><p>By this approach, separations of concerns is there. Similarly if another company Z wants no of values, a new method can be added without modifying the existing functionalities</p></li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Analytics {\n constructor() {\n this.average = 0\n this.noOfValues = 0\n }\n setAverage(value){\n const total = value + this.average*this.noOfValues\n const average = total/(this.noOfValues + 1)\n this.average = average\n this.noOfValues = this.noOfValues + 1\n return average\n }\n getAverage(){\n return this.average\n }\n}\n\nconst analytics = new Analytics()\n\nconsole.log(\"setAverage, no 1: \", analytics.setAverage(1))\nconsole.log(\"average is\", analytics.getAverage())\nconsole.log(\"setAverage, no 3: \", analytics.setAverage(3))\nconsole.log(\"average is\", analytics.getAverage())\nconsole.log(\"setAverage, no 5: \", analytics.setAverage(5))\nconsole.log(\"setAverage, no 7: \", analytics.setAverage(7))\nconsole.log(\"average is\", analytics.getAverage())\nconsole.log(\"average is\", analytics.getAverage())\nconsole.log(\"setAverage, no 10: \", analytics.setAverage(10))\nconsole.log(\"average is\", analytics.getAverage())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-24T05:34:53.163", "Id": "239345", "ParentId": "238416", "Score": "1" } } ]
{ "AcceptedAnswerId": "238723", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:04:34.513", "Id": "238416", "Score": "3", "Tags": [ "javascript", "interview-questions" ], "Title": "Finding average of stream of numbers" }
238416
<p>This is for an API and I want to optimize this because it has 2 for loops followed by another 2 for loops and it is taking 4 hours for 40000 rows in the database.</p> <p>The object obtained after the request to the API is a nested dictionary. Is there a faster way to go through a nested dictionary with lists and more dictionaries with more lists within, than using nested for loops?</p> <p>I have to analyze more than 500 000 files and for different transportation modes so it will take me 1 week to run this code for all the modes. Is there some way to optimize it?</p> <p>I am looking for a guideline or a methodology to follow. I am not a developer or software engineer and new to Python.</p> <pre><code>import urllib import json import requests import csv import pandas as pd def get_car(tripgokey,database): tripgo_key='xxxxxx' mode ='me_car' database=pd.read_csv('tripgo_get_car.csv') for ind, row in database.iterrows(): orig_cord=row[1] dest_cord=row[2] dep_time=row[3] # print([orig_cord,dest_cord,dep_time]) URL= 'https://api.tripgo.com/v1/routing.json?from=('+orig_cord+')&amp;to=('+dest_cord+')&amp;modes='+mode+'&amp;v=11&amp;locale=en&amp;departAfter='+str(dep_time)+'&amp;ir=true' headers={ 'Accept': 'application/json', 'X-TripGo-Key': tripgo_key } TripGoData=requests.get(URL,headers=headers).json() print (URL) if 'groups'and'segmentTemplates'in TripGoData: bestTrip={} #Choose the best Trip for Group in TripGoData['groups']: for Trip in Group['trips']: if Trip['depart'] &gt;=dep_time: if bestTrip == {}: bestTrip=Trip elif Trip['arrive']&lt;bestTrip['arrive']: # It is prefer to arrive early rather than a longer trip bestTrip=Trip #Get the General Information for the BEST TRIP database.loc[ind,"CO2"]= bestTrip['carbonCost'] database.loc[ind,"Total_Trip_Time"]=(int(bestTrip['arrive'])-int(bestTrip['depart']))/60 database.loc[ind,"TotalCost"]=bestTrip['moneyCost'] #Get the individual information for each segment in the BEST TRIP for Segment in bestTrip['segments']: for Template in TripGoData['segmentTemplates']: if Template['hashCode']==Segment['segmentTemplateHashCode']: if Template['modeInfo']['identifier']=='me_car': database.loc[ind,"Car_Distance"]=int(Template['metres'])/1000 database.loc[ind,"Car_Cost"]=Template['localCost']['cost'] database.loc[ind,"Car_Travel_Time"]=(int(Segment['endTime'])-int(Segment['startTime']))/60 elif "stationary_parking"in Template['modeInfo']['identifier']: if "onstreet"in Template['modeInfo']['identifier']: database.loc[ind,"Parking"]="onstreet" else: database.loc[ind,"Parking"]="offstreet" if 'localCost' in Template: database.loc[ind,"Cost_Parking"]=Template['localCost']['cost'] else: database.loc[ind,"Cost_Parking"]=0 else: database.loc[ind,"Walking_Distance"]=int(Template['metres'])/1000 database.loc[ind,"Walking_Travel_Time"]=(int(Segment['endTime'])-int(Segment['startTime']))/60 elif 'error' in TripGoData: if 'errorCode' in TripGoData: database.loc[ind,"DATA_STATUS"]="Error: "+str(TripGoData['errorCode'])+"--&gt;"+TripGoData['error'] else: database.loc[ind,"DATA_STATUS"]="Error: "+TripGoData['error'] else: database.loc[ind,"DATA_STATUS"]="Data no available" database.to_csv('Car_Data.csv',index=False) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:54:22.360", "Id": "467571", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>Some suggestions for optimizing:</p>\n\n<ul>\n<li>Did you consider the option that the API request could be taking the longest time? Maybe it's worth it to check whether the API has an option to extract multiple records at once.</li>\n<li>It might be possible that <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html\" rel=\"nofollow noreferrer\"><code>pd.read_json</code></a> will suit your needs, but I never worked with it so you might have to figure out if nested dictionaries can be read, and if yes, how.</li>\n<li>Setting fields using <code>.loc</code> is much slower than creating a list and setting it as a column at once.</li>\n<li>A general tip: create some timers to check which part of your code is the slowest. Start with optimizing at the slowest part. You can also make use of a <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a> instead of creating timers, but that can be complicated.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:33:02.490", "Id": "238421", "ParentId": "238420", "Score": "4" } }, { "body": "<p>One way to (slightly) speed up repeated connections to the same server is to use a <a href=\"https://2.python-requests.org/en/v1.1.0/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>Session</code></a>, which keeps the connection alive.</p>\n\n<p>In addition, <code>requests</code> can take a parameter dictionary which will even take care of urlencoding for you:</p>\n\n<pre><code>import requests\n\nURL = \"https://api.tripgo.com/v1/routing.json\"\nHEADERS = {'Accept': 'application/json',\n 'X-TripGo-Key': \"XXXX\"}\n\nwith requests.Session() as session:\n ...\n for ind, (_, orig_cord, dest_cord, dep_time) in database.iterrows():\n params = {\"from\": f\"({orig_cord})\",\n \"dest\": f\"({dest_cord})\",\n \"modes\": mode,\n \"departAfter\": dep_time,\n \"v\": 11, \"locale\": \"en\", \"ir\": \"true\"}\n\n data = session.get(URL, params=params, headers=headers).json()\n ...\n</code></pre>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, by having spaces around <code>=</code> when using it for assignment and after commas, used tuple unpacking to directly set the variables in the loop instead of having to do it manually right away and used the relatively new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> to get the parenthesis around the parameters where needed.</p>\n\n<p>If the API does not support making multiple requests at once, you might also have to look into making multiple requests in parallel, e.g. using <a href=\"https://aiohttp.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\"><code>aiohttp</code></a> like I did in <a href=\"https://codereview.stackexchange.com/questions/237253/wordcloud-from-all-answers-of-a-user-here-on-cr\">this recent question of mine</a>.</p>\n\n<hr>\n\n<p>For your nested <code>for</code> loop, I'm not sure there is a better way to check all nested subentries. But you can at least make it into a <a href=\"https://djangostars.com/blog/list-comprehensions-and-generator-expressions/\" rel=\"nofollow noreferrer\">generator expression</a> that flattens it and then use the built-in <code>min</code>:</p>\n\n<pre><code>from operator import itemgetter\n\ntrips = (trip for group in data[\"groups\"] for trip in group\n if trip[\"depart\"] &gt;= dep_time)\nbest_trip = min(trips, key=itemgetter(\"arrive\"))\n</code></pre>\n\n<p>Note that <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends using <code>lower_case</code> for variables (and functions).</p>\n\n<hr>\n\n<p>This line does not do what you think it does:</p>\n\n<pre><code>if 'groups'and'segmentTemplates'in TripGoData:\n</code></pre>\n\n<p>This is parsed as </p>\n\n<pre><code>if ('groups' and 'segmentTemplates') in TrupGoData:\n</code></pre>\n\n<p>which is </p>\n\n<pre><code>if 'segmentTemplates' in TrupGoData:\n</code></pre>\n\n<p>because non-empty strings are truthy and <code>and</code> returns the last value if all values are truthy (and the first falsey value if not).</p>\n\n<p>Instead you have to use</p>\n\n<pre><code>if 'groups' in TrupGoData and 'segmentTemplates' in TrupGoData:\n</code></pre>\n\n<hr>\n\n<p>And for writing to a csv it is probably easier to use <a href=\"https://docs.python.org/3/library/csv.html#csv.DictWriter\" rel=\"nofollow noreferrer\"><code>csv.DictWriter</code></a> and return dictionaries from each row:</p>\n\n<pre><code>import csv\n\ndef get_best_trip_info(orig_cord, dest_cord, dep_time):\n data = ...\n best_trip = ...\n out = {}\n out[\"carbonCost\"] = best_trip['carbonCost']\n ...\n return out\n\n\ndatabase = ...\nwith open('Car_Data.csv', \"w\") as out_file\n writer = csv.DictWriter(out_file, [\"carbonCost\", ...])\n writer.writerows(get_best_trip_info(orig_cord, dest_cord, dep_time)\n for ind, (_, orig_cord, dest_cord, dep_time) in database.iterrows())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:41:42.427", "Id": "238429", "ParentId": "238420", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T11:48:49.350", "Id": "238420", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x" ], "Title": "Get best trip info from tripgo API and save to CSV" }
238420
<p>This code should toggle the state (open/closed) of a submenu when the associated top-level trigger is clicked. The menu should toggle for mouse clicks, keyboard events and touch events - since detecting these is not possible each case is supported separately.</p> <p>The toggle functionality should also be a11y friendly. It updates the state of <code>aria-*</code> attributes and handles moving keyboard focus where needed.</p> <p>Meaning of individual elements can be found in the comments. </p> <p>The HTML structure of the menu is:</p> <pre class="lang-html prettyprint-override"><code>&lt;ul class="site-nav__list"&gt; &lt;li class=" has-children"&gt; &lt;a class="js-toggle-submenu" href="#menutoggle-ID"&gt; &lt;span&gt;TITLE&lt;/span&gt; &lt;svg aria-hidden="true" focusable="false"&gt;&lt;use href="#chevron-down"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;ul class="submenu"&gt; &lt;li class="container"&gt; &lt;a class="submenu__item" href="URL"&gt; SUBMENU TITLE &lt;/a&gt; &lt;/li&gt; &lt;!-- ... --&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><br> The JavaScript to toggle is:</p> <pre class="lang-js prettyprint-override"><code>/** * Open and close submenus in a11y friendly way. */ ( function( $, window, document, undefined ) { const IS_DESKTOP_NAV_MQ = '(min-width: 901px)'; let $triggers = $('.js-toggle-submenu'); // init a11y attrs $triggers.each((index, trigger) =&gt; { $(trigger).attr('aria-expanded', 'false'); $(trigger).next().attr('aria-hidden', 'true'); }); /** * Check if submenu events should run. * @return {Boolean} */ function menu_should_toggle() { return window.matchMedia(IS_DESKTOP_NAV_MQ).matches; } /** * Check if a trigger's submenu is open. * Check using a11y attrs to promote the use of these over data-* or classes. * @param {jQuery} $trigger A top level link that toggles the submenu. * @return {Boolean} */ function is_open( $trigger ) { return $trigger.is('[aria-expanded="true"]'); } /** * Open a specific submenu based on the trigger link. * @param {jQuery} $trigger A top level link that toggles the submenu. */ function open( $trigger ) { // 1) $trigger.attr('aria-expanded', 'true'); $trigger.next().attr('aria-hidden', 'false'); } /** * Close a specific submenu based on the trigger link. * @param {jQuery} $trigger A top level link that toggles the submenu. */ function close( $trigger ) { // 1) $trigger.attr('aria-expanded', 'false'); $trigger.next().attr('aria-hidden', 'true'); } /** * Close the currently open submenu. */ function close_expanded_menu() { let $trigger = $triggers.filter('[aria-expanded="true"]'); if ( $trigger.length ) { close($trigger); } } /** * Close the currently open submenu when Esc is passed. * Should be binded to a keydown event on the document. * @param {Event} event A keyboard event. */ function close_on_esc( event ) { if ( 'Escape' !== event.key ) { return; } close_expanded_menu(); $(document).unbind('keydown', close_on_esc); } /** * MOUSE SUPPORT * Click toggles state of submenu */ $triggers.click((event) =&gt; { if ( !menu_should_toggle() ) { return; } let $trigger = $(event.target); if ( !$trigger.is('.js-toggle-submenu') ) { $trigger = $trigger.closest('.js-toggle-submenu'); } if ( $trigger.is('[aria-expanded="false"]') ) { close_expanded_menu(); open($trigger); } else { close($trigger); } $(document).bind('keydown', close_on_esc); event.preventDefault(); }); /** * KEYBOARD SUPPORT * * Should be able to `tab` across all top level menu items. * Does not open the submenu when a top level item is focused. * * Pressing `enter` should expand the submenu *but* not move focus into it. * 1) Submenu state is controlled by aria-expanded attr on * top level item ensuring a11y attrs must be set to use it. * Focus does not move. * * Pressing `tab` once open should move to first submenu item. * We get this "for free" due to our submenu links * directly following the top level link in the DOM structure. * * If `Esc` is pressed while in the submenu, it should collapse and * focus returns to the top level item. * See 2) * * If `tab` is pressed on the last submenu item, submenu should close * and focus transferred to the next top level item. * 3) Checks for focus on the next tabbable element to detect this. * * If `Shift` + `tab` is pressed on the first submenu item, * focus moves naturally to the top level item. * If pressed again, submenu should close and focus moves * to previous top level item/previous tabbable element * 4) Checks for focus on the previous tabbable element to detect this. */ $triggers.on( 'keydown', function(event) { if ( !menu_should_toggle() ) { return; } // 1) if ( 'Enter' !== event.key ) { return; } let $trigger = $(event.target); if ( $trigger.is('[aria-expanded="false"]') ) { listen_keyboard_events($trigger, 'bind'); open($trigger); } else { listen_keyboard_events($trigger, 'unbind'); close($trigger); } event.preventDefault(); return false; } ); /** * Listen for keyboard events on a specific trigger and submenu. * @param {jQuery} $trigger A top level link that toggles the submenu. * @param {String} action bind|unbind */ function listen_keyboard_events( $trigger, action = 'bind' ) { if ( 'bind' !== action &amp;&amp; 'unbind' !== action ) { return; } function keyboard_on_esc( event ) { if ( 'Escape' !== event.key ) { return; } // Move focus back to trigger if inside the submenu if ( $trigger.next().is( $(document.activeElement).closest('.submenu') ) ) { focusOnElement($trigger); } close($trigger); listen_keyboard_events($trigger, 'unbind'); } function keyboard_on_blur( event ) { close($trigger); listen_keyboard_events($trigger, 'unbind'); } // @uses lib.focus.js let $prev_tab = getPrevTabbable($trigger); let $next_tab = getNextTabbable($trigger); // Access function from string param $(document)[action]('keydown', keyboard_on_esc); // Menu has been blurred if either of these get focus $prev_tab[action]('focus', keyboard_on_blur); // 4) $next_tab[action]('focus', keyboard_on_blur); // 3) } /** * TOUCH SUPPORT * * 5) Tapping on an item will open the submenu associated with it. * 5.1) Tapping on the same item again will close it. * 6) Tapping on any other item will close the active submenu. * 7) Tapping outside of the submenu will close it. * 8) Zoom, or other multi-touch gestures should not open or close the menu. */ $triggers.on( 'touchend', function(event) { if ( !menu_should_toggle() ) { return; } // 8) if ( event.touches.length &gt; 1 ) { return; } // sanitise target in case child element received event let $trigger = $(event.target); if ( !$trigger.is('.js-toggle-submenu') ) { $trigger = $trigger.closest('.js-toggle-submenu'); } // 5.1) if ( is_open($trigger) ) { close($trigger); } else { // 6) close_expanded_menu(); // 5) open($trigger); } event.preventDefault(); return false; } ); } )( jQuery, window, document ); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:53:21.327", "Id": "238425", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Toggle submenu state on click, keydown and touch with a11y support" }
238425
<p>I've been asigned to a project no dev has touched in a long time. It's an ASP.NET MVC 4 application.<br> It appeared to be well coded, but had no testing and the database migration folder is not present.<br> For further development I'm given time for minimal testing to ensure that my changes won't break the code. <br> When writing a Unit Test for a controller I noticed, that the code is not testable, because not only are results returned, but there is a lot of DB magic going on.<br> Some sample:<br></p> <pre><code>[HandleError] public class AccountController : Controller { private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public IFormsAuthenticationService FormsService { get; set; } public IMembershipService MembershipService { get; set; } protected override void Initialize(RequestContext requestContext) { // ... Init code } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { { if (ModelState.IsValid) { var dbEntities = new PortalEntity(); _logger.Debug("User " + model.UserName + " is trying to login"); var userId = (from us in dbEntities.aspnet_Users where us.UserName.Equals(model.UserName) select us.UserId).FirstOrDefault&lt;Guid&gt;(); var userprojects = (from up in dbEntities.T_USER_PROJECT where up.UPR_USER_ID.Equals(userId) select up); //NEU alle Benutzer können sich anmelden var projectId = (from u in dbEntities.T_PROJECT join v in userprojects on u.PRO_ID equals v.UPR_PROJECT_ID where u.PRO_IS_ACTIVE select u.PRO_ID).FirstOrDefault(); var loginAllowed = dbEntities.T_PROJECT.Any(x =&gt; x.PRO_ID.Equals(projectId) &amp;&amp; x.PRO_STARTED); //loginAdmin = ; var userRole = dbEntities.aspnet_Roles.Single(x =&gt; x.RoleName.Equals("Administrators")).RoleId; var isUserAdmin = dbEntities.aspnet_Users.Where(x =&gt; x.aspnet_Roles.Any(y =&gt; y.RoleId.Equals(userRole))).Any(x =&gt; x.UserId.Equals(userId)); if (MembershipService.ValidateUser(model.UserName, model.Password) &amp;&amp; (loginAllowed || isUserAdmin)) { _logger.Debug("User " + model.UserName + " existiert und möchte sich nun einloggen"); FormsService.SignIn(model.UserName, model.RememberMe); if (isUserAdmin) return RedirectToAction("Index", "Admin"); return RedirectToAction("Edit", "Stage1"); } var errMsg = ViewResources.ErrorUserOrPasswordWrong; if (!loginAllowed &amp;&amp; !isUserAdmin) { errMsg = ViewResources.ErrorNoEntryAllowed; } ModelState.AddModelError(string.Empty, errMsg); } // If we got this far, something failed, redisplay form return View(model); } } } </code></pre> <p>I abstracted a class <code>AccountService</code> that handels all db access:</p> <pre><code>private class AccountService { private PortalEntity dbEntities = new PortalEntity(); public Guid GetUserId(LogOnModel model) { Guid userId = (from us in dbEntities.aspnet_Users where us.UserName.Equals(model.UserName) select us.UserId).FirstOrDefault&lt;Guid&gt;(); return userId; } public IQueryable&lt;T_USER_PROJECT&gt; GetProjectsForUserId(Guid userId) { IQueryable&lt;T_USER_PROJECT&gt; userprojects = (from up in dbEntities.T_USER_PROJECT where up.UPR_USER_ID.Equals(userId) select up); return userprojects; } public int GetProjectId(IQueryable&lt;T_USER_PROJECT&gt; userprojects) { int projectId = (from u in dbEntities.T_PROJECT join v in userprojects on u.PRO_ID equals v.UPR_PROJECT_ID where u.PRO_IS_ACTIVE select u.PRO_ID).FirstOrDefault(); return projectId; } public bool IsLoginAllowed(int projectId) { bool loginAllowed = dbEntities.T_PROJECT.Any(x =&gt; x.PRO_ID.Equals(projectId) &amp;&amp; x.PRO_STARTED); return loginAllowed; } public Guid GetUserRoleGuid() { Guid userRole = dbEntities.aspnet_Roles.Single(x =&gt; x.RoleName.Equals("Administrators")).RoleId; return userRole; } public bool IsUserAdmin(Guid userRole, Guid userId) { bool isUserAdmin = dbEntities.aspnet_Users.Where(x =&gt; x.aspnet_Roles.Any(y =&gt; y.RoleId.Equals(userRole))).Any(x =&gt; x.UserId.Equals(userId)); return isUserAdmin; } } </code></pre> <p>Resulting in the new LogOn method:</p> <pre><code>[HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { AccountService service = new AccountService(); { if (ModelState.IsValid) { _logger.Debug("User " + model.UserName + " is trying to login"); var userId = service.GetUserId(model); var userprojects = service.GetProjectsForUserId(userId); var projectId = service.GetProjectId(userprojects); var loginAllowed = service.IsLoginAllowed(projectId); var userRole = service.GetUserRoleGuid(); var isUserAdmin = service.IsUserAdmin(userRole, userId); if (MembershipService.ValidateUser(model.UserName, model.Password) &amp;&amp; (loginAllowed || isUserAdmin)) { _logger.Debug("User " + model.UserName + " existiert und möchte sich nun einloggen"); FormsService.SignIn(model.UserName, model.RememberMe); if (isUserAdmin) return RedirectToAction("Index", "Admin"); return RedirectToAction("Edit", "Stage1"); } var errMsg = ViewResources.ErrorUserOrPasswordWrong; if (!loginAllowed &amp;&amp; !isUserAdmin) { errMsg = ViewResources.ErrorNoEntryAllowed; } ModelState.AddModelError(string.Empty, errMsg); } // If we got this far, something failed, redisplay form return View(model); } } </code></pre> <p>Issues I'm having:</p> <ul> <li>Languages english and german are mixed in both comments and logs (prefer eng > ger?)</li> <li>Magic strings (<code>x.RoleName.Equals("Administrators")</code>), what to do with those?</li> <li>I made <code>AccountService</code> a private class, should I define a base class or interface <code>Service</code>?</li> <li>Should I be putting all these services into a dir <code>/services</code>?</li> <li>Is this approach even viable / necessary?</li> <li>Do I have to DI a service in every method or one per controller?</li> </ul> <p>Any feedback is appriciated.</p>
[]
[ { "body": "<p>I guess you'll find a lot of redundancy in the code since its been held by the controllers. </p>\n\n<p>Your idea of making a service is a good idea, you may need to add different services, but at the end you'll have services that can be reused, avoiding code redundancy. This would help ease things more and more. So, continue in this approach. Interface or abstract, that depends on your implementation. Go with what you see best fits your needs. You can also define both if needed. And yes, defining them under a new namespace, would be better. </p>\n\n<p>Do you need to do all that ? it depends. If the application will be continued and there is no new migrations. Then, I don't think it needs that, you might make changes whenever needed (like do one controller on each time you're requested to make changes on any of them). little by little, you'll have a full updated project. </p>\n\n<p>However, if there is another migration process, then you need to reconsider your choices, see what needs your efforts and what's not. </p>\n\n<p>For the magic strings, use <code>Enum</code>. </p>\n\n<p>I forgot the first issue, for which language you should favor over the other, mostly English is your choice, but from a back experience, If there is some work guidelines for developers, then it should be mentioned in that guidelines, if not, then see what is the official communication language in your work (emails ..etc) and enforce it in the code as well. You can do your comments in both languages (each comment would hold English and translation to German). I usually use English even if the application comments are written in a different language, because : </p>\n\n<ol>\n<li>English is an official language in most companies in my country. </li>\n<li>I'm coding in English, why should I write comments in different language ? it would be an awkward code style ;).</li>\n<li>It's a good way to practice your language and keep it rolling, specially if you're in a place where it's rarely used. </li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:06:15.907", "Id": "238433", "ParentId": "238426", "Score": "3" } } ]
{ "AcceptedAnswerId": "238433", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T12:59:45.527", "Id": "238426", "Score": "1", "Tags": [ "c#", "unit-testing", "asp.net", "asp.net-mvc", "controller" ], "Title": "Decoupling of validation and data access in ASP.NET" }
238426
<p>I'm very new to Javascript...</p> <p>Below is my code to convert Array to key/value JSON. Would like to know if there is a better way to achieve this or if I use any know bad practices.</p> <p>An input: <code>[10, [20.1, 20.2], 1]</code></p> <p>The output: <code>{"channel_id":10, "payload":[20.1,20.2], "sequence":1}</code></p> <p>My working code to generate the output:</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 myArray = [10, [20.1, 20.2], 1] class MyObject { constructor(a, b, c) { this.channel_id = a, this.payload = b, this.sequence = c; } } myObject = new MyObject(myArray[0], myArray[1], myArray[2]) console.log(JSON.stringify(myObject))</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T20:19:04.843", "Id": "467645", "Score": "0", "body": "I've updated the post to make it clear that it complete and functions correctly. Thanks." } ]
[ { "body": "<ul>\n<li><p>Not sure that a class definition makes a lot of sense here since you don’t really have any real behavior being defined in this class. </p></li>\n<li><p>Destructuring can also help you populate variables from the input array directly.</p></li>\n<li><p>camelCase is generally preferred in JS vs. snake_case. </p></li>\n</ul>\n\n<p>For example you might simplify to something like this:</p>\n\n<pre><code>const conversionFn = ( [ channelId, payload, sequence ] ) =&gt; { \n return { channelId, payload, sequence };\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:00:07.200", "Id": "238432", "ParentId": "238428", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:21:59.687", "Id": "238428", "Score": "2", "Tags": [ "javascript", "beginner" ], "Title": "Array to key/value JSON conversion" }
238428
<p>I wrote a small C++ program to monitor activity (messages sent) on a network and display the current status of the machines. The assumptions are as follows:</p> <p>There exist sessions on a network. A session is made up of one master machine and several slave machines sending messages. On a startup masters and slaves both broadcast a message and then send a regular heartbeat messages. These two message types use a similar protocol but are sent on different ports. Machines can start up and shut down in any order. An active machine can crash and then recover by sending a startup message again. There may be multiple sessions (multiple master and slave networks) active on a network at any one time.</p> <hr> <p>Protocol 1 - each message is contained within a single data packet and these are broadcast over UDP port 7106. The message is sent as a plaintext string.</p> <p>Master sends this on startup: <strong>SESSION|sessionname|creator|machineid1|machineid2|machineid3|machinen</strong></p> <p>Example: <strong>SESSION|my session|adamspc|lukespc|mattspc</strong></p> <p>Slaves sends this on startup: <strong>PC|machineid|sessionname</strong></p> <p>Example: <strong>PC|alexspc|my session</strong></p> <p>There are other message types sent over the protocol that should be ignored.</p> <hr> <p>Protocol 2 - each message is contained within a single data packet and these are broadcast over UDP port 7104. The message is sent as a plaintext string.</p> <p>Every machine sends this at least once a second <strong>PCSTATUS|machineid|version|fps</strong></p> <p>Example: <strong>PCSTATUS|johnspc|11.2|60</strong></p> <p>There are other message types sent over the protocol that should be ignored.</p> <p>state diagram for each machine is as follows:</p> <p><a href="https://i.stack.imgur.com/xDGhA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xDGhA.png" alt="enter image description here"></a></p> <p>I would appreciate any feedback, what should be improved, added etc. Could be just regarding some parts (socket handling, messages processing, way of capturing data etc).</p> <pre><code>#include &lt;sys/select.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;map&gt; #define PORT 7104 #define PORT2 7106 #define MAXLINE 1024 using namespace std; int max(int x, int y) { if (x &gt; y) return x; else return y; } struct machInfo { string name; string lastHeartBeatTs; machInfo(const string&amp; name) : name(name) {} }; struct sessInfo { string name; string master; vector&lt;string&gt; slaves; sessInfo(const string&amp; name) : name(name) {} }; struct netInfo { map&lt;string, sessInfo&gt; sessions; map&lt;string, machInfo&gt; machines; void procDataSock1(string&amp; data); void procDataSock2(string&amp; data); void printInfo() { // TODO print info about the network } }; // if it's a heartbeat msg then capture the timestamp void netInfo::procDataSock1(string&amp; data) { string delimiter = "|", msgType, machine; size_t pos = 0; pos = data.find(delimiter); if (pos != string::npos) { msgType = data.substr(0, pos); data.erase(0, pos + delimiter.length()); } else return; if (msgType == "PCSTATUS") { pos = data.find(delimiter); if (pos != string::npos) { machine = data.substr(0, pos); } else return; map&lt;string, machInfo&gt;::iterator it = machines.find(machine); if ( it != machines.end() ) { time_t _tm = time(NULL); struct tm * curtime = localtime ( &amp;_tm ); string ts(asctime(curtime)); it-&gt;second.lastHeartBeatTs = ts; } } } // if it's a SESSION or MESSAGE msg, then capture the available info and store it void netInfo::procDataSock2(string&amp; data) { string delimiter = "|", msgType, session, machine, master; size_t pos = 0; pos = data.find(delimiter); if (pos != string::npos) { msgType = data.substr(0, pos); data.erase(0, pos + delimiter.length()); } else return; if (msgType == "SESSION") { pos = data.find(delimiter); if (pos != string::npos) { session = data.substr(0, pos); data.erase(0, pos + delimiter.length()); } else return; pos = data.find(delimiter); if (pos != string::npos) { master = data.substr(0, pos); data.erase(0, pos + delimiter.length()); } else return; map&lt;string, sessInfo&gt;::iterator it1 = sessions.find(session); if ( it1 == sessions.end() ) { sessions.insert(pair&lt;string, sessInfo&gt;(session, sessInfo(session))); } else it1-&gt;second.master = master; map&lt;string, machInfo&gt;::iterator it2 = machines.find(master); if ( it2 == machines.end() ) { machines.insert(pair&lt;string, machInfo&gt;(master, machInfo(master))); } } else if (msgType == "PC") { pos = data.find(delimiter); if (pos != string::npos) { machine = data.substr(0, pos); data.erase(0, pos + delimiter.length()); } else return; session = data; map&lt;string, sessInfo&gt;::iterator it1 = sessions.find(session); if ( it1 == sessions.end() ) { sessions.insert(pair&lt;string, sessInfo&gt;(session, sessInfo(session))); } map&lt;string, machInfo&gt;::iterator it2 = machines.find(machine); // if first startup message we need to add it to machines if ( it2 == machines.end() ) { machines.insert(pair&lt;string, machInfo&gt;(machine, machInfo(machine))); it1 = sessions.find(session); // will always evaluate to true if ( it1 != sessions.end() ) { it1-&gt;second.slaves.push_back(machine); } } } } int main() { netInfo ni; int sockfd, sockfd2; struct sockaddr_in servaddr, servaddr2; if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) &lt; 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } if ( (sockfd2 = socket(AF_INET, SOCK_DGRAM, 0)) &lt; 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&amp;servaddr, 0, sizeof(servaddr)); memset(&amp;servaddr2, 0, sizeof(servaddr2)); servaddr.sin_family = AF_INET; // IPv4 servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORT); servaddr2.sin_family = AF_INET; // IPv4 servaddr2.sin_addr.s_addr = INADDR_ANY; servaddr2.sin_port = htons(PORT2); if ( bind(sockfd, (const struct sockaddr *)&amp;servaddr, sizeof(servaddr)) &lt; 0 ) { perror("bind failed"); exit(EXIT_FAILURE); } if ( bind(sockfd2, (const struct sockaddr *)&amp;servaddr2, sizeof(servaddr2)) &lt; 0 ) { perror("bind failed"); exit(EXIT_FAILURE); } int cnt = 1; while (true) { // print info about the system every 20 messages if (cnt++ % 20 == 0) ni.printInfo(); fd_set socks; FD_ZERO(&amp;socks); FD_SET(sockfd, &amp;socks); FD_SET(sockfd2, &amp;socks); int nsocks = max(sockfd, sockfd2) + 1; if (select(nsocks, &amp;socks, (fd_set *)0, (fd_set *)0, 0) &gt;= 0) { if (FD_ISSET(sockfd, &amp;socks)) { // handle socket 1 char buffer[MAXLINE]; struct sockaddr_storage src_addr; socklen_t src_addr_len=sizeof(src_addr); int n = recvfrom( sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&amp;src_addr,&amp;src_addr_len); if (n==-1) { cout &lt;&lt; "error... " &lt;&lt; endl; } else if (n==sizeof(buffer)) { cout &lt;&lt; "datagram too large for buffer" &lt;&lt; endl; } else { buffer[n] = '\0'; string data(buffer); ni.procDataSock1(data); } } if (FD_ISSET(sockfd2, &amp;socks)) { // handle socket 2 char buffer[MAXLINE]; struct sockaddr_storage src_addr; socklen_t src_addr_len=sizeof(src_addr); int n = recvfrom( sockfd2, buffer, sizeof(buffer), 0, (struct sockaddr*)&amp;src_addr,&amp;src_addr_len); if (n==-1) { cout &lt;&lt; "error... " &lt;&lt; endl; } else if (n==sizeof(buffer)) { cout &lt;&lt; "datagram too large for buffer" &lt;&lt; endl; } else { buffer[n] = '\0'; string data(buffer); ni.procDataSock2(data); } } } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T10:27:51.260", "Id": "467698", "Score": "0", "body": "Is your message protocol obligatory or optional ? Maybe json and strongly typed messaging would be safer." } ]
[ { "body": "<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Standard advice is to avoid depriving yourself of the benefits of the <code>std</code> namespace like this. Prefer to import <em>just the names you need</em>, into the <em>smallest reasonable scope</em>. Or just qualify names as you use them; <code>std</code> is intentionally a very short name.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int max(int x, int y) {\n if (x &gt; y) return x; else return y;\n}\n</code></pre>\n</blockquote>\n\n<p>This seems unnecessary, given that we can simply use <code>std::max()</code> (and might even start doing so unintentionally, given the <code>using</code> declaration above).</p>\n\n<hr>\n\n<blockquote>\n<pre><code>machInfo(const string&amp; name) : name(name) {}\n</code></pre>\n</blockquote>\n\n<p>If we pass by value, we can avoid copying when given an rvalue <code>name</code>:</p>\n\n<pre><code>machInfo(std::string name)\n : name{std::move(name)}\n{}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>void procDataSock1(string&amp; data);\nvoid procDataSock2(string&amp; data);\n</code></pre>\n</blockquote>\n\n<p>Naming is hard - but surely we can do better than this??</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (pos != string::npos) {\n machine = data.substr(0, pos);\n }\n else\n return;\n</code></pre>\n</blockquote>\n\n<p>It's easier to read if we turn this around, to deal with the problem case first:</p>\n\n<pre><code> if (pos == string::npos) {\n return;\n }\n\n machine = data.substr(0, pos);\n</code></pre>\n\n<p>We now no longer need <code>else</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> map&lt;string, machInfo&gt;::iterator it = machines.find(machine);\n</code></pre>\n</blockquote>\n\n<p><code>auto</code> is useful for types like this:</p>\n\n<pre><code> auto const it = machines.find(machine);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> map&lt;string, sessInfo&gt;::iterator it1 = sessions.find(session);\n if ( it1 == sessions.end() ) {\n sessions.insert(pair&lt;string, sessInfo&gt;(session,\n sessInfo(session)));\n }\n</code></pre>\n</blockquote>\n\n<p>That's exactly equivalent to <code>try_emplace()</code>:</p>\n\n<pre><code> sessions.try_emplace(session, session);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> exit(EXIT_FAILURE);\n</code></pre>\n</blockquote>\n\n<p><code>std::exit</code> and <code>EXIT_FAILURE</code> are both declared by <code>&lt;cstdlib&gt;</code>, but it hasn't been included. Given that this is <code>main()</code>, consider plain <code>return</code> instead of <code>std::exit()</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>servaddr.sin_family = AF_INET; // IPv4\n</code></pre>\n</blockquote>\n\n<p>No IPv6 support?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> perror(\"bind failed\");\n</code></pre>\n</blockquote>\n\n<p>Good to see use of the proper facilities here. <code>std::perror()</code> is declared in <code>&lt;cstdio&gt;</code>, so we need to include that, too.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> cout &lt;&lt; \"datagram too large for buffer\" &lt;&lt; endl;\n</code></pre>\n</blockquote>\n\n<p>Having seen nice <code>std::perror()</code> above, it's a shame that we're using the wrong stream here - error messages should certainly go to <code>std::cerr</code>, not <code>std::cout</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T19:26:23.353", "Id": "467638", "Score": "0", "body": "Small addition: Use of `std::max` will require `#include <algorithm>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T00:08:20.580", "Id": "467663", "Score": "0", "body": "Isn't `\\n` considered slightly better than `std::endl`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T11:01:28.817", "Id": "467701", "Score": "0", "body": "@Pedro, I generally agree, but often the implied `flush` can be useful when we're emitting diagnostics like this. In many cases, that's the last output before the program fails, and we'd hate for this information to be stuck in a buffer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T17:26:06.133", "Id": "238441", "ParentId": "238435", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:11:40.780", "Id": "238435", "Score": "5", "Tags": [ "c++", "websocket" ], "Title": "Monitor activity on a network" }
238435
<p>I'm still learning Python and especially Object Oriented Programming. The latter, though, seems to confuse me a lot: defining class object attributes vs instance attributes, passing arguments, using outside-of-the-class functions vs class methods, etc.</p> <p>I understand it's a rather ambiguous question I'm asking, but based on the code below I'd appreciate if someone could help me organize it more and point to logic gaps/incorrect <strong>OOP</strong> way. </p> <p>My goal is to learn OOP, blackjack game is just an example of what I've understood so far.</p> <p>P.S. Please ignore the comments, if they don't make sense to you. (I made them for a non-Python friend to help me with the same problem).</p> <pre><code>import random class Deck: """ Creating class object attributes, that will be used to build game deck """ ranks = ("Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace") suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} deck = [] def __init__(self): """ Building &amp; shuffling the deck, whenever class instance is created """ self.deck = [] # Resetting deck, whenever class instance is created for rank in self.ranks: for suit in self.suits: self.deck.append((rank, suit)) random.shuffle(self.deck) print("\n********************\nNEW GAME BEGINS NOW!\n") class Hand: """ Hand class to control each player cards, values and aces count """ def __init__(self): self.hand = [] # Starting with an empty hand for each player(class instance) self.value = 0 # Starting with 0 value for each hand self.aces_count = 0 # Starting with 0 aces for each hand def get_card(self, deck): """ Removing last(top) card from the deck and adding it to the hand :param deck: Game deck object :return: None """ self.hand.append(deck.pop()) def get_hand_value(self): """ Calculating value of the hand, adjusting to possible Aces :return: Hand value """ self.value = 0 # Resetting hand value, when method is called self.aces_count = 0 # Resetting aces count, when method is called for rank, suit in self.hand: self.value += Deck.values[rank] for rank, suite in self.hand: if rank == 'Ace': self.aces_count += 1 if self.aces_count &gt;= 1 and self.value &gt; 21: self.value = self.value - 10 * self.aces_count return self.value def reveal_cards(self, player="Player", hide=False): """ Revealing card(s) of the Player/Dealer :param player: str reference to Player's or Dealer's hand :param hide: bool; Used to hide Dealer's last card :return: None """ if hide is False: print("{} cards: {}".format(player, self.hand)) else: print("{} cards: [{}, ('????', '????')]".format(player, self.hand[0:-1])) class Bets: """ Bets class to organize Player's chips, bets and addition/subtrcation when he wins/loses """ def __init__(self, total): """ Added attributes to __init__ method to leave an option (for future) to add 2nd instance of Bets class. e.g. dealer's bets """ self.total = total # Asking player how much $$ he wants to play on self.bet = 0 # Starting with 0 bet self.betting = 1 # Flag to continue asking for a bet def win_bet(self): """ Adds bet amount to player's total :return: None """ self.total += self.bet def lose_bet(self): """ Subtracts bet amount from player's total :return: None """ self.total -= self.bet def take_bet(self): """ Validates, whether player has enough $$ to bet Reserves bet amount from player's total :return: None """ if self.total != 0: while self.betting: self.bet = int(input("Enter your bet: \n")) if self.bet == 0: print("Bet should be greater than 0!") self.take_bet() elif self.bet &gt; self.total: print("Bet cannot exceed your total amount of {}".format(self.total)) self.take_bet() else: print("Player bet is : {}".format(self.bet)) self.betting = 0 break else: print("Not enough money to play.\n") restart_game(bets) def hit_or_stand(deck, hand1, hand2, bets, limit): """ Hit or Stand function, which determines whether Player/Dealer hits or stands :param deck: Game deck object :param hand1: Player's hand object :param hand2: Dealer's hand object :param bets: Player's bets object :param limit: Defines limit for each hand to stop hitting at, list of 2 integers :return: None """ while hand1.get_hand_value() &lt; int(limit[0]): h_or_s = str(input("Hit or Stand? H / S\n")) if h_or_s[0].lower() == "h": print("Player hits &gt;&gt;&gt; ") hand1.get_card(deck.deck) if busted(hand1, hand2, bets) is False and blackjack(hand1, hand2, bets) is False: hand1.reveal_cards(player="Player", hide=False) print("Player value: {}".format(hand1.get_hand_value())) elif h_or_s[0].lower() == "s": print("Player stands...") while hand2.get_hand_value() &lt; int(limit[1]): hand2.get_card(deck.deck) if busted(hand1, hand2, bets) is False and blackjack(hand1, hand2, bets) is False: print("\nDealer hits &gt;&gt;&gt;") hand2.reveal_cards(player="Dealer", hide=True) continue else: define_winner(hand1, hand2, bets) break def drop_win(hand1, hand2, bets): """ Function checks whether player or dealer got :param hand1: Player's hand object :param hand2: Dealer's hand object :param bets: Player's bets object :return: bool True, if player/dealer got blackjack (21) """ if hand1.get_hand_value() == hand2.get_hand_value() == 21: print("BlackJack Tie on drop!") display_all_cards_and_values(hand1, hand2) continue_playing(bets) return True elif hand1.get_hand_value() == 21 and hand2.get_hand_value() &lt; 21: print("Player BlackJack on drop!") display_all_cards_and_values(hand1, hand2) bets.win_bet() continue_playing(bets) return True elif hand2.get_hand_value() == 21 and hand1.get_hand_value() &lt; 21: print("Dealer BlackJack on drop!") display_all_cards_and_values(hand1, hand2) bets.lose_bet() continue_playing(bets) return True else: return False def busted(hand1, hand2, bets): """ Function checks, whether player or dealer busted // got hand value over 21 :param hand1: Player's hand object :param hand2: Dealer's hand object :param bets: Player's bets object :return: bool True if player/dealer busted """ if hand1.get_hand_value() &gt; 21: print("Player Busted :-|") display_all_cards_and_values(hand1, hand2) bets.lose_bet() continue_playing(bets) return True elif hand2.get_hand_value() &gt; 21: print("Dealer Busted!") display_all_cards_and_values(hand1, hand2) bets.win_bet() continue_playing(bets) return True else: return False def blackjack(hand1, hand2, bets): """ Function checks, whether player or dealer got Blackjack (21) :param hand1: Player's hand object :param hand2: Dealer's hand object :param bets: Player's bets object :return: None """ if hand1.get_hand_value() == 21 and hand2.get_hand_value() &lt; 21: display_all_cards_and_values(hand1, hand2) print("Player BlackJack!") bets.win_bet() continue_playing(bets) return True elif hand2.get_hand_value() == 21 and hand1.get_hand_value() &lt; 21: display_all_cards_and_values(hand1, hand2) print("Dealer BlackJack!") bets.lose_bet() continue_playing(bets) return True else: return False def define_winner(hand1, hand2, bets): """ Function defines winner, when both player and dealer stopped hitting and haven't busted or got blackjack :param hand1: Player's hand object :param hand2: Dealer's hand object :param bets: Player's bets object :return: None """ print("\n********************\nDefining winner!\n") if hand1.get_hand_value() == hand2.get_hand_value(): print("Tie!") display_all_cards_and_values(hand1, hand2) continue_playing(bets) elif hand1.get_hand_value() &gt; hand2.get_hand_value(): print("Player Wins!") display_all_cards_and_values(hand1, hand2) bets.win_bet() continue_playing(bets) else: print("Dealer Wins!") display_all_cards_and_values(hand1, hand2) bets.lose_bet() continue_playing(bets) def continue_playing(bets): """ Function asks player, whether he wants to continue playing, considering he has enough balance :param bets: Player's bets object :return: None """ if bets.total &gt; 0: answer = str(input("Your current balance is: {} . Want to continue playing? Y / N\n".format(bets.total))) if answer[0].lower() == 'y': pass elif answer[0].lower() == "n": global playing playing = 0 else: print("Invalid Input") continue_playing(bets) else: print("Not enough money to play :(\n") restart_game(bets) def restart_game(bets): """ Function restarts the game from scratch, resetting total amount :param bets: Player's bets object :return: None """ answer = str(input("Want to start a new game? Y / N\n")) if answer[0].lower() == 'y': bets.total = 100 main() elif answer[0].lower() == "n": exit() else: print("Invalid Input") restart_game(bets) def display_all_cards_and_values(hand1, hand2): """ Function reveals all cards and prints each hand's value, when there's a winner :param hand1: Player's hand object :param hand2: Dealer's hand object :return: None """ print("Player's cards : {}".format(hand1.hand)) print("Player's value: {}".format(hand1.get_hand_value())) print("Dealer's cards: {}".format(hand2.hand)) print("Dealer's value: {}".format(hand2.get_hand_value())) def main(): global playing playing = 1 player_bets = Bets(total=100) while playing: game_deck = Deck() print("Player total is {}".format(player_bets.total)) player_hand = Hand() dealer_hand = Hand() player_bets.take_bet() player_bets.betting = 1 player_hand.get_card(game_deck.deck) player_hand.get_card(game_deck.deck) dealer_hand.get_card(game_deck.deck) dealer_hand.get_card(game_deck.deck) player_hand.reveal_cards(player="Player", hide=False) dealer_hand.reveal_cards(player="Dealer", hide=True) if drop_win(hand1=player_hand, hand2=dealer_hand, bets=player_bets) is False: print("Player value: {}".format(player_hand.get_hand_value())) hit_or_stand(deck=game_deck, hand1=player_hand, hand2=dealer_hand, bets=player_bets, limit=[21, 17]) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T12:18:37.260", "Id": "467713", "Score": "0", "body": "Your question title should explain what your code does - and not what you want fixed with it; I suggest you remove the \"need OOP advice\" from the title." } ]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>Parameter defaults are not relevant for <code>reveal_cards</code> - it's always called with <code>hide</code> set.</li>\n<li>Boolean parameters are a code smell. Usually they should be replaced by two methods which each encapsulate just their difference, usually calling a third method to do the common work.</li>\n<li>The ranks and suits and their values should probably be an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enumeration</a>. That way any reference to for example the ace would be a reference to an enumeration value rather than a magic string which <em>happens</em> to be connected to a number elsewhere.</li>\n<li>The value of the ace is <em>either</em> 1 <em>or</em> 11, depending on what's best for the player. That could be encapsulated by a method on the ace enum value.</li>\n<li>Try to get rid of comments by improving the code where possible. For example, renaming <code>hand1</code> to <code>player_hand</code> removes the need for mapping that in a comment.</li>\n<li>Mixing output and logic is usually a bad idea. Pulling out the printing code to just print the current state after each event should make the logic easier to read.</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.</li>\n<li><a href=\"https://pypi.org/project/isort/\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group imports (built-ins first, then libraries and finally imports from within your project) and sort them.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> can give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend validating your <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>This ensures that anyone reading the code (including yourself) understand how it's meant to be called, which is very powerful in terms of modifying and reusing it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T03:00:39.960", "Id": "238467", "ParentId": "238436", "Score": "2" } }, { "body": "<p>You're going the right path, but to master OOP think about the logical division of things. <code>Hands</code> and <code>Decks</code> can indeed be seen as objects, but you've kept functions like <code>display_all_cards_and_values</code>, <code>restart_game</code>, and <code>continue_playing</code> separate---these sound like aspects of a <code>Game</code> to me. Some of your classes also contain methods and data that don't seem to relate to them; <code>print(\"\\n********************\\nNEW GAME BEGINS NOW!\\n\")</code> doesn't seem like a very <code>Deck</code> thing. The initial shuffle of the deck (in <code>__init__</code> sounds like a <code>Deck</code> method: <code>def shuffle(self) -&gt; None: random.shuffle(self.deck)</code>.</p>\n\n<p>So what I would say is to try to turn (almost) everything into objects. If you have functions that just format strings or that transform sequences somehow, then make them separate functions, but as you force yourself to think of more things as objects it's going to get increasingly easy to structure things, and you'll realise that there are a lot of natural pairings to be made. You can also look for parts where you repeat yourself, and try to generalise as much as you can out of those parts (e.g. your if-statements in <code>drop_win</code>, which contain the same 4–5 lines with only minor differences).</p>\n\n<p>Smaller advice:</p>\n\n<ul>\n<li><p>your <code>values</code> is basically an enum, so you can use an enum instead.</p></li>\n<li><p>list comprehensions are fast, use them:</p>\n\n<pre><code>self.deck = []\nfor rank in self.ranks:\n for suit in self.suits:\n self.deck.append((rank, suit))\n</code></pre>\n\n<p>-></p>\n\n<pre><code>self.deck = [rank, suit for itertools.product(ranks, suits)]\n</code></pre></li>\n<li><p>if you're using Python version >= 3.6, utilize f-strings!</p>\n\n<pre><code>print(\"{} cards: {}\".format(player, self.hand))\n</code></pre>\n\n<p>-></p>\n\n<pre><code>print(f\"{player} cards: {self.hand}\")\n</code></pre>\n\n<p>and you can even add conditionals</p>\n\n<pre><code>print(f\"{player} cards: {self.hand if not hide else self.hand[0:-1]}\")\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-16T14:07:31.840", "Id": "478985", "Score": "1", "body": "Thank you to all of you guys: ades, l0b0, C. Harley\nIt's definitely a lot to swallow for me, but i'll keep practicing and use all of your advises to improve my OOP. \nI'll post new code later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-20T14:36:51.557", "Id": "479464", "Score": "0", "body": "Best of luck! Don't forget that you can, and should, accept (the check mark under votes) your preferred answer once you're happy with the replies." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-20T14:25:59.103", "Id": "239190", "ParentId": "238436", "Score": "2" } }, { "body": "<p>I think the reason why you're having a problem with classes and OOP is because you've not fully understood the things around you. For instance - you start with Deck, because that's your the focus of the game. You're thinking about the game - and not the objects themselves.</p>\n\n<blockquote>\n <p>defining class object attributes vs instance attributes,</p>\n</blockquote>\n\n<p>Think of a class as a set of architectural plans - it's not a real thing until you actually instantiate it. Let's OOP the start of your program.</p>\n\n<p>What's a Deck made up of? Cards. Can you go smaller than a card? No. Okay, so that's the first object you should create.</p>\n\n<p>Create your first class as Card. Now describe the Card. What does a card have? It has a Rank and a Suit. What else can you use to describe the card? You could describe the quality of the paper and the thickness, as well as the colours used to paint the card - but we discard those attributes because they serve no purpose for what we're trying to achieve, which is playing the game (and they don't matter for our program).</p>\n\n<p>Now, let's think about actions (methods/functions) of the card - does the card have any actions? No. We know they are dealt by the dealer, but by themselves, they don't do anything. So that tells you it's an object with data/state, but no methods.</p>\n\n<p>Now each card is different, and we know there are 52 cards (ignoring the Joker) typically in each deck. Do you build all 52 cards manually? You can. That's a brute-force approach, which you did. Do you know what computers are good at? Giving them a set of instructions and letting them repeat until the goal is achieved - this is the basis of Machine Learning.</p>\n\n<p>So, we create the Card, and we know when we create the card, it must have 2 attributes at minimum:</p>\n\n<pre><code>class Card:\n def __init__(self, rank, suit):\n self.rank, self.suit = rank, suit\n</code></pre>\n\n<p>But we know we have to get information from the card - we want to get a value, we want to get the rank, and we want to display the card information itself, in a human-readable way, such as 7 of Spades, or 7S. Let's go for the shorter-version - but you can change that later on that single line.</p>\n\n<pre><code>class Card:\n def __init__(self, rank, suit):\n self.rank, self.suit = rank, suit\n def __str__(self):\n return f\"{self.rank}{self.suit}\"\n</code></pre>\n\n<p>Ah, but if we think of an Ace - it represents 2 values depending on how it is used by the player. So let's add the two states - hard and soft values to the class. \nWe don't know <em>how</em> we're going to address that (such as the player having 4 aces with all of them together only representing a hand value of 4), so this is okay for the moment. Let's add hard and soft values:</p>\n\n<pre><code>class Card:\n def __init__(self, rank, suit):\n self.rank, self.suit = rank, suit\n def __str__(self):\n return f\"{self.rank}{self.suit}\"\n def get_hard_value(self):\n return self.rank\n def get_soft_value(self):\n return self.rank\n</code></pre>\n\n<p>Now let's consider how we're going to create a card with a special rule. For cards 2-9, they're straight-forward, we don't need anything special. Aces and Face cards however do require different rules or behavior.\nAs the Ace only has a single rule (either 1 or 11) - let's do that first. We inherit Card as the base class object, and specify the unique rules:</p>\n\n<pre><code>class Ace(Card):\n \"\"\" Aces can be either 1 or 11\"\"\"\n def __init__(self, rank, suit):\n super().__init__(rank, suit)\n def __str__(self):\n return f\"A{self.suit}\"\n def get_hard_value(self):\n return 1\n def get_soft_value(self):\n return 11\n</code></pre>\n\n<p>And now look at the Face Cards. Like the Ace, we know the face cards value should be hard-coded to 10, but we are faced with a slightly different issue (pun intended). The card is either K, Q, or J but keeps a value of 10. So, if we get an initial value that specifies that it is a K/Q/J - such as 11,12,13? Let's keep that initial value as an extra property, and override the value back to 10.</p>\n\n<pre><code>class FaceCard(Card):\n \"\"\" Face cards have a value of 10 and a must be either of King, Queen or Jack\"\"\"\n def __init__(self, rank, suit):\n super().__init__(rank, suit)\n self.special = rank\n self.rank = 10\n def __str__(self):\n label = [\"K\", \"Q\", \"J\"][self.special - 11]\n return f\"{label}{self.suit}\"\n</code></pre>\n\n<p>Now we have the architecture of the card, with the specific cases where the card changes slightly based on the rules of the cards. We have used inheritance to create a base class, and inherit Card with special overriding rules to show how - even though an Ace is a Card - it is slightly different.</p>\n\n<p>This explanation should demonstrate the architecture of what a class object is - it is not yet instantiated - we don't have an instance object for you to see the difference - so let's create a set of instances of card, face card and ace. How do we do that? by creating the deck.</p>\n\n<p>The deck will be a grouping of cards in a certain way depending on the rules of the game. Currently, your <code>Deck</code> class is very specific to vanilla Blackjack - if you wanted to add a Joker as a wild-card - you'd need to rewrite the <code>Deck</code> class.\nWhat if you wanted to switch back? Your Deck class is broken for a vanilla Blackjack game, and you'd need to rewrite it again, losing all the changes you created for a Jokers wild Blackjack game.</p>\n\n<p>We learn the value of inheritance by this specific case. <code>deck = BlackJackDeck()</code> or <code>deck = BlackJackJokersWildDeck()</code> allow you to create different games with slightly different sets of cards.</p>\n\n<p>So - analysis of the deck of cards for the vanilla Blackjack game. What is it? It's a set (unique items, no duplicates) of cards. What attributes does it have? It contains a specific size (52) of cards. Any other attributes? Not really. What about actions? Yes, it has an action of dealing a card - which reduces the available deck by 1. What happens when the deck is exhausted? Typically you should not reach this edge case unless you exceed a certain number of players.</p>\n\n<p>We've covered class objects and their attributes, now we look at instantiated/concrete objects from the class, and passing arguments. We will cover those with the <code>Deck</code> class.</p>\n\n<p>You also wanted clarification on <strong>class functions verses functions outside classes</strong>. This is more about the game itself - Blackjack or Texas Hold'em - the game has specific actions (functions/methods) which <strong>act</strong> on the deck of cards.</p>\n\n<p>The cards don't care what game you're playing. They exist, they are dealt. That is the functionality combining the cards and the deck. The game - that is those \"outside functions\" with different scoring rules and rules of the game like of the number of players per game. Does that help? What something <strong>is</strong> verses what you <strong>do</strong> with it.</p>\n\n<p>If an object has an action (like giving a card when it is asked for) then it belongs with the object. If you <strong>do</strong> something <strong>with</strong> that card - then the action belongs <em>outside</em> the object. Take some time to think about it. Until then, we dig into the <code>Deck</code> object (Which I've renamed as <code>BlackJackDeck</code> because it's more specific of what it is. Correct naming of variables and classes help other programmers to understand your code easier).</p>\n\n<pre><code>from random import shuffle\n\nclass BlackJackDeck:\n \"\"\" A set of cards suitable for a Blackjack game which can deal a random card\"\"\"\n def __init__(self):\n self.cards = []\n for suit in [\"H\", \"D\", \"C\", \"S\"]:\n self.cards += [Card(rank, suit) for rank in range(2,10)]\n self.cards += [FaceCard(rank, suit) for rank in range(11,14)]\n self.cards += [Ace(11, suit)]\n shuffle(self.cards)\n\n def deal(self):\n for card in self.cards:\n yield card\n</code></pre>\n\n<p>I'll leave the rest of the game up to you, but essentially now we have a set of code where we have a Deck of cards specific to a Blackjack game, where we can create a deck for each round, and deal a card when requested.</p>\n\n<p>This creating of objects, from the smallest thing and getting larger, mimics real life is what OOP is all about. Learning the S.O.L.I.D principals can help you improve your OOP code too.\nLooking further at your code, I see <code>drop_win</code> <code>busted</code> and <code>blackjack</code> do calculations of the value of players hand - all this belongs in one place - the Player class. It is the player which holds the hand of cards, it is the player that plays, bets, gets another card, stands or hits, and leaves the table with their winnings.</p>\n\n<p>I'll import the deck into my iPython CLI and show you how to use it - notice calling <code>deck.deal()</code> gives the same deck? This is because the shuffle is only called when creating a new Deck.</p>\n\n<pre><code>In [52]: deck = BlackJackDeck()\n\nIn [53]: for card in deck.deal():\n ...: print(f\"{card} {card.rank}\")\n ...:\n9H 9\n7C 7\n3H 3\n(snip)\n\nIn [54]: cards = deck.deal()\n\nIn [55]: next(cards)\nOut[55]: &lt;__main__.Card at 0x6089c50&gt;\n\nIn [56]: print(next(cards))\n7C\n\nIn [57]: print(next(cards))\n3H\n\nIn [58]: a = next(cards)\n\nIn [59]: print(a)\nAD\n\nIn [60]: dir(a)\nOut[60]:\n[(snip)\n '__str__',\n '__subclasshook__',\n '__weakref__',\n 'get_hard_value',\n 'get_soft_value',\n 'rank',\n 'suit']\n\nIn [61]: a.rank\nOut[61]: 11\n\nIn [62]: a.get_hard_value()\nOut[62]: 1\n\nIn [63]: a.get_soft_value()\nOut[63]: 11\n</code></pre>\n\n<p>I hope this helps to clarify objects a little further. It's an interesting way to represent things for coding - and not the only way - classes work well for data objects and object-specific actions - but I find components of functional programming safer. As mentioned, learn SOLID principals and they will help your coding get better.</p>\n\n<p>Good luck and keep up the coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T16:45:51.230", "Id": "242043", "ParentId": "238436", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T15:12:40.970", "Id": "238436", "Score": "8", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Python Blackjack, need OOP advice" }
238436
<p>For a research analysis, I'm writing a small bash script that serves as a frontend to <a href="https://sylabs.io/singularity" rel="nofollow noreferrer">Singularity</a>. The reason is that I want to save in this script which options are needed for singularity. For example, I want the working directory to appear at a fixed path in the container, regardless of the actual working directory path. </p> <p>Singularity has the <code>--contain</code> option for this, but this requires me to manually define a temporary directory for the container. I use <code>mktemp</code> for that. After the end of the script, I use <code>trap</code> to delete that directory. However, I fear that there might be a corner case where <code>trap "rm -rf '$tmpdir'</code> might delete the wrong directory.</p> <p>The script, called <code>cexec</code>, executes an arbitrary command inside the container. For example <code>./cexec R</code> starts R inside the container. </p> <p><strong>Is there a corner case in the following script where the script deletes a directory that it didn't create?</strong></p> <pre><code>#!/bin/bash # Execute a command in the container set -ue thisdir="$(dirname "$BASH_SOURCE")" container="rserver_200211_commitd117c677.sif" # get such a file by using `singularity pull ...` # Create a temporary directory tmpdir="$(mktemp -d -t cexec-XXXXXXXX)" # We delete this directory afterwards, so its important that $tmpdir # really has the path to an empty, temporary dir, and nothing else! # (for example empty string or home dir) if [[ ! "$tmpdir" || ! -d "$tmpdir" ]]; then echo "Error: Could not create temp dir $tmpdir" exit 1 fi # check if temp dir is empty tmpcontent="$(ls -A "$tmpdir")" if [ ! -z "$tmpcontent" ]; then echo "Error: Temp dir '$tmpdir' is not empty" exit 1 fi # Delete the temporary directory after the end of the script trap "rm -rf '$tmpdir'" EXIT singularity exec \ -B "$tmpdir:/tmp" \ --contain \ -H "$thisdir:/data" \ "$container" \ "$@" </code></pre>
[]
[ { "body": "<p>Always set up the trap <em>before</em> trying to create the directory. Otherwise there's a race condition where the script may die after creating the directory but before having a chance to clean it up. And use single quotes for the <code>trap</code> command to make sure the variable is only expanded at exit:</p>\n\n<pre><code>trap 'rm -rf \"$tmpdir\"' EXIT\ntmpdir=\"$(mktemp -d)\"\n</code></pre>\n\n<p>If the trap ends up being triggered <em>before</em> <code>mktemp</code> the result is simply <code>rm -rf \"\"</code>, which does nothing.</p>\n\n<p>Some other suggestions:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/10383546/96588\"><code>#!/usr/bin/env bash</code></a> is a more portable shebang.</li>\n<li><code>set -o errexit -o nounset</code> is more readable than <code>set -ue</code>.</li>\n<li><code>BASH_SOURCE</code> is an array, and it's only by accident that <code>$array_name</code> refers to the first element of <code>array_name</code>. <code>directory=\"$(dirname \"${BASH_SOURCE[0]}\")\"</code> would be more explicit.</li>\n<li><code>if [[ ! \"$tmpdir\" || ! -d \"$tmpdir\" ]]</code> is redundant. If <code>mktemp</code> fails the script will stop there, and if it's been removed <code>rm -rf \"$tmpdir\"</code> is safe, as mentioned.</li>\n<li><a href=\"https://unix.stackexchange.com/q/128985/3645\">Don't use <code>ls</code> in scripts!</a></li>\n<li>The temporary directory <em>can't</em> already contain any files. That's part of the contract of <code>mktemp</code> - it <em>will</em> create a new directory if it can, or fail otherwise.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T10:58:42.530", "Id": "467700", "Score": "0", "body": "I don't normally like single quotes for the `trap`, leaving the variable unexpanded (there's a risk that some other code modifies it, particularly with a generic name like that). So I'd have something like `while tmpdir=\"$(mktemp -u)\"; trap \"rm -rf '$tmpdir'\" EXIT; mkdir \"$tmpdir\"; do : ; done`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T20:04:03.820", "Id": "467748", "Score": "0", "body": "If you're worried about something modifying `tmpdir` you can just `readonly tmpdir`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T02:36:49.773", "Id": "238464", "ParentId": "238439", "Score": "2" } } ]
{ "AcceptedAnswerId": "238464", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T16:14:38.120", "Id": "238439", "Score": "3", "Tags": [ "bash" ], "Title": "A temporary directory that exists only during run time of user-specified code" }
238439
<p>I am trying to solve a maze problem.</p> <p>The input data is a matrix, where the individual element represents the height of the mountain in that particular area, I have to start from position (0,0) and go to the position (n-1, n-1); where n is the size of the maze, my goal is to return the minimum number of possible climb round that I have to make in order to achieve this goal.</p> <p>For example:</p> <pre><code>b = 010 010 010 </code></pre> <p>In the matrix b,If I start from <code>(0,0)</code> I have to climb to height <code>1</code>, now I am on the hill and I have to go down, so the total number of climb round is </p> <p><code>abs(0(height of starting position) - 1(height of mountain)) + abs(1(height of mountain) - 0(height of the third column)) = 2</code></p> <p>If I reach to third column then I do nnot have to climb any further round as my goal (2,2) would be at same level</p> <pre><code>c = 010 101 010 </code></pre> <p>Similarly for <code>c</code>, the answer would be <code>4</code></p> <p>A typical example would be</p> <pre><code>75218176 00125954 30062751 01192976 24660156 14932066 44532310 60429682 </code></pre> <pre class="lang-py prettyprint-override"><code>""" self.location stores the location of current node self.cost stores the cost or path length from adjacent node approaching from a particular path, for example in the above example If I have coming along the path 752 then cost of the node whose location is (0,2) would be 3, as the difference of height 5 and height 2 is 3 self.altitude simply stores the number which is at the location self.totalCost represent the totalCost from the begenning, for example: for the path 752, the total cost of '2' would be 7- 5 + 5 -2 = 5 getTotalcost() simply add the parent cost with the difference in altitude of parent and self neighbours() returns the possible node which can be reached from the current position. Open is basically implementation of priority queue, I have not used heapq because in order to maintain the invariancy in structure I am not supposed to delete any element at random, although I can re-heapify after deletion but that seems to an obvious choice for inefficiency """ class node: def __init__(self, loc): self.location = loc self.cost = 0 self.altitude = 0 self.parent = None self.totalCost = 0 def __eq__(self, other): return self.location == other.location def __hash__(self): return hash(self.location) def getTotalcost(self): if self.parent: self.totalCost = self.cost + self.parent.totalCost return self.totalCost def __lt__(self, other): return self.getTotalcost() &lt; other.getTotalcost() def neighbours(S, Node): a,b = Node.location options = [] for i in (a, b + 1), (a, b - 1), (a + 1, b), (a - 1, b): if min(i) &gt;= 0 and max(i) &lt; S: options.append(node(i)) return options class Open: def __init__(self, point): self.container = [point] self.se = set(self.container) self.l = 1 def push(self, other): if not(other in self.se): self.properPlace(other) else: a = other b = self.container.index(other) k = self.container[b] if k.getTotalcost() &gt; a.getTotalcost(): del self.container[b] self.l -= 1 self.se.remove(k) self.properPlace(other) def __iter__(self): return iter(self.container) def rem(self): self.l -= 1 return self.container.pop(0) def properPlace(self, other): i = 0 while i &lt; self.l and self.container[i].getTotalcost() &lt; other.getTotalcost(): i += 1 self.container.insert(i, other) self.l += 1 self.se.add(other) def path_finder(maze): maze= maze.split("\n") l = len(maze) start = node((0,0)) start.altitude = int(maze[0][0]) start.totalCost = 0 r = Open(start) visited = set() while True: i = r.rem() if i.location == (l - 1, l- 1): return i.getTotalcost() for j in neighbours(l, i): j.altitude = int(maze[j.location[0]][j.location[1]]) if j not in visited: j.cost = abs(i.altitude - j.altitude) j.parent = i r.push(j) visited.add(i) </code></pre> <p>I have some thoughts that my implementation of priority queue is inefficient, am I right? If yes, then how can I make it more efficient? How can I make the program efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T22:53:48.690", "Id": "467660", "Score": "0", "body": "Do you need to implement the priority queue yourself (for homework, just for the fun/challenge, etc.), or would a pre-built solution be just as good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T06:38:35.053", "Id": "467682", "Score": "0", "body": "It would be best if someone helps me to find the chunk and suggest to improve where the maximum computational time goes in my code, else even the more efficient implementation would be good too." } ]
[ { "body": "<p>The advice I think most important:</p>\n\n<ul>\n<li><p>stick to 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>\nIt helps everyone - including yourself - <em>read</em> your code. </p></li>\n<li><p>Naming: name things for what they can/will be used for, their <em>raison d'être</em>.<br>\nFor example, the class featuring <code>push()</code>, <code>rem()</code>, and <code>_properPlace()</code> is <em>not</em> used to <em>be open</em> or <em>open something</em>. It looks a <em>priority queue with <code>increase_priority()</code></em>.<br>\nThe <em>instance</em> <code>r</code> in <code>path_finder()</code> holds a set of <em>tentative costs</em>, or, if you insist, \"open\" nodes.<br>\nThe usual suggestion in the context of <a href=\"https://en.m.wikipedia.org/wiki/Pathfinding\" rel=\"nofollow noreferrer\">path finding</a> is to use a <a href=\"https://en.m.wikipedia.org/wiki/Fibonacci_heap\" rel=\"nofollow noreferrer\">Fibonacci_heap</a> - there is <a href=\"https://pypi.org/project/fibheap/\" rel=\"nofollow noreferrer\">PyPI fibheap</a>.</p></li>\n<li><p>Modelling<br>\n<code>node</code> is a strange hybrid of node and edge, given its single <code>parent</code> and <code>cost</code>:<br>\ncost is <em>not</em> an attribute of a node, but an attribute of an edge, a pair of nodes </p></li>\n</ul>\n\n<p>I suspect <code>del</code> and <code>insert</code> on <code>Open.container</code> to be the performance culprits.<br>\nYou could try and adapt <em>heapq</em>:<br>\nlocate nodes using <code>index()</code> as presented (O(n))<br>\nupdate cost and use <code>_siftdown()</code> to restore heap property</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T09:13:40.213", "Id": "238611", "ParentId": "238440", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T17:18:50.680", "Id": "238440", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "graph", "priority-queue" ], "Title": "Efficient implementation of priority queue" }
238440
<p>I'm trying to implement a really basic queue (as an array) in my computer science class and want some feedback on my logic/methodology. the queue is not circular, it just includes the basic functions of enqueue/dequeue (along with the other obvious ones.) Please criticize and give feedback so I can educate myself on the best practices. </p> <p>I was given this assignment as part of an entry level CS class. I was told not to make a circular queue. So this of course is not an efficient model by any means.. just a rough idea of what queues do. </p> <p>what the code should do: users can add to the queue by moving forward the last element of the array, and "remove" items (they kinda still float around in memory though. remove isn't a great word) by moving the first element forward. </p> <p>Class declaration:</p> <pre><code>class queueList { private: int *list; int queueFront; int queueRear; int maxSize; public: void enqueue(const int &amp;x); bool isEmpty(); bool isFull(); void dequeue(); queueList(const int &amp;x); int front(); int back(); }; </code></pre> <p>class implementation: </p> <pre><code>queueList::queueList(const int &amp;x) { list = new int[x]; queueRear = 0; queueFront = 0; maxSize = x; } void queueList::enqueue(const int &amp;x) { if (!isFull()) { list[queueRear] = x; //cout &lt;&lt; list[queueRear] &lt;&lt; endl; queueRear++; } } bool queueList::isEmpty() { return (queueFront == queueRear); } bool queueList::isFull() { return (queueRear == maxSize); } void queueList::dequeue() { if (!isEmpty()) { list[queueFront] = 0; cout &lt;&lt; list[queueFront] &lt;&lt; endl; queueFront++; } } int queueList::front() { return list[queueFront]; } int queueList::back() { return list[queueRear]; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T00:47:37.183", "Id": "467672", "Score": "1", "body": "Could you add a short explanation for how your code works, and why you made any unorthodox choices if you did?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T01:29:27.737", "Id": "467674", "Score": "1", "body": "@k00lman sure thing, I added a description that added more detail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T07:23:07.823", "Id": "467686", "Score": "1", "body": "I always worry about these sorts of classes, where they ask you to implement queues and lists and things. I get that they are designed to teach low level coding skills, but seem to forget that you should never (99.9999% of the time) write your own, but use the one provided by the library. Would a carpenters training include how to make wood glue and a saw?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T13:24:31.507", "Id": "467714", "Score": "0", "body": "Why fiddle your own, when its already there and widely available : https://en.cppreference.com/w/cpp/container/queue\n@Neil maybe not the saw - where they would teach how to use it properly without sawing fingers off - but carpenters glue ... should still be taught" } ]
[ { "body": "<p>Use <code>std::size_t</code> for container sizes and indices, not <code>int</code>.</p>\n\n<pre><code>std::size_t queueFront;\nstd::size_t queueRear;\nstd::size_t maxSize;\n</code></pre>\n\n<p>Use meaningful variable names. When I use your constructor, what does \"x\" mean? Something like <code>queue_size</code> is more meaningful. This can also be a <code>std::size_t</code>. This also doesn't need to be a reference, since it's likely the same size as a pointer, but feel free to continue passing as reference if you want. You just normally don't see that with primitive types.</p>\n\n<pre><code>queueList(std::size_t queue_size);\n</code></pre>\n\n<p>Similarly, pick a meaningful name for your <code>enqueue</code> function. Even something like <code>value</code> carries more meaning than <code>x</code>. This should NOT be a <code>std::size_t</code>, since obviously you do want to insert an <code>int</code> into your <code>int</code> array.</p>\n\n<p>Handle the special case in your constructor where the passed-in size is 0 or less. It won't be less than 0 if you switch to <code>size_t</code>, but it can still be 0. Do you want to allow this? How do you manage the memory? Calling <code>new int[0];</code> is undefined behavior. Also, use initializer lists when possible for constructors. It prevents variables from being double-assigned and objects from being double-constructed. You won't notice any speedup on this problem, but it's a good habit to get into.</p>\n\n<pre><code>queueList::queueList(std::size_t queue_size)\n : list(queue_size &gt; 0 ? new int[queue_size] : nullptr)\n , queueRear(0)\n , queueFront(0)\n , maxSize(queue_size)\n{ }\n</code></pre>\n\n<p>Explicitly <code>delete</code> your default constructor to avoid ambiguity.</p>\n\n<pre><code>queueList() = delete;\n</code></pre>\n\n<p>Your constructor manages a resource (memory allocated with <code>new</code>), so you must also declare a destructor that <code>delete</code>s the memory. Since you must declare a destructor, you must follow at LEAST the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"noreferrer\">rule of 3</a> and define a copy constructor and a copy assignment operator. A best practice would be to follow the rule of 5 (same link as rule of 3) and define additionally a move constructor and move assignment operator.</p>\n\n<p>They key with all of these is: what does it mean to create a copy of your queue? What does it mean to move your queue? Most of these questions will have to do with managing the underlying allocated memory.</p>\n\n<pre><code>~queueList() { delete[] list }; // destructor\nqueueList(const queueList&amp; other); // copy constructor\nqueueList&amp; operator=(const queueList&amp; other); // copy assignment operator\nqueueList(queueList&amp;&amp; other); // move constructor\nqueueList&amp; operator=(queueList&amp;&amp; other); // move assignment operator\n</code></pre>\n\n<p>Your queue is currently one-time-use. It can only ever hold <code>queue_size</code> (<code>x</code> in your code) elements ever. It can't hold more elements than what you initially allocate. The latter is surmountable, but you should make it a goal to allow the queue to grow (or have a policy of throwing some error, or letting the user know through documentation that excess values will be lost). The one-time usability of each data slot is CRIMINAL though. My suggestion is to allow <code>queueRear</code> and <code>queueFront</code> to wrap around the array using modulo arithmetic as they move to the right.</p>\n\n<p><strong>dequeue should return a value!!!</strong> This is a huge shock to anyone who will try to use your class. They don't always want to print the value. They likely want to use it in some future calculation. This is easy. However, your current code doesn't even print the current value. It just always overwrites it with 0, then prints 0. This also decouples your class from requiring iostream to work.</p>\n\n<p>Change your dequeue to look like this:</p>\n\n<pre><code>int queueList::dequeue()\n{\n if (isEmpty())\n {\n // figure out what to do here.\n // Throw an error? Seems appropriate. \n // Another option is to return a std::pair&lt;int, bool&gt;,\n // where the second value indicates whether there were\n // any items in the queue\n }\n int retval = list[queueFront++];\n queueFront = queueFront % maxSize; // talking about modulo arithmetic earlier\n return retval;\n}\n</code></pre>\n\n<p>Your <code>isEmpty()</code> and <code>isFull()</code> functions can have their prototypes modified to be <code>const</code>, since neither modify the object:</p>\n\n<pre><code>bool isEmpty() const\n{\n ...\n}\n\nbool isFull() const\n{\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T22:23:32.197", "Id": "467655", "Score": "0", "body": "thank you for such a thoughtful reply! My teacher actually asked for the queue not to be circular (which is inefficient and means the queue isn't very functional). With this in mind, do you think the logic is okay for how I'm determining whether my queue is empty or full? If I have a queue of three components and ran it through my dequeue function 3 times, my front and rear would both end with index three. Is the logic ok there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T22:24:27.473", "Id": "467656", "Score": "0", "body": "The logic there is okay, yes. As long as you and your teacher are both aware that this is a one-time-use operation queue." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:50:35.407", "Id": "238453", "ParentId": "238448", "Score": "8" } } ]
{ "AcceptedAnswerId": "238453", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:01:11.673", "Id": "238448", "Score": "4", "Tags": [ "c++", "beginner", "c++11" ], "Title": "Implementing a queue in C++" }
238448
<p>I am new to Python programing language. I have created the codes, based on <a href="https://stackoverflow.com/questions/42844948/trying-to-make-a-kml-file-in-python">this solution</a>.</p> <p>I prepared two simple programs:</p> <pre><code>import simplekml List2 = [ [ 'Placemark','old file', 51.500152, -0.126236 ] ] # description, lat, lon List3 = [ [ 'New placemark','new file', 51.600152, -0.136236 ] ] kml = simplekml.Kml() for row in List2: kml.newpoint(name=row[0], description=row[1], coords=[(row[3], row[2])]) # lon, lat, optional height for row in List3: kml.newpoint(name=row[0], description=row[1], coords=[(row[3], row[2])]) kml.save("test2.kml") </code></pre> <p>and from another file here:</p> <pre><code>import simplekml kml = simplekml.Kml() kml.newpoint(name="Kirstenbosch", description="Description", coords=[(18.432314,-33.988862)]) # lon, lat,optional height kml.newpoint(name="Kirstenbosch2", description="&lt;b&gt; Botanic garden &lt;/b&gt; in South Africa", coords= [(18.532314,-33.788862)]) kml.save("output/botanicalgarden2.kml") </code></pre> <p>I know that this code (<a href="https://support.google.com/maps/forum/AAAAQuUrST85PsG3XdzWxU/?hl=ms" rel="nofollow noreferrer"><code>simplekml tool</code></a>) can be used for the bulk <code>.kml</code> data, as it was mentioned <a href="https://support.google.com/maps/forum/AAAAQuUrST85PsG3XdzWxU/?hl=ms" rel="nofollow noreferrer">here</a>.</p> <p>Could you tell me how to write this code not repeatedly, as I did? I would like to have a multitude of place mark locations within one list/new point, when possible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-08T08:49:57.327", "Id": "467856", "Score": "0", "body": "TIL that mathematical tools take `(lon, lat)`, instead of `(lat, lon)`, because it maps to the common way to put `(x, y)` coordinates for plotting..." } ]
[ { "body": "<p>In your first code you already have everything you need, you just don't use it. <code>List2</code> and <code>List3</code> are each lists of points to create. But they only contain one point, so your <code>for</code> loop does nothing exciting, it only runs once.</p>\n\n<p>You can simply add more points to any of the lists, here I take the first as an example:</p>\n\n<pre><code>import simplekml\n\npoints = [['Placemark', 'old file', 51.500152, -0.126236],\n ['New placemark', 'new file', 51.600152, -0.136236]] # description, lat, lon\n\nkml = simplekml.Kml()\nfor point in points:\n kml.newpoint(name=point[0], description=point[1],\n coords=[(point[3], point[2])]) # lon, lat, optional height\n\nkml.save(\"test2.kml\")\n</code></pre>\n\n<p>You could make this a bit more readable by using a <code>collections.namedtuple</code> for the markers. This way your comments become superfluous:</p>\n\n<pre><code>from collections import namedtuple\nimport simplekml\n\nMarker = namedtuple(\"Marker\", [\"name\", \"description\", \"lat\", \"lon\"])\n\npoints = [Marker('Placemark', 'old file', 51.500152, -0.126236),\n Marker('New placemark', 'new file', 51.600152, -0.136236)]\n\nkml = simplekml.Kml()\nfor point in points:\n kml.newpoint(name=point.name, description=point.description,\n coords=[(point.lon, point.lat)])\n\nkml.save(\"test2.kml\")\n</code></pre>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, when naming my variables. Variables and functions should be <code>lower_case</code> and only classes (such as the namedtuple class I create) should be in <code>PascalCase</code>. PEP8 also recommends putting a space after commas and not to use unnecessary whitespace. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-08T08:57:26.827", "Id": "238554", "ParentId": "238449", "Score": "3" } } ]
{ "AcceptedAnswerId": "238554", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:19:15.727", "Id": "238449", "Score": "2", "Tags": [ "python" ], "Title": "Create multiple kml files in Python" }
238449
<p>I have this string that I am sometimes double encoding it because it is coming from two different fields. I have build this method that will do a string StringComparison. It seems complicated wanted to know if there is a better way to do something like this.</p> <pre><code> class Program { static void Main(string[] args) { string str1 = "This string is already encode &amp;lt;0.1"; Console.WriteLine(HTTPEncodeString(str1)); string str2 = "This string needs to be encoded &lt;0.01"; Console.WriteLine(HTTPEncodeString(str2)); } public static string HTTPEncodeString(string source) { if (EncodeText(source)) { return source; } else { return HttpUtility.HtmlEncode(source); } } public static bool EncodeText(string val) { string decodedText = HttpUtility.HtmlDecode(val); string encodedText = HttpUtility.HtmlEncode(decodedText); return encodedText.Equals(val, StringComparison.OrdinalIgnoreCase); } } </code></pre>
[]
[ { "body": "<p>A decoded string stays unchanged when returned from <code>HttpUtility.HtmlDecode()</code>. Therefore you can do it in a single line:</p>\n\n<pre><code>public static string HtmlEncodeString(string text)\n{\n return HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(text));\n}\n</code></pre>\n\n<hr>\n\n<p>The following shows a refactoring of your approach. Notice the changes in names to something more meaningful:</p>\n\n<pre><code>public static string HtmlEncodeString(string text)\n{\n return IsHtmlEncoded(text) ? text : HttpUtility.HtmlEncode(text);\n}\n\npublic static bool IsHtmlEncoded(string text)\n{\n return !text.Equals(HttpUtility.HtmlDecode(text), StringComparison.OrdinalIgnoreCase);\n}\n</code></pre>\n\n<p>Is also uses, that the result of decoding an encoded text is different from the text itself, while the result of decoding a decoded text is equal to the text. In this way you can avoid a least one call to <code>HtmlEncode()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T13:41:09.310", "Id": "467715", "Score": "0", "body": "There are decoded strings that are not invariant under decoding - see my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T13:59:36.053", "Id": "467718", "Score": "0", "body": "@TobySpeight: you're right. Bad answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T14:03:43.990", "Id": "467719", "Score": "0", "body": "@Jefferson: You should remove your acceptance of this answer, because it's not right." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T07:35:40.223", "Id": "238470", "ParentId": "238450", "Score": "1" } }, { "body": "<p>This isn't a language I know, but there appears to be a problem with the logic.</p>\n\n<p>Suppose I have a simple statement:</p>\n\n<blockquote>\n <p><code>In XML, ampersand can be represented using '&amp;amp;' or '&amp;#38;'</code></p>\n</blockquote>\n\n<p>Is that an already-encoded string? The logic here says that it is, but we see that's not the case - the HTML version of that would be</p>\n\n<blockquote>\n <p><code>In XML, ampersand can be represented using '&amp;amp;amp;' or '&amp;amp;#38;'</code></p>\n</blockquote>\n\n<p>If it's hard to keep track in code, a better option might be a small class to hold a HTML-encoded string, so that we don't confuse these with content strings (or vice-versa, if HTML-encoded is the default in your target environment).</p>\n\n<p>But TBH, I think that good variable naming should be enough to track which strings are which.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T13:56:41.157", "Id": "467716", "Score": "0", "body": "what would the class look like? would it be a bunch of nested replaces" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T15:06:00.063", "Id": "467723", "Score": "1", "body": "Thanks @Henrik: it's been a while since I've hand-written a CREF value!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T13:39:02.383", "Id": "238475", "ParentId": "238450", "Score": "6" } }, { "body": "<p>I'd like to extend on Toby's excellent post.</p>\n\n<p>You shouldn't be using/needing a stop gap mechanism like this.</p>\n\n<p>Data you are working with should never be HTML-encoded and there should never be any need for you to encoding it yourself with <code>HtmlEncode</code>. Any and all HTML-encoding should happen as late as possible, namely automatically in the template engine used (I believe in C# by default this would be in the Razor templates).</p>\n\n<p>If you do have data that is already HTML-encoded make sure to keep it separate from any other data and use the \"raw html\" function of the template engine to output it. However you need to KNOW (do NOT assume!) that that HTML doesn't contain any malicious code.</p>\n\n<p>If you have data (for example from a third party) of which you do not know if it HTML-encoded or not, then you preferable should assume it is not encoded and let it be HTML-encoded by the template engine when it is output, even if that results in double encoded HTML. Also you need to make sure that everyone involved (the third party, your boss, etc.) knows that this is a dangerous situation, that needs to be addressed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T12:53:13.830", "Id": "467959", "Score": "0", "body": "thanks for the comment, I have a field in the database that is storing HTML like <B> and <I> tags. I also have data in the same field that is &lt;50. So it is both encode and decode" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T13:15:29.510", "Id": "467961", "Score": "0", "body": "@Jefferson: No, that data would be considered already HTML-encoded. No need to encode/decode it. Keep it separate, validate that it actually contains what you assume (for example, by using a HTML cleaner/sanitizer library) and output it as \"raw html\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T12:29:23.047", "Id": "238619", "ParentId": "238450", "Score": "1" } } ]
{ "AcceptedAnswerId": "238470", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T21:27:16.630", "Id": "238450", "Score": "1", "Tags": [ "c#" ], "Title": "c# Checking if string is HtmlDecode" }
238450