body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>After working on the project for 15 hours of I had my layout set 1 row and 1 column per square, no problem. Then I decided that I needed each square to have multiple rows. I would have never guessed that it would take almost 6 hours to work this out. </p> <h2>The reason that I changed the layout</h2> <p>I had most of the logic worked. When the cell is clicked all the moves for each piece (except casling and en passant). I know which piece could move where and identified any threats to a piece. </p> <p>At this point I started writing the mechanism that would create and parse chess notations for the moves. Then it hit me. My logic was flawed! Well kinda, there was, however, an better way to load the board into the gaming engine than to read the chessboard range. Using the Chess Notation Log to power the Model. This would allow players to import, export and recreate games from their logs.</p> <p>I already had a Chess Notation Log table but was going to displaying it in a listbox because the row heights were too tall. That is what made me decide to have multiple rows per square.</p> <h2>Previous layout</h2> <p><a href="https://i.stack.imgur.com/ptXoM.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ptXoM.gif" alt="Old chessboard layout"></a></p> <h2>New layout</h2> <p><a href="https://i.stack.imgur.com/SFSWX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SFSWX.png" alt="New chessboard layout"></a></p> <h2>Adjusting the row heights and column widths</h2> <p>This code (based of of <a href="https://www.mrexcel.com/board/threads/how-to-make-excel-cell-real-square-in-size.253647/" rel="noreferrer">Tom Urtis post</a>) took most of the time. </p> <pre><code>Private Sub FitColumnsToRangeHeight(ByRef Target As Range, ByVal RowHeight As Double) Const Precision As Double = 0.1 With Target .RowHeight = RowHeight Do While .Width &lt; .Height .ColumnWidth = .ColumnWidth + Precision DoEvents Loop Do While .Width &gt; .Height .ColumnWidth = .ColumnWidth - Precision DoEvents Loop End With End Sub </code></pre> <h2>Code</h2> <pre><code>Option Explicit Public Enum PieceType King Queen Rook Bishop Knight Pawn End Enum Public Enum PieceColor Black = 9818 White = 9812 End Enum Public Sub CreateChessBoard() Application.ScreenUpdating = False Const RowHeight As Double = 15, RowsPerSquare As Long = 4 Const TopLeftAddress = "B3" Dim Squares As Range Rem Reset ActiveWorksheet Cells.Delete With Range(TopLeftAddress).Resize(8 * RowsPerSquare, 9).Offset(0, -1).EntireColumn .VerticalAlignment = xlCenter .HorizontalAlignment = xlCenter End With Set Squares = Range(TopLeftAddress).Resize(8 * RowsPerSquare, 8) FitColumnsToRangeHeight Squares, RowHeight Squares.BorderAround xlSolid, xlMedium Dim r As Long, c As Long, n As Long For n = 1 To 8 r = (n - 1) * RowsPerSquare + 1 For c = 1 To 8 With Squares.Cells(r, c).Resize(RowsPerSquare) .Merge .Interior.Color = IIf((n + c) Mod 2 = 0, xlNone, vbCyan) .Name = "_" &amp; Chr(64 + c) &amp; (9 - n) End With Next With Squares.Cells(r, 0).Resize(RowsPerSquare) .Merge .Value = Array(8, 7, 6, 5, 4, 3, 2, 1)(n - 1) .Font.Size = 18 End With Next For c = 1 To 8 With Squares(Squares.Count + c).Resize(2) .Merge End With Next With Squares .Font.Size = 36 End With With Squares.Rows(Squares.Rows.Count + 1) .Font.Size = 20 .Value = Array("A", "B", "C", "D", "E", "F", "G", "H") End With With Squares .Rows(1).Value = Array(ChrW(Black + Rook), ChrW(Black + Knight), ChrW(Black + Bishop), ChrW(Black + Queen), ChrW(Black + King), ChrW(Black + Bishop), ChrW(Black + Knight), ChrW(Black + Rook)) .Rows(RowsPerSquare + 1).Value = Array(ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn), ChrW(Black + Pawn)) .Rows(RowsPerSquare * 6 + 1).Value = Array(ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn), ChrW(White + Pawn)) .Rows(RowsPerSquare * 7 + 1).Value = Array(ChrW(White + Rook), ChrW(White + Knight), ChrW(White + Bishop), ChrW(White + Queen), ChrW(White + King), ChrW(White + Bishop), ChrW(White + Knight), ChrW(White + Rook)) End With End Sub Private Sub FitColumnsToRangeHeight(ByRef Target As Range, ByVal RowHeight As Double) Const Precision As Double = 0.1 With Target .RowHeight = RowHeight Do While .Width &lt; .Height .ColumnWidth = .ColumnWidth + Precision DoEvents Loop Do While .Width &gt; .Height .ColumnWidth = .ColumnWidth - Precision DoEvents Loop End With End Sub </code></pre> <h2>Why write a Chess game</h2> <p>I was inspired to write this after watching a weekly live YouTube stream where the hosts is working out the code, while interacting with the chat. What a phenomenal idea. </p> <p>I would love to make some training videos but to code a project like this live! Geez, how would I explain scraping 15 hours of work...."This is known as the Waterfall technique....", lol.</p> <h2>Questions</h2> <p>I didn't need this to be pretty, just accurate. So I only have few questions. </p> <ul> <li>It would be interesting to see another way to write <code>FitColumnsToRangeHeight()</code> </li> <li>Color scheme suggestions</li> </ul> <p>I'll have plenty of questions later on. Particularly, when I move on to writing the AI(s). I will probably base them off of Matt's Battle IStrategy. We'll see. </p>
[]
[ { "body": "<p>Iteratively incrementing/decrementing a width until you get it just right seems slow and inefficient to me.</p>\n\n<p>Instead, my approach is just to measure the conversion factor, and then use that measurement to set the width in one go. This is way, way faster.</p>\n\n<pre><code>Public Function WidthPerColumnWidth(r As Range) As Double\n WidthPerColumnWidth = (r.ColumnWidth * r.Columns.Count) / r.Width\nEnd Function\n\nPublic Sub FitColumnsToRangeHeight(ByRef Target As Range, ByVal RowHeight As Double)\n With Target\n .RowHeight = RowHeight\n .ColumnWidth = WidthPerColumnWidth(Target) * RowHeight * (.Rows.Count / .Columns.Count)\n End With\nEnd Sub\n</code></pre>\n\n<p>Since the conversion factor is dependent on the size of zero on the default (normal) font (see <a href=\"https://docs.microsoft.com/en-us/office/vba/api/Excel.Range.ColumnWidth\" rel=\"nofollow noreferrer\">the docs</a>), we could also determine the conversion factor based on a single cell (say A1), and cache that, if we expect no changes to the default style while the code is running.</p>\n\n<pre><code>Public Function WidthPerColumnWidth() As Double\n Static ConversionFactor As Double\n If ConversionFactor = 0 Then\n With Range(\"A1\")\n ConversionFactor = .ColumnWidth / .Width\n End With\n End If\n WidthPerColumnWidth = ConversionFactor\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:04:23.430", "Id": "456628", "Score": "0", "body": "I used similar code to create the first layout. It makes almost perfectly square cells but that is not what I want. My code will make the entire range square. For example: if you have a range of 100 Rows by 10 Columns, each column width will = the height of 10 cells." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:11:27.960", "Id": "456630", "Score": "0", "body": "@TinMan Ah, see the edit, I misunderstood the function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:14:57.547", "Id": "456632", "Score": "0", "body": "It wasn't to hours after I got it working before I understood how it works!! I should have provided a more detailed explanation for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:20:47.573", "Id": "456634", "Score": "0", "body": "Btw, since you're making a chess board, you don't need code to adjust `FitColumnsToRangeHeight` for an unequal amount of borders, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:28:11.543", "Id": "456636", "Score": "0", "body": "I wanted to code it so I could easily experiment with different themes, row heights and rows to columns ratios." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T12:07:44.747", "Id": "233536", "ParentId": "233533", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T11:37:40.707", "Id": "233533", "Score": "5", "Tags": [ "game", "vba", "chess" ], "Title": "Chess game: Part 1 - Creating the layout" }
233533
<p>This is my solution for <a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">Day 2 of Advent of Code 2019</a>.</p> <p>It's the <code>eval</code> function I want to get reviewed. Is this acceptable Haskell code? Is it even close to being idiomatic? Also, is it OK to leverage laziness this way?</p> <pre class="lang-hs prettyprint-override"><code>module Day2 where import Data.Vector (Vector, fromList, head, (!), (//)) import Data.List.Split (splitOn) type Intcode = Vector Int data Op = Add | Mult | Noop intToOp :: Int -&gt; Op intToOp 1 = Add intToOp 2 = Mult intToOp 99 = Noop intToOp x = error $ "invalid opCode, should not happen" ++ show x eval :: Intcode -&gt; Intcode eval intcode = go intcode 0 where go intcode currentIndex = let op = intToOp $ intcode ! currentIndex v1Pos = intcode ! (currentIndex + 1) v2Pos = intcode ! (currentIndex + 2) savePos = intcode ! (currentIndex + 3) nextIndex = currentIndex + 4 v1 = intcode ! v1Pos v2 = intcode ! v2Pos in case op of Add -&gt; go (intcode // [(savePos, (v1 + v2))]) nextIndex Mult -&gt; go (intcode // [(savePos, (v1 * v2))]) nextIndex Noop -&gt; intcode part1 :: IO () part1 = do input &lt;- readFile "../input/day2.txt" let intcode = fromList (read &lt;$&gt; splitOn "," input) let result = eval $ intcode // [(1, 12), (2, 2)] putStrLn $ show $ result ! 0 part2 :: IO () part2 = do input &lt;- readFile "../input/day2.txt" let memory = fromList (read &lt;$&gt; splitOn "," input) let inputs = [(i, j) | i &lt;- [0..99], j &lt;- [0..99]] let results = fmap (\(noun, verb) -&gt; (eval $ memory // [(1, noun), (2, verb)], noun, verb)) inputs let (result, noun, verb) = Prelude.head $ filter (\(res, _, _) -&gt; (res ! 0) == 19690720) results putStrLn $ show $ 100 * noun + verb </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T15:19:07.070", "Id": "456602", "Score": "0", "body": "Links can rot. [Please include a description of the challenge here in your question.](//codereview.meta.stackexchange.com/q/1993)" } ]
[ { "body": "<p><code>slice</code> combines some lookups. The index arithmetic can be frontloaded.</p>\n\n<pre><code>eval :: Intcode -&gt; Intcode\neval = go [0,4..] where\n go (index:es) intcode =\n let\n [opcode, v1Pos, v2Pos, savePos] = toList $ slice index 4 intcode\n v1 = intcode ! v1Pos\n v2 = intcode ! v2Pos\n in\n case intToOp opcode of\n Add -&gt; go es $ intcode // [(savePos, v1 + v2)]\n Mult -&gt; go es $ intcode // [(savePos, v1 * v2)]\n Noop -&gt; intcode\n</code></pre>\n\n<p><code>//</code> takes linear time on immutable vectors. <code>Noop</code> should be <code>Halt</code>. This displays the unreliability of adding data types for their suggestive names. Therefore, inline <code>intToOp</code>.</p>\n\n<pre><code>eval :: Intcode -&gt; Intcode\neval = modify $ \\intcode -&gt;\n void $ runMaybeT $ for_ [0,4..] $ \\index -&gt; do\n [opcode, v1Pos, v2Pos, savePos] &lt;- traverse (read intcode) [index..index+3]\n v1 &lt;- read intcode v1Pos\n v2 &lt;- read intcode v2Pos\n case opcode of\n 1 -&gt; lift $ write intcode savePos $ v1 + v2\n 2 -&gt; lift $ write intcode savePos $ v1 * v2\n 99 -&gt; empty\n _ -&gt; error $ \"invalid opCode, should not happen\" ++ show opcode\n</code></pre>\n\n<p>Of course, all of this imperativeness doesn't feel Haskell. However, interpreting an imperative language is pretty much the one time you need not feel bad about that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:25:48.437", "Id": "233555", "ParentId": "233544", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T14:09:21.430", "Id": "233544", "Score": "2", "Tags": [ "haskell" ], "Title": "Advent of Code 2019, Day 2 in Haskell" }
233544
<p>I am trying to write my own implementation of a hash table (hash map) in C++. It turns out that my code is unoptimized as I can't pass performance tests. Can you please give some advice for optimization of the program?</p> <p>I am using open addressing for resolving collisions with quadratic probing. Hash function for string: value of polynom, coefs of polynom - every single char of string. Only strings are inserted into hash table</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cmath&gt; //HashTable class /* Using open adressing for resolving collisions with quadratic probing */ class HashTable { public: HashTable(); bool Set(std::string key); bool Remove(std::string key); bool Get(std::string key); private: int GetHash(std::string text, int table_size); std::vector&lt;std::pair&lt;std::string, bool&gt;&gt; table; void ExtendTable(); size_t fullness = 0; }; HashTable::HashTable() { //first element of pair - key, second - is the cell free for(int i = 0; i &lt; 8; i++) { table.push_back(std::make_pair("",true)); } } int HashTable::GetHash(std::string text, int table_size) { //Hash function for string. Calculates polynom value using Horner method int b = text[0]; int point = (int)sqrt(table_size); //x value for polynom for(int i = 1; i &lt; text.size(); i++) { b = (text[i] + b*point) % table_size; } return b % table_size; } void HashTable::ExtendTable() { //Extends table if fullness == 3/4 * size of table //creates new table std::vector&lt;std::pair&lt;std::string, bool&gt;&gt; new_table; for(int i = 0; i &lt; 2*this-&gt;table.size(); i++) { new_table.push_back(std::make_pair("", true)); } //copying old table to a new one for(int i = 0; i &lt; this-&gt;table.size(); i++) { int new_index = GetHash(this-&gt;table[i].first, 2*this-&gt;table.size()); int step = 1; while(!new_table[new_index].second) { new_index += pow(step, 2); new_index %= 2*this-&gt;table.size(); step++; } new_table[new_index] = this-&gt;table[i]; } this-&gt;table = new_table; } bool HashTable::Set(std::string key) { //Adding new element to hash table. Dublicates are ignored int index = GetHash(key, this-&gt;table.size()); int step = 1; while(!this-&gt;table[index].second) { if(this-&gt;table[index].first == key) return false; index += pow(step, 2); index %= this-&gt;table.size(); step++; } this-&gt;table[index] = std::make_pair(key, false); this-&gt;fullness++; if(this-&gt;fullness*4 &gt;= this-&gt;table.size()*3) ExtendTable(); return true; } bool HashTable::Get(std::string key) { //Checks if element is in hash table int index = GetHash(key, this-&gt;table.size()); int step = 1; int counter = 0; while(counter &lt; this-&gt;fullness+1) { if(this-&gt;table[index].first == key) return true; index += pow(step, 2); index %= this-&gt;table.size(); step++; counter++; } return false; } bool HashTable::Remove(std::string key) { //removes hash table int index = GetHash(key, this-&gt;table.size()); int step = 0; int counter = 0; while(counter &lt; this-&gt;fullness+1) { if(this-&gt;table[index].first == key) { this-&gt;fullness--; this-&gt;table[index].first = ""; this-&gt;table[index].second = true; return true; } index += pow(step, 2); index %= this-&gt;table.size(); step++; counter++; } return false; } int main() { HashTable table; std::ios_base::sync_with_stdio(0),std::cin.tie(0),std::cout.tie(0); std::string input = ""; while(std::cin &gt;&gt; input) { if(input == "+") { std::cin &gt;&gt; input; bool flag = table.Set(input); if(flag) std::cout &lt;&lt; "OK" &lt;&lt; std::endl; else std::cout &lt;&lt; "FAIL" &lt;&lt; std::endl; } else if(input == "?") { std::cin &gt;&gt; input; bool flag = table.Get(input); if(flag) std::cout &lt;&lt; "OK" &lt;&lt; std::endl; else std::cout &lt;&lt; "FAIL" &lt;&lt; std::endl; } else if(input == "-") { std::cin &gt;&gt; input; bool flag = table.Remove(input); if(flag) std::cout &lt;&lt; "OK" &lt;&lt; std::endl; else std::cout &lt;&lt; "FAIL" &lt;&lt; std::endl; } } return 0; } </code></pre>
[]
[ { "body": "<h1>The Hash</h1>\n\n<p>Your table looks to have a power-of-two size, starting at 8 and then doubling if needed. That's fine, good even, depending on how you use it.</p>\n\n<p>But then this happens:</p>\n\n<blockquote>\n<pre><code>int HashTable::GetHash(std::string text, int table_size) {\n //Hash function for string. Calculates polynom value using Horner method\n int b = text[0];\n int point = (int)sqrt(table_size); //x value for polynom\n for(int i = 1; i &lt; text.size(); i++) {\n b = (text[i] + b*point) % table_size;\n }\n return b % table_size;\n}\n</code></pre>\n</blockquote>\n\n<p>The slow square root is a problem of its own (how big of a problem depends on the size of the strings), but a <em>very bad effect</em> happens if <code>table_size</code> is a power of <em>four</em> (which it is half the time): <code>point</code> would be a power of two. So the multiplication (modulo a power of two) just shifts bits out of the top and loses them, deleting bits in a first-in-first-out fashion: the final hash is only affected by the last couple of characters, the bits from the first characters get shifted out. The effect gets worse as the table gets bigger, eventually only the very last character would be part of the hash.</p>\n\n<p>The overall effect on your program is that as the table gets bigger, performance fluctuates between OK (probably) for odd power sizes and Increasingly Bad for even power sizes, getting worse and worse for bigger tables and long strings that share a suffix.</p>\n\n<p>This wouldn't have been an issue for prime size tables, but that comes with a significant downside of its own.</p>\n\n<p>What to use instead: <code>std::hash&lt;std::string&gt;</code> probably, or write a hash that does not suffer from this problem, there are many string hashing algorithms that don't have this issue.</p>\n\n<p>Also <code>b</code> should really be some unsigned type, both to avoid the scary UB nature of signed integer overflow and also the more practical concern of avoiding a negative value as result (as a reminder, <code>%</code> on signed types returns the <em>signed remainder</em>, the result can be negative depending on the inputs). Which leads to:</p>\n\n<h1>The Types</h1>\n\n<p>A lot of variables and return types here are of type <code>int</code>. Many of them should be something else, such as <code>size_t</code>. Using <code>int</code> results in many unexpected type conversions, for example in <code>index %= this-&gt;table.size();</code> which actually converts <code>index</code> to <code>size_t</code> first, then does the remainder, then converts back to an <code>int</code> again. Having a signed index risks overflowing it if the <code>step</code> gets big, and often costs an explicit sign-extension operation.</p>\n\n<p>The first <code>index</code>, which comes from <code>GetHash</code>, could be negative, which would be bad (indexing the vector at a negative index).</p>\n\n<h1>The Quadratic step</h1>\n\n<p>You wrote:</p>\n\n<blockquote>\n <p><code>new_index += pow(step, 2);</code></p>\n</blockquote>\n\n<p>That's a common thing for beginners to write, but unfortunately, that's a floating point square. The resulting code on x64 with Clang 9 and -O2 is:</p>\n\n<pre><code> xorps xmm0, xmm0\n cvtsi2sd xmm0, r14d\n xorps xmm1, xmm1\n cvtsi2sd xmm1, ebx\n mulsd xmm0, xmm0\n addsd xmm1, xmm0\n cvttsd2si eax, xmm1\n</code></pre>\n\n<p>A lot of converting and other floating point operations.</p>\n\n<p>Writing it as <code>new_index += step * step;</code> results in:</p>\n\n<pre><code> mov eax, edi\n imul eax, edi\n add eax, ebx\n</code></pre>\n\n<p>But it turns out you don't even need this, see further below..</p>\n\n<h1>The Modulo</h1>\n\n<p>You wrote:</p>\n\n<blockquote>\n <p><code>index %= this-&gt;table.size();</code></p>\n</blockquote>\n\n<p>Which does not use that the table size is a power of two, so for example on x64 with Clang 9 and -O2 again, that results in:</p>\n\n<pre><code> cdqe\n xor edx, edx\n div rsi\n ; use rdx (the remainder)\n</code></pre>\n\n<p>A 64-bit <code>div</code> ranges from slow to very slow. The time depends on the processor model and on the values being divided and on whether we're measuring latency or throughput (or a bit of both?), so it's difficult to pin a single number to it, but as a ballpark number let's say it's around 50x as slow as integer addition. Division (and therefore remainder) is a difficult operation, so this issue is not restricted to x64 processors.</p>\n\n<p>Having a power-of-two sized table is perfect to avoid that operation, you can use (and it's a waste of the opportunity to not use this):</p>\n\n<pre><code>index &amp;= this-&gt;table.size() - 1;\n</code></pre>\n\n<p>Unfortunately compilers are not yet so sophisticated that they can discover and track the property of the size being a power of two through the program. Such optimizations do happen locally, <a href=\"https://godbolt.org/z/cHSTke\" rel=\"nofollow noreferrer\">if the divisor is obviously a power of two</a> which is much easier for a compiler to discover than a more \"global\" invariant of your data structure.</p>\n\n<h1>Non-termination of <code>Set</code></h1>\n\n<p>It's unlikely, but <code>Set</code> could loop forever. What that takes is a probe sequence that visits only filled slots. You might expect the 75% fullness bound to prevent that, but this probe sequence (cumulatively adding <code>i²</code> modulo a power of two), while not too bad, does not guarantee visiting 75% of the slots. There is a probe sequence that <em>does</em> guarantee that:</p>\n\n<pre><code>index += step;\n</code></pre>\n\n<p>Doesn't look quadratic? It is! <code>step</code> goes up by 1 every step, so the sequence formed by <code>index</code> has the closed form formula <code>index(i) = initialHash + (i² + i) / 2</code>: the famous <a href=\"https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/\" rel=\"nofollow noreferrer\">triangular numbers based quadratic probing</a>. That will visit <em>every</em> slot (if necessary, of course escaping from the loop early is encouraged!) with no duplicates, so there would be no accidental infinite loop.</p>\n\n<hr>\n\n<p>Well this may all look pretty negative, but there are a couple of things I definitely liked in that code: firstly using <code>std::vector</code> for the storage, so this class does not need to concern itself with memory management. And this trick, <code>this-&gt;fullness*4 &gt;= this-&gt;table.size()*3</code>, rather than multiplying by a floating point number.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:30:28.873", "Id": "456618", "Score": "0", "body": "Wow! Thanks for an amazing code review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:49:09.633", "Id": "456622", "Score": "0", "body": "By the way, can I replace ```int point = (int)sqrt(table_size)``` with ```int point = 31``` or another prime number?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T05:37:33.483", "Id": "456658", "Score": "0", "body": "@ДанилаМишин yes that would work" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T17:02:33.200", "Id": "233550", "ParentId": "233545", "Score": "3" } } ]
{ "AcceptedAnswerId": "233550", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T14:46:06.800", "Id": "233545", "Score": "1", "Tags": [ "c++", "programming-challenge", "reinventing-the-wheel", "homework" ], "Title": "Optimizing Hash Table" }
233545
<p>I need help to dynamically create an array with nested objects holding again an array of objects each. The structure is as follows:</p> <pre><code>tiles=[ { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] }, { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] }, { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] }, { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] } ]; </code></pre> <p>However, the amount of row objects and amount of rows is dynamic. In the example above, it's 3 x 4.</p> <p>My current approach is a simple nested loop:</p> <pre class="lang-js prettyprint-override"><code>updateTileEditor(x: number, y: number) { this.tiles = []; for (var i = 0; i &lt; y; i++) { let helperArray = []; for (var j = 0; j &lt; x; j++) { helperArray.push({ isChecked: true, src: '' }); } this.tiles.push({ "row": helperArray }); } } </code></pre> <p>Could you perhaps propose a more feasable approach to this?</p> <p>Be aware that every nested object of the nested array must be a different object. In other words, the objects can not point to the same reference.</p> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T20:14:10.523", "Id": "456631", "Score": "1", "body": "I'm having a hard time following you. Perhaps if we understood the application of the function we might be able to assist you in refactoring. For instance, what does \"Be aware that every nested object of the nested array must be a different object. In other words, the objects can not point to the same reference.\" mean? No two sub-objects can be the same or that sub-objects can't be the same as a parent level object? I see no logic in your current function to check any of this, so I'm confused as to what you're trying to communicate." } ]
[ { "body": "<p>I can propose more functional approach. I don't have arguments to say that it's better, it's just how I prefer to write code for generating two-dimensional arrays filled with some initial values.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function createRow(rowLength: number) {\n return Array(rowLength).fill(null).map(() =&gt; ({\n isChecked: true,\n src: ''\n }))\n}\n\nfunction updateTileEditor(length: number, height: number) {\n this.tiles = Array(height).fill(null).map(() =&gt; ({\n row: createRow(length)\n }));\n}\n</code></pre>\n\n<p>Explanation: </p>\n\n<ul>\n<li><code>Array(height)</code> creates an empty array of fixed size <code>height</code> - we want to create <code>height</code> rows.</li>\n<li><code>.fill(null)</code> is used to fill the array with any values, so you can map these values to new ones. Any other value can be used instead of <code>null</code>. Mapping empty array would return us new empty array.</li>\n<li><code>.map(() =&gt; createRow(rowLength))</code> creates new array in which each value is a new row. <code>() =&gt; createRow(rowLength)</code> gets called for each value in the array, so you can be sure that you will have new row for each value.</li>\n</ul>\n\n<p>I also renamed <code>x</code> to <code>length</code> and <code>y</code> to <code>height</code> - these names are more descriptive, which I think can help new readers with figuring out the purpose of these variables.</p>\n\n<p>I will write it here, because I don't have enough reputation to comment:\nyou could also use arrays for rows instead of objects that have one property called \"row\".\nIf you have only one value then maybe you don't need to wrap it in an object? - I guess I would need more details about the problem to say that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T17:43:22.450", "Id": "233600", "ParentId": "233548", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T16:40:47.103", "Id": "233548", "Score": "3", "Tags": [ "javascript", "typescript", "angular-2+" ], "Title": "Dynamically create array with nested objects/array" }
233548
<p>Please review the following code for thread pool in C (I wrote it to implement a threaded web server for my personal project). I have been programming in C++ and Java but never did any serious programming in C.</p> <p>threadpool.h</p> <pre><code>#ifndef THREAD_POOL_H #define THREAD_POOL_H #include &lt;pthread.h&gt; #define MAX_THREAD 10 typedef struct { void *(*function) (void *); } runnable_task; typedef struct safe_queue_node { runnable_task *task; struct safe_queue_node *next; } safe_queue_node; typedef struct safe_queue{ struct safe_queue_node *head; struct safe_queue_node *tail; pthread_mutex_t mutex; } safe_queue; typedef struct { pthread_t threads[MAX_THREAD]; safe_queue *queue; int count; volatile int should_close; } thread_pool; runnable_task * new_runnable_task( void *(*function) (void *)); thread_pool * new_thread_pool(); void free_thread_pool( thread_pool *pool); void add_task_to_pool( thread_pool *pool, runnable_task *task); void shutdown_thread_pool( thread_pool *pool); #endif </code></pre> <p>threadpool.c</p> <pre><code>#include "threadpool.h" #include &lt;stdlib.h&gt; runnable_task * new_runnable_task( void *(*function) (void *)) { runnable_task *task = malloc(sizeof(runnable_task)); task-&gt;function = function; return task; } safe_queue_node * _new_safe_queue_node( runnable_task *task) { safe_queue_node *node = malloc(sizeof(safe_queue_node)); node-&gt;task = task; node-&gt;next = NULL; return node; } safe_queue * _new_safe_queue() { safe_queue *queue = malloc(sizeof(safe_queue)); pthread_mutex_init(&amp;queue-&gt;mutex, NULL); queue-&gt;head = NULL; queue-&gt;tail = NULL; return queue; } void _free_safe_queue( safe_queue *queue) { free(queue); } runnable_task * _get_from_queue( safe_queue *queue) { runnable_task *task = NULL; pthread_mutex_lock(&amp;queue-&gt;mutex); if (queue-&gt;head != NULL) { task = queue-&gt;head-&gt;task; queue-&gt;head = queue-&gt;head-&gt;next; if (queue-&gt;head == NULL) queue-&gt;tail = NULL; } pthread_mutex_unlock(&amp;queue-&gt;mutex); return task; } void * _run_task( void *arg) { thread_pool *pool = (thread_pool *) arg; while (!pool-&gt;should_close) { runnable_task *task = _get_from_queue(pool-&gt;queue); if (task == NULL) continue; task-&gt;function(NULL); } return NULL; } thread_pool * new_thread_pool( int count) { thread_pool *pool = malloc(sizeof(thread_pool)); pool-&gt;queue = _new_safe_queue(); pool-&gt;count = count &lt;= MAX_THREAD ? count : MAX_THREAD; pool-&gt;should_close = 0; for (int i = 0; i &lt; pool-&gt;count; i++) { pthread_create(pool-&gt;threads + i, NULL, _run_task, pool); } return pool; } void free_thread_pool( thread_pool *pool) { _free_safe_queue(pool-&gt;queue); free(pool); } void _add_to_queue( safe_queue *queue, runnable_task *task) { pthread_mutex_lock(&amp;queue-&gt;mutex); if (queue-&gt;head == NULL) { queue-&gt;head = queue-&gt;tail = _new_safe_queue_node(task); } else { queue-&gt;tail-&gt;next = _new_safe_queue_node(task); queue-&gt;tail = queue-&gt;tail-&gt;next; } pthread_mutex_unlock(&amp;queue-&gt;mutex); } void add_task_to_pool( thread_pool *pool, runnable_task *task) { _add_to_queue(pool-&gt;queue, task); } void shutdown_thread_pool( thread_pool *pool) { while (pool-&gt;queue-&gt;head != NULL) ; pool-&gt;should_close = 1; for (int i = 0; i &lt; pool-&gt;count; i++) pthread_join(pool-&gt;threads[i], NULL); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:26:33.447", "Id": "456615", "Score": "0", "body": "A single threaded server should be able to handle 10K requests. Multithreading is overkill. Don't make the mistake of each request is served by a single dedicated thread. Note: Most of the time on requests is spent waiting for IO to become ready it is not highly computational so you want to concentrate on making sure your workers don't wait for IO but move to the next request that has IO available to processes (in or out)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:27:36.827", "Id": "456616", "Score": "0", "body": "see the C10K problem: https://en.wikipedia.org/wiki/C10k_problem" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T18:29:13.517", "Id": "456617", "Score": "0", "body": "This is why the highly efficient web server `Node.js` is a single threaded server." } ]
[ { "body": "<ul>\n<li><p>Busy waiting on an empty queue is <a href=\"https://en.wikipedia.org/wiki/Newspeak#Vocabulary\" rel=\"nofollow noreferrer\">doubleplusungood</a>. Add a condition variable to the queue, let the threads to <a href=\"https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html\" rel=\"nofollow noreferrer\"><code>pthread_cond_wait</code></a> on it, and <a href=\"https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_signal.html\" rel=\"nofollow noreferrer\"><code>pthread_cond_signal</code></a> it when adding the task to the queue.</p></li>\n<li><p>The functions you don't want to export (those with the leading underscores) shall be <code>static</code>.</p></li>\n<li><p><code>sizeof(type)</code> may lead to a double maintenance problem. Prefer <code>sizeof(var)</code>, as in</p>\n\n<pre><code>thread_pool *pool = malloc(sizeof(*pool));\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T18:54:54.937", "Id": "233601", "ParentId": "233551", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T17:15:03.240", "Id": "233551", "Score": "2", "Tags": [ "c", "multithreading", "pthreads" ], "Title": "Thread Pool in C for web server" }
233551
<p>The following piece of code will print a text based on the divisibility of number.<br> If the number is not divisible by 3, 5 and 7, then the number gets printed.</p> <p>Does making use of a f-string make the type cast of integers to string implicit?</p> <pre class="lang-python prettyprint-override"><code>def convert(number): result = "" if (number % 3 == 0): result += "Pling" if (number % 5 == 0): result += "Plang" if (number % 7 == 0): result += "Plong" if(number % 7 != 0 and number % 5 != 0 and number%3 != 0): result = f{'number'} return result </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:10:12.767", "Id": "456727", "Score": "0", "body": "There is no way that this code can work. You have a SyntaxError which errors on malformed Python syntax - before the code even runs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:53:53.677", "Id": "456765", "Score": "0", "body": "@Peilonrayz I've tried it on multiple simple numbers and it errors on that too." } ]
[ { "body": "<p>In programming, there are only three useful numbers, 0, 1, and many.</p>\n\n<p>If you write an if-condition that repeats all the tests already done, you're doing something wrong.</p>\n\n<p>If you write similar ad hoc code for three special cases, you're doing something wrong.</p>\n\n<p>E.g. adding \"11 Plung\" will require two more lines for the special case and the \"no match\" case will have to be made even longer and uglier.</p>\n\n<p>Write simple code for a general case, and then supply specific data as needed:</p>\n\n<pre><code>def convert(number):\n names = [ [3, \"Pling\"], [5, \"Plang\"], [7, \"Plong\"] ]\n result = \"\"\n for value,message in names:\n if not number % value: result += message\n if message == \"\": message = f\"{number}\"\n return result\n\nfor index in range(1,25): print(index, convert(index))\n</code></pre>\n\n<p>That way, if you later need to add the \"11\" case, it's a simple change, and more importantly it happens in only one place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T00:43:23.740", "Id": "233566", "ParentId": "233562", "Score": "4" } }, { "body": "<p>Comprehension can handle your parameters instead of using <code>elif</code> statements. Just as an example I have converted the list into key:value pairs. The <code>if</code> statement is only allowing things to populate the new dictionary that satisfy the argument.</p>\n\n<pre><code>names = [ [3, \"Pling\"], [5, \"Plang\"], [7, \"Plong\"] ]\n\nnew_dict = {i: k for i, k in names if i%i == 0}\n</code></pre>\n\n<p>Python will process the input in the format you want.</p>\n\n<pre><code>import string\n\nnew_string_digits = string.digits\nprint(type(new_string_digits), new_string_digits, new_string_digits*2)\nstring_to_number = int(new_string_digits)\nprint(type(string_to_number), string_to_number, string_to_number*2)\n</code></pre>\n\n<p>Notice the difference in how the compiler has processed the information:</p>\n\n<pre><code>&lt;class 'str'&gt; 0123456789 01234567890123456789\n&lt;class 'int'&gt; 123456789 246913578\n</code></pre>\n\n<p>In the <code>str</code> instance it has just repeated the string input and in the <code>int</code> instance the number has been multiplied. I find it quite useful to convert the two because its easy to extract or plug information into without needing to use complex calculations or arguments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T02:52:20.100", "Id": "233570", "ParentId": "233562", "Score": "2" } } ]
{ "AcceptedAnswerId": "233566", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T21:47:48.307", "Id": "233562", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Printing text based on divisibility of number" }
233562
<p>I created this package <a href="https://github.com/hxtree/PXP/" rel="nofollow noreferrer">PXP</a>.</p> <blockquote> <p>PXP enables markup to instantiate objects, call methods, and generate HTML. It works similar to a server-side templating engine, but rather than enforcing braces it enables developers to use markup to build dynamic web pages.</p> </blockquote> <p>I'm interested primary in feedback related to core implement below, which is implements a builder design pattern, is at the heart of the package, and nearing a 1.0 (although any feedback as an issues is welcomed).</p> <p>What is done right?<br /> What can be done to improve this package?</p> <p>PXP/src/Page/PageDirector.php</p> <pre><code>&lt;?php /** * This file is part of the PXP package. * * (c) Matthew Heroux &lt;matthewheroux@gmail.com&gt; * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pxp\Page; use Pxp\Page\Builder\Builder; /** * Class PageDirector * @package Pxp\Page */ class PageDirector { /** * Calls Builder using parameters supplied * * @param Builder $builder * @param $parameters * @return object */ public function build(Builder &amp;$builder, $parameters): object { $builder-&gt;createObject($parameters); return $builder-&gt;getObject(); } } </code></pre> <p>PXP/src/Page/Builder/DynamicBuilder.php</p> <pre><code>&lt;?php /** * This file is part of the PXP package. * * (c) Matthew Heroux &lt;matthewheroux@gmail.com&gt; * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pxp\Page\Builder; use Pxp\Page\Page as Page; /** * Class DynamicBuilder * @package Pxp\Page\Builder */ class DynamicBuilder extends Builder { private $page; /** * Creates Page object using parameters supplied * * @param $parameters * @return bool|null */ public function createObject(array $parameters): ?bool { if (!isset($parameters['filename'])) { return false; } $this-&gt;page = new Page($parameters['filename']); // instantiate dynamic elements if (is_array($parameters['handlers'])) { foreach ($parameters['handlers'] as $xpath_expression =&gt; $class_name) { $this-&gt;page-&gt;instantiateElement($xpath_expression, $class_name); } } // call hooks if (is_array($parameters['hooks'])) { foreach ($parameters['hooks'] as $name =&gt; $description) { $this-&gt;page-&gt;callHook($name, $description); } } return true; } /** * Gets Page object * * @return object|null */ public function getObject(): ?object { return $this-&gt;page; } } </code></pre> <p>PXP/src/Page/Page.php</p> <pre><code>&lt;?php /** * This file is part of the PXP package. * * (c) Matthew Heroux &lt;matthewheroux@gmail.com&gt; * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pxp\Page; /** * Interface PageDefaultInterface * @package Pxp\Page */ interface PageDefaultInterface { public function loadByPath(string $filepath): void; public function __toString(): string; public function callHook(string $hook_name, string $options = null): bool; public function instantiateElement(string $xpath_expression, string $class_name): bool; public function replaceElement(\DOMElement &amp;$element, string $new_xml): void; public function query($query); } /** * Class Page * * Features a DOM loaded from a HTML/XML document that is modified during runtime * * @package Pxp\Page */ class Page implements PageDefaultInterface { // Document Object Model (DOM) public $dom; // DOM XPath Query object public $xpath; // instantiated DynamicElements public $element_objects; // name of function called to load DynamicElement Args by ID public $arg_load_function; // DomDocument object setting to preserve white space public $preserveWhiteSpace = false; // DomDocument format output option public $formatOutput = true; // DomDocument strict error checking setting public $strictErrorChecking = false; // validate DOM on Parse public $validateOnParse = false; // DomDocument encoding public $encoding = 'UTF-8'; // registered includes added during output public $includes = [ 'js' =&gt; [], 'css' =&gt; [] ]; // entities are required to avoid server side DOM parse errors public $entities = [ 'nbsp' =&gt; '&amp;#160;', 'copy' =&gt; '&amp;#169;', 'reg' =&gt; '&amp;#174;', 'trade' =&gt; '&amp;#8482;', 'mdash' =&gt; '&amp;#8212;' ]; // DynamicElement placeholder ID attribute private $element_index_attribute = '_pxp_ref'; // DomDocument LibXML debug private $libxml_debug = false; /** * Page constructor * * @param null $filename */ public function __construct($filename = null) { // create a document object model $this-&gt;dom = new \DomDocument(); // objects containing elements $this-&gt;element_objects = new \SplObjectStorage(); // surpress xml parse errors unless debugging if (!$this-&gt;libxml_debug) { libxml_use_internal_errors(true); } if ($filename != null) { $this-&gt;loadByPath($filename); } } /** * Custom load page wrapper for server side HTML5 entity support * * @param string $filepath */ public function loadByPath(string $filepath): void { if (filter_var($filepath, FILTER_VALIDATE_URL)) { // if existing website $source = file_get_contents($filepath); $this-&gt;dom-&gt;loadHTML($source); } else { // entities are automatically removed before sending to client $entity = ''; foreach ($this-&gt;entities as $key =&gt; $value) { $entity .= '&lt;!ENTITY ' . $key . ' &quot;' . $value . '&quot;&gt;' . PHP_EOL; } // deliberately build out doc-type and grab file contents // using alternative loadHTMLFile removes HTML entities (&amp;copy; etc.) $source = '&lt;!DOCTYPE html [' . $entity . ']&gt; '; $source .= file_get_contents($filepath); $this-&gt;dom-&gt;loadXML($source); } // create document iterator $this-&gt;xpath = new \DOMXPath($this-&gt;dom); } /** * Calls single method to each instantiated DynamicElement * * @param string $hook_name * @param string|NULL $options * @return bool */ public function callHook(string $hook_name, string $options = null): bool { // iterate through elements foreach ($this-&gt;element_objects as $element) { // skip if element does not feature hook if (!method_exists($element, $hook_name)) { continue; } // on render if ($options == 'RETURN_CALL') { $query = '//*[@' . $this-&gt;element_index_attribute . '=&quot;' . $element-&gt;placeholder_id . '&quot;]'; foreach ($this-&gt;query($query) as $replace_element) { $new_xml = $element-&gt;__toString(); $this-&gt;replaceElement($replace_element, $new_xml); continue; } } else { // call element method call_user_func([ $element, $hook_name ]); } } return true; } /** * XPath query for DOM * * @param $query * @return mixed */ public function query($query) { return $this-&gt;xpath-&gt;query($query); } /** * Replaces element contents * * @param \DOMElement $element * @param string $new_xml */ public function replaceElement(\DOMElement &amp;$element, string $new_xml): void { // create a blank document fragment $fragment = $this-&gt;dom-&gt;createDocumentFragment(); $fragment-&gt;appendXML($new_xml); // replace parent nodes child element with new fragement $element-&gt;parentNode-&gt;replaceChild($fragment, $element); } /** * Instantiates dynamic elements found during xpath query * * @param string $xpath_expression * @param string $class_name * @return bool */ public function instantiateElement(string $xpath_expression, string $class_name): bool { // if class does not exist replace element with informative comment // iterate through handler's expression searching for applicable elements foreach ($this-&gt;query($xpath_expression) as $element) { // skip if placeholder already assigned if ($element-&gt;hasAttribute($this-&gt;element_index_attribute)) { continue; } // resolve class name $element_class_name = $class_name; if ($element-&gt;hasAttribute('name')) { $element_name = $element-&gt;getAttribute('name'); $element_class_name = str_replace('{name}', $element_name, $class_name); } // if class does not exist if (!class_exists($element_class_name)) { $this-&gt;replaceElement($element, '&lt;!-- Handler &quot;' . $element_class_name . '&quot; Not Found --&gt;'); continue; } // get xml from element $xml = $this-&gt;getXml($element); // get args from element $args = $this-&gt;getArgs($element); // instantiate element $element_object = new $element_class_name($xml, $args); // object not instantiated if (!is_object($element_object)) { $this-&gt;replaceElement($element, '&lt;!-- Handler &quot;' . $element_class_name . '&quot; Error --&gt;'); continue; } // set element object placeholder $element-&gt;setAttribute($this-&gt;element_index_attribute, $element_object-&gt;placeholder_id); // store object $this-&gt;element_objects-&gt;attach($element_object); } return true; } /** * Get element's innerXML * * @param \DOMElement $element * @return string */ private function getXml(\DOMElement $element): string { $xml = ''; $children = $element-&gt;childNodes; foreach ($children as $child) { $xml .= $element-&gt;ownerDocument-&gt;saveHTML($child); } return $xml; } /** * Get element's ARGs * * @param \DOMElement $element * @return array */ private function getArgs(\DOMElement &amp;$element): array { $args = []; // get attributes if ($element-&gt;hasAttributes()) { foreach ($element-&gt;attributes as $name =&gt; $attribute) { $args[$name] = $attribute-&gt;value; } } // get child args $objects = $element-&gt;getElementsByTagName('arg'); foreach ($objects as $object) { $name = $object-&gt;getAttribute('name'); $value = $object-&gt;nodeValue; $args[$name] = $value; } // use element id attribute to load args if ($element-&gt;hasAttribute('id')) { $element_id = $element-&gt;getAttribute('id'); // allow director to specify function to load args from based on id if (function_exists($this-&gt;arg_load_function)) { $args_loaded = call_user_func($this-&gt;arg_load_function, $element_id); // merge args $args = array_merge($args_loaded, $args); } } return $args; } /** * Returns DomDocument as HTML * * @return string */ public function __toString(): string { return $this-&gt;dom-&gt;saveHTML(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T12:25:17.350", "Id": "456723", "Score": "0", "body": "Thank you for your question. I find it hard to understand [what your code does an how it can be used](https://pxp.readthedocs.io/en/latest). It is no good having a library that no one can use because they can't understand it. As a programmer, not a user, I would also like to know why you chose this structure. What is the purpose of a `PageDirector`, `PageBuilder`, `Page`, etc? I understand that you have concentrated your efforts on the technical implementation, but we can only review code if we can understand the ideas and concepts behind it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T00:13:31.893", "Id": "456793", "Score": "0", "body": "Thank you @KIKOSoftware. You are 100% correct! The docs/readme are scribbles (I was experimenting with PHP phpdocumentor doing reST and not there yet, will manually write ASAP); please try the examples, they should make sense. The design pattern was chosen to separate the construction of the complex page objects from its representation so that different types of pages could be built, e.g. static for (WYSIWYG), dynamic (for rendering to client), search index (to exclude dynamic objects marked), etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:56:45.613", "Id": "456842", "Score": "0", "body": "I did have a look at the examples, before I wrote the comment above. It seems your aim is to make it easier for programmers to write dynamic pages in HTML. However, to do so, they also need to write the matching PHP code, which, in my eyes, only complicates things. I agree that combining HTML and PHP in one file can be ugly, but it does keep things together. As for your implementation, I already indicated that I think you purely concentrated on the technology, and didn't think about the persons who are supposedly going to use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:47:19.507", "Id": "456896", "Score": "0", "body": "@KIKOSoftware the package adheres to the UNIX philosophy. Yes, the average Jane would be more likely to use a package that will include this package, which would feature built in DynamicElements, TinyMCE, etc. Your feedback is appreciated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T00:22:57.440", "Id": "233565", "Score": "4", "Tags": [ "php", "design-patterns", "xml", "template", "dom" ], "Title": "Enables markup to instantiate objects, call methods, and generate HTML" }
233565
<p>I am new in developer role, and I have my code which I would like to simplify or make it better. And wondering if someone can do a quick check.</p> <p>The code calculates the Score of the Bowling game, which is input as a string of the whole game (ex. as following: "X|7/|9-|x|-8|8/|-6|x|X|X||81").</p> <p>Program.cs</p> <pre><code> public class Program { public static void Main(string[] args) { Console.WriteLine("#=======================#"); Console.WriteLine("# Welcome to Ten-Pin Bowling! #"); Console.WriteLine("#=======================#"); var game = new TenPinGame("X|7/|9-|x|-8|8/|-6|x|X|X||81"); Console.WriteLine("Game: {0}", input); Console.WriteLine("Score: " + game.Score()); Console.WriteLine("#=====#"); } Console.WriteLine("Thank you for playing with us!"); Console.WriteLine("Have a nice day!"); Console.Read(); } } </code></pre> <p>TenPinGame.cs</p> <pre><code>public class TenPinGame : IGame { public const int MaxFrameNumber = 10; public const int StartingPinsNumber = 10; public List&lt;Frame&gt; Frames { get; } = new List&lt;Frame&gt;(); private string[] framesStringArray; public static string bonusSubsctring; public TenPinGame (string gameInput) { string framesSubstring = ParseGame(gameInput); framesStringArray = Utilities.SplitFramesString(framesSubstring, MaxFrameNumber); FrameRepository.ProcessFrameString(framesStringArray, Frames, MaxFrameNumber, StartingPinsNumber); } /// &lt;summary&gt; /// Splitting input string into 2 parts: Frames and Bonus throws /// &lt;/summary&gt; /// &lt;param name="gameInput"&gt;&lt;/param&gt; internal string ParseGame(string gameInput) { string framesSubstring = ""; if (gameInput.Contains("||")) { int index = gameInput.IndexOf("||"); framesSubstring = gameInput.Substring(0, index); bonusSubsctring = gameInput.Substring(index + 2); } return framesSubstring; } /// &lt;summary&gt; /// Calculate the Total score for the whole game/line. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public int Score() { int score = 0; foreach (var frame in Frames) { int frameIndex = Frames.IndexOf(frame); if (!frame.IsLastFrame &amp;&amp; frame.IsStrike) { if (Frames[frameIndex + 1].Throws.Count == 1) score += 10 + Frames[frameIndex + 1].Throws[0] + Frames[frameIndex + 2].Throws[0]; else if (Frames[frameIndex + 1].Throws.Count == 2 || Frames[frameIndex + 1].Throws.Count == 3) score += 10 + Frames[frameIndex + 1].Throws[0] + Frames[frameIndex + 1].Throws[1]; //else // throw new ArgumentException($"The next frame has invalid throws count {Frames[frameIndex + 1].Throws.Count}."); } else if (!frame.IsLastFrame &amp;&amp; frame.IsSpare) { score += 10 + Frames[frameIndex + 1].Throws[0]; } else if (frame.IsLastFrame &amp;&amp; frame.IsStrike) { score += 10 + Frames[frameIndex].Throws[1] + Frames[frameIndex].Throws[2]; } else if (frame.IsLastFrame &amp;&amp; frame.IsSpare) { score += 10 + Frames[frameIndex].Throws[1]; } else { score += frame.Throws[0] + frame.Throws[1]; } } return score; } } </code></pre> <p>Frame.cs</p> <pre><code>public class Frame { public List&lt;int&gt; Throws = new List&lt;int&gt;(); public int KnokcedDownPinsCount { get; set; } public bool IsStrike { get; set; } public bool IsSpare { get; set; } public bool IsLastFrame { get; set; } public bool IsBonusAllowed { get; set; } public bool IsFrameOver { get; set; } public Frame(bool isLastFrame = false) { this.IsLastFrame = isLastFrame; } public void ValidateEachThrow () { if (TenPinGame.StartingPinsNumber == 0) { throw new InvalidOperationException("Sorry, no pins are left standing."); } if (KnokcedDownPinsCount &lt; 0) { throw new InvalidOperationException($"Sorry, the # of knocked down pins {KnokcedDownPinsCount} is out of range."); } else if (KnokcedDownPinsCount &gt; TenPinGame.StartingPinsNumber) { throw new InvalidOperationException($"Sorry, the # of knocked down pins {KnokcedDownPinsCount} is is more than {TenPinGame.StartingPinsNumber} still standing pins."); } } } </code></pre> <p>Utilities.cs</p> <pre><code>public class Utilities { /// &lt;summary&gt; /// Split each frame into a separate string in the string array /// &lt;/summary&gt; /// &lt;param name="framesString"&gt;&lt;/param&gt; public static string[] SplitFramesString(string framesString, int maxFrameNumber) { string[] framesStringArray = Array.Empty&lt;string&gt;(); if (framesString.Contains("|")) { framesStringArray = framesString.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (framesStringArray.Length &gt; maxFrameNumber) { throw new ArgumentException($"Sorry, you have {framesStringArray.Length} frames, " + $"which is higher than Max number of {maxFrameNumber} frames allowed for this game."); } } return framesStringArray; } /// &lt;summary&gt; /// Process each charcters in the given frame and set corresponding frame properties accordingly. /// &lt;/summary&gt; /// &lt;param name="characterInString"&gt;&lt;/param&gt; /// &lt;param name="Frames"&gt;&lt;/param&gt; /// &lt;param name="stratingPinsNumber"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static int ProcessCharArray(char characterInString, Frame Frames, int stratingPinsNumber) { int pinsCount = 0; if (characterInString &gt;= '0' &amp;&amp; characterInString &lt;= '9') { Frames.Throws.Add((int)char.GetNumericValue(characterInString)); pinsCount = int.Parse(characterInString.ToString()); } else if (characterInString.ToString().ToUpperInvariant() == "X") { Frames.IsStrike = true; Frames.IsFrameOver = true; Frames.Throws.Add(10); pinsCount = 10; } else if (characterInString.ToString().ToUpperInvariant() == "/") { Frames.IsSpare = true; Frames.IsFrameOver = true; Frames.Throws.Add(stratingPinsNumber - Frames.Throws[0]); pinsCount = 10; } else if (characterInString.ToString().ToUpperInvariant() == "-") { Frames.Throws.Add(0); pinsCount += 0; } else if (characterInString.ToString().ToUpperInvariant() == "/" &amp;&amp; Frames.IsLastFrame &amp;&amp; Frames.IsBonusAllowed) { throw new ArgumentException("The Spare cannot be set on the Bonus Throws, please check."); } else { throw new ArgumentException($"Invalid argument '{characterInString}' was detected in the provided input, please check."); } return pinsCount; } } </code></pre> <p>FrameRepository.cs</p> <pre><code>public class FrameRepository { /// &lt;summary&gt; /// Process each frame-string in the frames string array, to determine the pins count for each frame /// &lt;/summary&gt; /// &lt;param name="framesList"&gt;&lt;/param&gt; public static void ProcessFrameString(string[] framesList, List&lt;Frame&gt; Frames, int MaxFrameNumber, int StartingPinsNumber) { foreach (var frame in framesList) { if (!Frames.Any() || Frames.Last().IsFrameOver) { var isLastFrame = Frames.Count == MaxFrameNumber - 1; Frames.Add(new Frame(isLastFrame)); } char[] frameCharArr = frame.ToCharArray(); foreach (char c in frameCharArr) { Frames.Last().KnokcedDownPinsCount = Utilities.ProcessCharArray(c, Frames.Last(), StartingPinsNumber); if (!Frames.Last().IsLastFrame &amp;&amp; Frames.Last().Throws.Count == 2) { Frames.Last().IsFrameOver = true; } } if (Frames.Count == MaxFrameNumber) { Frames.Last().IsLastFrame = true; char[] bonusCharArr = TenPinGame.bonusSubsctring.ToCharArray(); if (Frames.Last().IsStrike) { if (bonusCharArr.Length &gt; 2) { throw new ArgumentException($"The number of bonus throws {bonusCharArr.Length}, is over allowed for the Last Strike. Please check."); } Frames.Last().IsBonusAllowed = true; foreach (char c in bonusCharArr) { Frames.Last().KnokcedDownPinsCount = Utilities.ProcessCharArray(c, Frames.Last(), StartingPinsNumber); } } else if (Frames.Last().IsSpare) { if (bonusCharArr.Length != 1) { throw new ArgumentException($"The number of bonus throws {bonusCharArr.Length}, is over allowed for the Last Spare. Please check."); } Frames.Last().IsBonusAllowed = true; Frames.Last().KnokcedDownPinsCount = Utilities.ProcessCharArray(bonusCharArr[0], Frames.Last(), StartingPinsNumber); } } } } } </code></pre>
[]
[ { "body": "<p>Something to note: you pass the overall game data into TenPinGame as a string, which you then parse. It would make sense to parse this data first, then instantiate the Game object.</p>\n\n<p>Imagine if you had to add a new feature, which allowed users to input scores from a User Interface. You would then have two \"access points\", your <em>TenPinGame</em> class should reflect this.</p>\n\n<p>From what I can see, there are three functions relating to input parsing: <em>SplitFramesString</em>, <em>ProcessCharArray</em> and <em>ParseGame</em>. It would make sense to move these three functions into a separate <em>GameInputParser</em>, like so:</p>\n\n<pre><code>public class GameInputParser\n{\n public static string[] SplitFramesString(string framesString, int maxFrameNumber) { /*code*/ }\n\n public static int ProcessCharArray(char characterInString, Frame Frames, int stratingPinsNumber) { /*code*/ }\n\n internal string ParseGame(string gameInput) { /*code*/ }\n\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T21:28:06.727", "Id": "233607", "ParentId": "233567", "Score": "5" } }, { "body": "<p>From a functional perspective, you could change your <code>ProcessCharArray</code> to stop allocating unneeded memory on the heap by using this. Being that a <code>char</code> is derivative of <code>ValueType</code>. The memory will be allocated on the stack within your defined scope and will keep the GC from cleaning up the mess that's created with <code>characterInString.ToString().ToUpperInvariant() == \"X\"</code>.</p>\n\n<pre><code>public static int ProcessCharArray(char characterInString, Frame Frames, int \nstratingPinsNumber)\n{\n int pinsCount = 0;\n\nif (char.IsDigit(characterInString))\n{\n Frames.Throws.Add((int)char.GetNumericValue(characterInString));\n pinsCount = int.Parse(characterInString.ToString());\n}\nelse if (char.ToUpperInvariant(characterInString) == 'X')\n{\n Frames.IsStrike = true;\n Frames.IsFrameOver = true;\n Frames.Throws.Add(10);\n pinsCount = 10;\n}\nelse if (characterInString == '/')\n{\n Frames.IsSpare = true;\n Frames.IsFrameOver = true;\n Frames.Throws.Add(stratingPinsNumber - Frames.Throws[0]);\n pinsCount = 10;\n}\nelse if (characterInString == '-')\n{\n Frames.Throws.Add(0);\n pinsCount += 0;\n}\nelse if (characterInString == '/' &amp;&amp; Frames.IsLastFrame &amp;&amp; Frames.IsBonusAllowed)\n{\n throw new ArgumentException(\"The Spare cannot be set on the Bonus Throws, please check.\");\n}\nelse\n{\n throw new ArgumentException($\"Invalid argument '{characterInString}' was detected in the provided input, please check.\");\n}\n\n return pinsCount;\n}\n</code></pre>\n\n<p>here is an alternative approach for the logic in your method as well. :)</p>\n\n<pre><code>if (char.IsDigit(characterInString))\n{\n Frames.Throws.Add((int)char.GetNumericValue(characterInString));\n var pinsCount = int.Parse(characterInString.ToString());\n return pinsCount;\n}\n\nswitch(char.ToUpperInvariant(characterInString))\n{\n case 'X':\n Frames.IsStrike = true;\n Frames.IsFrameOver = true;\n Frames.Throws.Add(10);\n return 10;\n case '-':\n Frames.Throws.Add(0);\n return 0;\n case '/':\n if(Frames.IsLastFrame &amp;&amp; Frames.IsBonusAllowed)\n throw new ArgumentException(\"The Spare cannot be set on the Bonus Throws, please check.\");\n\n Frames.IsSpare = true;\n Frames.IsFrameOver = true;\n Frames.Throws.Add(stratingPinsNumber - Frames.Throws[0]);\n return 10;\n default : throw new ArgumentException($\"Invalid argument '{characterInString}' was detected in the provided input, please check.\"); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:36:22.013", "Id": "233704", "ParentId": "233567", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T00:54:32.217", "Id": "233567", "Score": "6", "Tags": [ "c#" ], "Title": "Calculation of the Bowling Game score" }
233567
<p><a href="https://i.stack.imgur.com/3XahS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3XahS.png" alt="enter image description here"></a></p> <p>I have polylines in a GIS database. The polylines are stored using a user-defined type called <a href="http://desktop.arcgis.com/en/arcmap/10.3/manage-data/using-sql-with-gdbs/what-is-the-st-geometry-storage-type.htm" rel="nofollow noreferrer">ST_GEOMETRY</a>.</p> <p>ST_GEOMETRY has lots of spatial functions. However, it does not have a polyline <strong>midpoint</strong> function.</p> <p>Therefore, I have written a custom PL/SQL <a href="https://math.stackexchange.com/questions/3457843/calculate-the-midpoint-of-a-polyline">midpoint</a> function to fill this gap.</p> <p>As a novice programmer, I'm wondering, how can the code be improved to be as fast and robust as possible?</p> <hr> <pre><code>-- execute this as the SDE user create or replace function ST_MidPoint (line_in IN sde.st_geometry) RETURN sde.st_geometry IS midpoint sde.st_geometry; srid integer; line_length number(38); num_parts integer; num_points integer; partNum integer; distanceAlong number(38); segmentLength number(38); part sde.st_geometry; p1 sde.st_geometry; p2 sde.st_geometry; x1 double precision; y1 double precision; x2 double precision; y2 double precision; BEGIN -- get the SRID of the line for later use in constructing the midpoint geometrey select sde.st_srid (line_in) into srid from dual; -- calculate the total length of the line select sde.st_length(line_in) into line_length from dual; -- get the number of parts that make up the line select sde.st_numgeometries(line_in) into num_parts from dual; distanceAlong := 0; for partNum in 1..num_parts loop --dbms_output.put_line(partNum); -- get the geometry for this part select sde.st_geometryn(line_in, partNum) into part from dual; -- get the number of points that make up this part select sde.st_numpoints(part) into num_points from dual; --dbms_output.put_line(num_points); -- get the first point (the "from" point) for the part select sde.st_pointn (part, 1) into p1 from dual; -- iterate along the line until the section that contains the midpoint is found for pointNum in 2..num_points loop -- get the "to" point of the segment select sde.st_pointn(part, pointNum) into p2 from dual; -- calculate the distance between the from point and the to point select sde.st_distance(p1, p2) into segmentLength from dual; -- add the distance along this segment to the running total distanceAlong := distanceAlong + segmentLength; --dbms_output.put_line(distanceAlong); -- check to see if the running total is past the midpoint if distanceAlong &gt;= line_length/2.0 then -- the two current points encompass the midpoint of the line -- determine the midpoint geometry and return it select sde.st_x(p1) into x1 from dual; select sde.st_y(p1) into y1 from dual; select sde.st_x(p2) into x2 from dual; select sde.st_y(p2) into y2 from dual; select sde.st_point((x1+x2)/2.0, (y1+y2)/2.0, srid) into midpoint from dual; -- the midpoint has been found, not need to interogate the rest of the line RETURN midpoint; end if; -- save the endpoint as the first point and continue down the line looking for the midpoint p1:=p2; end loop; end loop; return null; EXCEPTION WHEN OTHERS THEN raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM); END; / grant execute on ST_MidPoint to public; --select objectid,sde.ST_MidPoint(shape) geom --from gis.line_test --order by objectid; </code></pre> <p><strong>Update:</strong></p> <p>I have abandoned this function. It works, but it's horrendously inefficient because it's not possible to use the SDE functions &amp; operators to directly assign values to variables. I needed to wrap them in queries instead.</p> <p>More information here: <a href="https://gis.stackexchange.com/questions/344294/use-sde-st-geometry-functions-in-a-custom-function">Use SDE.ST_GEOMETRY functions in a custom function</a></p> <p>Originally, I had thought that the code could be improved. However, now I realize that this is not possible--due to the aforementioned problem.</p> <p>It would be my preference that this <strong>question be deleted</strong> (I tried but couldn't because there's an answer).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T00:20:18.487", "Id": "456705", "Score": "0", "body": "This is the reason why the INSERT INTOS were used: https://gis.stackexchange.com/q/344294/135445" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T00:24:40.197", "Id": "456706", "Score": "0", "body": "I think we should close this question. The function is so slow and poorly structured that it's not really useable. I'm going to go with another option (pre-compute with python)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:47:43.790", "Id": "456748", "Score": "2", "body": "You can write your own review explaining what makes the function poorly structured. There doesn't seem to be a valid reason to close the question, the other option is that you could delete it yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:02:52.717", "Id": "457764", "Score": "0", "body": "@pacmaninbw Yeah, I tried to delete the question, but I couldn't because there's an answer. I also added a note to the question about why the code can't be improved." } ]
[ { "body": "<p>I would recommend to try re-writing the procedure with Buffer and Centroid functions as below.</p>\n\n<p>procedure mindpoint (in_line_geometry)</p>\n\n<pre><code>line_buffer_geom = sde.st_buffer (in_line_geometry, 0.05)\ncenrtroid_buffer_geom = sde.st_centroid (line_buffer_geom )\nreturn cenrtroid_buffer_geom \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T04:00:35.857", "Id": "456655", "Score": "0", "body": "(Down-voters please comment.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T04:01:30.380", "Id": "456656", "Score": "0", "body": "The *cenrtroid* in `cenrtroid_buffer_geom` looks accidental." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T22:32:06.313", "Id": "502378", "Score": "0", "body": "Upon further testing, this doesn't seem to be a good approach. The midpoint doesn't get placed at the correct position along the line (especially curved lines). So, I think a true midpoint calculation would be better (example: a linear referencing solution)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T02:25:07.273", "Id": "233569", "ParentId": "233568", "Score": "1" } }, { "body": "<p>Check this function which returns the mid point X,Y in WKT format. Please note this function uses the SDO_LRS of Oracle which is part of Oracle Spatial.</p>\n\n<pre><code>create or replace function get_line_midpoint\n (line_in IN sde.st_geometry)\n -- RETURN sde.st_geometry\n RETURN VARCHAR2\nIS \nwkt_geometry clob;\nora_geometry sdo_geometry;\nmid_x number(10,6);\nmid_y number(10,6);\nmid_point_geom sde.st_geometry;\nBEGIN\n\nSELECT sde.ST_AsText(line_in) INTO wkt_geometry FROM DUAL;\nora_geometry := SDO_UTIL.FROM_WKTGEOMETRY(wkt_geometry);\n\n--mid_x:= sdo_cs.transform(SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)),8307).SDO_POINT.X;\nmid_x:= SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)).SDO_POINT.X;\n\n--mid_y:= sdo_cs.transform(SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)),8307).SDO_POINT.Y;\nmid_y:= SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)).SDO_POINT.Y;\n\nora_geometry := SDO_UTIL.FROM_WKTGEOMETRY('point ('|| mid_x || ' ' || mid_y ||')');\n\n\n\nreturn 'point ('|| mid_x || ' ' || mid_y ||')';\n\n\n\n\nEXCEPTION\nWHEN OTHERS THEN\n raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);\nEND;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-20T05:11:47.757", "Id": "458350", "Score": "1", "body": "Well, this changes things! [Spatial now free with all editions of Oracle Database](https://blogs.oracle.com/oraclespatial/spatial-now-free-with-all-editions-of-oracle-database)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-20T05:16:56.940", "Id": "458351", "Score": "0", "body": "Thanks for letting me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T11:55:27.063", "Id": "460111", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T23:43:44.627", "Id": "460333", "Score": "0", "body": "The procedure posted works fine. @TobySpeight are you asking the user who posted the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T08:33:52.473", "Id": "460376", "Score": "0", "body": "I don't doubt that it works, but that doesn't make it a *code review*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T22:46:00.443", "Id": "461045", "Score": "1", "body": "I posted a related answer on Stack Overflow: [Get midpoint of SDO.GEOMETRY polyline](https://stackoverflow.com/a/59708764/10936066)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T13:07:21.583", "Id": "234325", "ParentId": "233568", "Score": "2" } }, { "body": "<p>To build on @Ashok Vanam's &quot;buffer-and-centroid&quot; idea:</p>\n<p>It might be better to use <a href=\"https://desktop.arcgis.com/en/arcmap/latest/manage-data/using-sql-with-gdbs/st-pointonsurface.htm\" rel=\"nofollow noreferrer\">st_pointonsurface</a> (point will always be inside polygon) to get the centerpoint of the buffer polygon, instead of <a href=\"https://desktop.arcgis.com/en/arcmap/latest/manage-data/using-sql-with-gdbs/st-centroid.htm\" rel=\"nofollow noreferrer\">st_centroid</a> (can fall outside of polygon boundaries):</p>\n<pre><code>sde.st_x(sde.st_pointonsurface(sde.st_buffer(shape, 0.05))) as x,\nsde.st_y(sde.st_pointonsurface(sde.st_buffer(shape, 0.05))) as y\n</code></pre>\n<blockquote>\n<p>ST_PointOnSurface takes an ST_Polygon or ST_MultiPolygon and returns\nan ST_Point <strong>guaranteed to lie on its surface</strong>.</p>\n</blockquote>\n<blockquote>\n<p>ST_Centroid takes a polygon, multipolygon, or multilinestring and\nreturns the point that is in the <strong>center of the geometry's envelope</strong>.\nThat means that the centroid point is halfway between the geometry's\nminimum and maximum x and y extents.</p>\n</blockquote>\n<p>It's not the classiest solution in the world. But on the plus side, it is very simple/concise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T22:31:56.363", "Id": "502377", "Score": "0", "body": "Upon further testing, this doesn't seem to be a good approach. The midpoint doesn't get placed at the correct position along the line (especially curved lines). So, I think a true midpoint calculation would be better (example: a linear referencing solution)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T16:49:06.237", "Id": "254707", "ParentId": "233568", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T01:19:09.453", "Id": "233568", "Score": "2", "Tags": [ "sql", "oracle", "plsql" ], "Title": "Calculate the midpoint of a polyline" }
233568
<p>My application (legacy code) reads a CSV input file with an expected format with regards to Column names as follows:</p> <ul> <li>1st column - Should say "Marker"</li> <li>2nd column - Should say "Category"</li> <li>3rd column ... to ... N columns - These are the actual data columns. Should have number starting with 1 and increasing by 1 going right.</li> </ul> <p>In other words, 3rd column should have "1", 4th column header should have "2".</p> <p>Example CSV file with 10 data columns (total of 12 columns in file):</p> <pre class="lang-none prettyprint-override"><code>Marker,Category,1,2,3,4,5,6,7,8,9,10 TODD,Sea,0.001062344,0.001931534,0.002334951,0.002738369,0.003141786,0.003545203,0.004788256,0.005917489,0.007025671,0.008078547 JAMIE,Fork,0.00133847,0.002433581,0.002941854,0.003450128,0.003958402,0.004466676,0.006032825,0.007455569,0.00885179,0.010178331 LENNY,PITCH,0.001686365,0.003066119,0.003706504,0.004346889,0.004987274,0.005627659,0.007600883,0.009393428,0.011152557,0.012823893 </code></pre> <p>My code that does this validation (and it works) is as follows:</p> <pre class="lang-cs prettyprint-override"><code>fileStream = new FileStream(delimitedFileName, FileMode.Open, FileAccess.Read, FileShare.Read); csvStreamReader = new StreamReader(fileStream); string headerLine = csvStreamReader.ReadLine(); var headers = headerLine.Split(delimiter, '\\'); if (!string.Equals(headers[0], "Marker", StringComparison.InvariantCultureIgnoreCase) || (!string.Equals(headers[1], "Category", StringComparison.InvariantCultureIgnoreCase))) { throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv)."); } for (int i = 2; i &lt; headers.Length; i++) { if (!string.Equals(headers[i], (i-1).ToString(), StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv)."); } } </code></pre> <p>I want to avoid doing it like this, in 2 steps.</p> <p>Is there a way to do some sort of <code>delegate</code> or <code>Action</code> to do the 2nd section, i.e. validate that the data column names are correct, for a variable number of data columns?</p> <p>I want to avoid doing it in 2 separate sections as shown above, and have duplicate <code>throw new Exception</code> code for essentially the same exception.</p>
[]
[ { "body": "<p>Move the data column validation into a function</p>\n\n<pre><code>bool invalidDataColumns(string[] headers) {\n int[] numbers = headers.Skip(2).Select(s =&gt; int.TryParse(s, out var n) ? n : 0).ToArray();\n return !(numbers[0] == 1 &amp;&amp; numbers.Zip(numbers.Skip(1), (previous, current) =&gt; current - previous).All(diff =&gt; diff == 1));\n}\n</code></pre>\n\n<p>And call it within the <code>if</code> condition.</p>\n\n<pre><code>//...\n\nif (!string.Equals(headers[0], \"Marker\", StringComparison.InvariantCultureIgnoreCase)\n || (!string.Equals(headers[1], \"Category\", StringComparison.InvariantCultureIgnoreCase))\n || invalidDataColumns(headers)\n ) {\n throw new Exception(\"Invalid file format. Please use template (MarkerTemplate.csv).\");\n}\n\n//...\n</code></pre>\n\n<p>The condition could be reduced further by moving the entire thing into its own function as well</p>\n\n<pre><code>bool invalidHeaders(string[] headers) {\n return !string.Equals(headers[0], \"Marker\", StringComparison.InvariantCultureIgnoreCase)\n || (!string.Equals(headers[1], \"Category\", StringComparison.InvariantCultureIgnoreCase))\n || invalidDataColumns(headers);\n}\n</code></pre>\n\n<p>which now simplifies the code to</p>\n\n<pre><code>//...\n\nif (invalidHeaders(headers)) {\n throw new Exception(\"Invalid file format. Please use template (MarkerTemplate.csv).\");\n}\n\n//...\n</code></pre>\n\n<p>Unit test used to verify expected behavior</p>\n\n<pre><code>[TestClass]\npublic class InvalidDataColumnsTests {\n [TestMethod]\n [DataRow(\"Marker,Category,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15\", false)]\n [DataRow(\"Marker,Category,1,2,3,4,5,6,7,8,9,10\", false)]\n [DataRow(\"Marker,Category,1,2,3,4,5\", false)]\n [DataRow(\"Marker,Category,x,2,3,4,5,6,7,8,9,10\", true)]\n [DataRow(\"Category,1,2,3,4,5\", true)]\n public void Should_Validate_Columns(string headerLine, bool expected) {\n //string headerLine = \"Marker,Category,1,2,3,4,5,6,7,8,9,10\";\n string[] headers = headerLine.Split(new[] { \",\" }, StringSplitOptions.RemoveEmptyEntries);\n invalidHeaders(headers).Should().Be(expected);\n\n ////Example Use case\n //if (invalidHeaders(headers)) {\n // throw new Exception(\"Invalid file format. Please use template (MarkerTemplate.csv).\");\n //}\n }\n\n bool invalidHeaders(string[] headers) {\n return !string.Equals(headers[0], \"Marker\", StringComparison.InvariantCultureIgnoreCase)\n || (!string.Equals(headers[1], \"Category\", StringComparison.InvariantCultureIgnoreCase))\n || invalidDataColumns(headers);\n }\n\n bool invalidDataColumns(string[] headers) {\n int[] numbers = headers.Skip(2).Select(s =&gt; int.TryParse(s, out var n) ? n : 0).ToArray();\n return !(numbers[0] == 1 &amp;&amp; numbers.Zip(numbers.Skip(1), (previous, current) =&gt; current - previous).All(diff =&gt; diff == 1));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T21:21:52.893", "Id": "456774", "Score": "0", "body": "Thanks you, pretty much what I was hoping for as an answer to my question. The unit test are a bonus!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T03:40:59.403", "Id": "233575", "ParentId": "233572", "Score": "2" } }, { "body": "<p>You could do something like this:</p>\n\n<pre><code>fileStream = new FileStream(delimitedFileName, FileMode.Open, FileAccess.Read, FileShare.Read);\ncsvStreamReader = new StreamReader(fileStream);\nstring headerLine = csvStreamReader.ReadLine();\nvar headers = headerLine.Split(delimiter, '\\\\');\n\nfor (int i = 0; i &lt; headers.Length; i++)\n{\n if (i &gt;= 2 &amp;&amp; !string.Equals(headers[i], (i-1).ToString(), StringComparison.InvariantCultureIgnoreCase)\n || (i == 1 &amp;&amp; !string.Equals(headers[1], \"Category\", StringComparison.InvariantCultureIgnoreCase))\n || (i == 0 &amp;&amp; !string.Equals(headers[0], \"Marker\", StringComparison.InvariantCultureIgnoreCase)))\n {\n throw new Exception(\"Invalid file format. Please use template (MarkerTemplate.csv).\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T21:22:24.400", "Id": "456775", "Score": "0", "body": "This solution works too, and it's really simple. I could only choose 1 answer, so I chose the other and upvoted yours." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T07:15:31.413", "Id": "233579", "ParentId": "233572", "Score": "2" } } ]
{ "AcceptedAnswerId": "233575", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T03:03:54.177", "Id": "233572", "Score": "3", "Tags": [ "c#", "parsing", "csv", "delegates" ], "Title": "Validating CSV headers against an expected list" }
233572
<p>I have modelled a series of school classes as follows. The part I am not sure about is having a separate table for cancellations and substitute instructors.</p> <p>With this setup every time you looked up the class schedule for a given week you would have to search the <code>class_exceptions</code> table in order to see if the class was cancelled or the instructor was substituted with another one.</p> <p>Is there a better way of modelling this schema?</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE staff ( email TEXT, created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL default (now() at time zone 'utc'), updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL default (now() at time zone 'utc'), PRIMARY KEY (email) ); CREATE TABLE class_types ( id bigserial, name text NOT NULL, instructor_email TEXT NOT NULL, FOREIGN KEY (instructor_email) REFERENCES staff (email), created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL default (now() at time zone 'utc'), updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL default (now() at time zone 'utc'), PRIMARY KEY (id) ); CREATE TABLE classes ( class_type_id BIGINT NOT NULL, recurs_weekly BOOLEAN, is_public BOOLEAN, start_timestamp timestamp without time zone NOT NULL, end_timestamp timestamp without time zone NOT NULL, created_at timestamp without time zone NOT NULL default (now() at time zone 'utc'), updated_at timestamp without time zone NOT NULL default (now() at time zone 'utc'), FOREIGN KEY (class_type_id) REFERENCES class_types (id), PRIMARY KEY (class_type_id, start_timestamp) ); CREATE TABLE class_exceptions ( is_cancelled BOOLEAN, class_type_id BIGINT NOT NULL, start_timestamp timestamp without time zone NOT NULL, cover_instructor_email TEXT, FOREIGN KEY (class_type_id, start_timestamp) REFERENCES classes(class_type_id, start_timestamp), FOREIGN KEY (cover_instructor_email) REFERENCES staff (email), created_at timestamp without time zone NOT NULL default (now() at time zone 'utc'), updated_at timestamp without time zone NOT NULL default (now() at time zone 'utc') ); <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T12:09:14.417", "Id": "233586", "Score": "1", "Tags": [ "sql", "database", "postgresql" ], "Title": "Postgres Schema Design for School Classes with Cancellations and Substitute Instructors" }
233586
<h1>Context</h1> <p>Me and my team which I'm part of, for most of the time code in Excel VBA. Writing code in it self is pretty enjoyable, but combining our work in a shared repository is pretty painful. The ease our pain of combining/merging binary files, we have decided to help ourselves and create the Source Code Manager module.</p> <p><strong>Key features:</strong></p> <ul> <li>User, should be able to export code modules from the Workbook into any location</li> <li>User, should be able to import code modules from any location back to Workbook.</li> </ul> <p>Today, I would like from all of you to investigate the former.</p> <p><em>Note: if you want to export your code, might have to select <strong>Trust access to the VBA project object model</strong> in the Developer Macro Settings (File - Options - Trust Center - Trust Center Settings). Otherwise, code will not be exported!</em></p> <p><em>Note2: Everything, which is related to code management, I will try purposefully keep in one module to make it as shareable as possible. Sometime, I will intentionally break a OO principles like creating a new class and moving to it a set of closely related functionalities.</em></p> <p>If anything needs an explanation, let me know. This might be a good indication that a piece which I wrote is in a 'not easy to follow' manner, which I'm actively trying to avoid!</p> <hr> <h2>Dependencies</h2> <p>To start working with this code you need to add following references to your VB Project</p> <ul> <li>Microsoft Scripting Runtime</li> <li>Microsoft Visual Basic for Application Extensibility 5.3</li> <li>Microsoft ActiveX Data Object 6.1 Library</li> </ul> <p>This project requires also additional modules which can be found in <strong>External modules</strong></p> <ul> <li>ArrayH</li> <li>Exception</li> <li>Tools</li> </ul> <hr> <h2>Client code</h2> <p>In it's simplest form, you have to call one method <code>SourceControlH.ExportProjectComponents</code> which requires two parameters, source from which components will be exported (of type <code>Workbook</code>) and location, where components will be stored (of type <code>String</code>). </p> <pre class="lang-vb prettyprint-override"><code>Public Sub Start() SourceControlH.ExportProjectComponents ThisWorkbook, ThisWorkbook.Path &amp; "\src" End Sub </code></pre> <p>The following code presents how do I use <code>SourceControlH</code> module with the <code>Workbook_AfterSave</code> event which lets me to export the entire <code>VbProject</code> when it is saved. </p> <pre class="lang-vb prettyprint-override"><code>Private Sub Workbook_AfterSave(ByVal Success As Boolean) Dim ExportFolder As String ExportFolder = ThisWorkbook.Path &amp; "\src" If Fso.FolderExists(ExportFolder) = False Then Fso.CreateFolder ExportFolder End If SourceControlH.ExportProjectComponents ThisWorkbook, ExportFolder End Sub </code></pre> <hr> <h2>Under the hood</h2> <p>This section will present the actual code which does all the magic.</p> <p><strong>SourceControlH.bas</strong></p> <pre class="lang-vb prettyprint-override"><code>Option Explicit '@Folder("Helper") Private Const ModuleName As String = "SourceControlH" ' Path to the folder where components will be saved. Private pExportFolderPath As String ' Indicates if empty components should be exported or not. Private pExportEmptyComponents As Boolean Public Property Get ExportEmptyComponents() As Boolean ExportEmptyComponents = pExportEmptyComponents End Property Public Property Let ExportEmptyComponents(ByVal Value As Boolean) pExportEmptyComponents = Value End Property ' Exports and saves project's components, from Source workbook ' to the location which is specified in Path argument. ' If Source.VBProject is protected, throw an InvalidOperationException. ' If target path does not exists or if path does not points to a folder, ' throw an DirectoryNotFoundException. Public Sub ExportProjectComponents(ByVal Source As Workbook, ByVal Path As String) Const MethodName = "ExportProjectComponents" If Source.VBProject.Protection = vbext_pp_locked Then Exception.InvalidOperationException "Source.VBProject.Protection", _ "The VBA project, in this workbook is protected " &amp; _ "therefor, it is not possible to export the components. " &amp; _ "Unlock your VBA project and try again. " &amp; ModuleName &amp; "." &amp; MethodName End If If Tools.Fso.FolderExists(Path) = False Then Exception.DirectoryNotFoundException "Path", ModuleName &amp; "." &amp; MethodName End If pExportFolderPath = NormalizePath(Path) Dim Cmp As VBComponent For Each Cmp In GetExportableComponents(Source.VBProject.VBComponents) ExportComponent Cmp Next Cmp End Sub Private Function GetExportableComponents(ByVal Source As VBIDE.VBComponents) As Collection '&lt;VbComponents&gt; Dim Output As New Collection Dim Cmp As VBIDE.VBComponent For Each Cmp In Source If IsExportable(Cmp) Then Output.Add Cmp End If Next Cmp Set GetExportableComponents = Output Set Cmp = Nothing Set Output = Nothing End Function Private Function IsExportable(ByVal Component As VBIDE.VBComponent) As Boolean ' Check if component is on the list of exportable components. If ArrayH.Exists(Component.Type, ExportableComponentsTypes) = False Then IsExportable = False Exit Function End If If IsComponentEmpty(Component) = False Then IsExportable = True Exit Function End If If pExportEmptyComponents = True Then IsExportable = True Exit Function End If IsExportable = False End Function Private Property Get ExportableComponentsTypes() As Variant ExportableComponentsTypes = Array(vbext_ct_ClassModule, vbext_ct_MSForm, vbext_ct_StdModule, vbext_ct_Document) End Property ' Indicates if component is empty by checking number of code lines. ' Files, which contains just Option Explicit will be counted as empty. Private Function IsComponentEmpty(ByVal Source As VBIDE.VBComponent) As Boolean If Source.CodeModule.CountOfLines &lt; 2 Then IsComponentEmpty = True ElseIf Source.CodeModule.CountOfLines = 2 Then Dim Ln1 As String: Ln1 = Source.CodeModule.Lines(1, 1) Dim Ln2 As String: Ln2 = Source.CodeModule.Lines(2, 1) IsComponentEmpty = (VBA.LCase$(Ln1) = "option explicit" And Ln2 = vbNullString) Else IsComponentEmpty = False End If End Function Private Sub ExportComponent(ByVal Component As VBIDE.VBComponent) ' Full name means - name of the component with an extension. Dim FullName As String: FullName = GetComponentFullName(Component) Dim ExportPath As String: ExportPath = pExportFolderPath &amp; FullName Component.Export ExportPath End Sub ' To avoid problems with saving components, add backslash ' at the end of folder path. Private Function NormalizePath(ByVal Path As String) As String NormalizePath = Path &amp; IIf(Path Like "*\", vbNullString, "\") End Function Private Property Get ComponentTypeToExtension() As Dictionary Dim Output As New Dictionary With Output .Add vbext_ct_ClassModule, "cls" .Add vbext_ct_MSForm, "frm" .Add vbext_ct_StdModule, "bas" .Add vbext_ct_Document, "doccls" .Add vbext_ct_ActiveXDesigner, "ocx" End With Set ComponentTypeToExtension = Output End Property Private Function GetComponentFullName(ByVal Component As VBIDE.VBComponent) As String GetComponentFullName = Component.Name &amp; "." &amp; ComponentTypeToExtension.Item(Component.Type) End Function </code></pre> <hr> <h2>External modules</h2> <p>Modules, with code, which are used by <code>SourceControlH</code> module. These has to be include in your project as well.</p> <p><strong>Exception.cls</strong></p> <pre class="lang-vb prettyprint-override"><code>Option Explicit '@Exposed '@Folder("Lapis") '@PredeclaredId ' The exception that is thrown when a null reference (Nothing in Visual Basic) ' is passed to a method that does not accept it as a valid argument. Public Sub ArgumentNullException(ByVal ParamName As String, ByVal Message As String) Err.Raise 513, , "Value cannot be null." &amp; vbNewLine &amp; vbNewLine &amp; _ "Additional information: " &amp; Message &amp; vbNewLine &amp; vbNewLine &amp; _ "Parameter: " &amp; ParamName End Sub ' The exception that is thrown when one of the arguments provided to a method is not valid. Public Sub ArgumentException(ByVal ParamName As String, ByVal Message As String) Err.Raise 518, , "An exception of type ArgumentException was thrown." &amp; vbNewLine &amp; vbNewLine &amp; _ "Additional information: " &amp; Message &amp; vbNewLine &amp; vbNewLine &amp; _ "Parameter: " &amp; ParamName End Sub ' The exception that is thrown when a method call is invalid for the ' object's current state. Public Sub InvalidOperationException(ByVal ParamName As String, ByVal Message As String) Err.Raise 515, , "An exception of type InvalidOperationException was thrown." &amp; vbNewLine &amp; vbNewLine &amp; _ "Additional information: " &amp; Message &amp; vbNewLine &amp; vbNewLine &amp; _ "Parameter: " &amp; ParamName End Sub ' Occurs when an exception is not caught. Public Sub UnhandledException(ByVal Message As String) Err.Raise 517, , "An exception of type UnhandledException was thrown." &amp; vbNewLine &amp; vbNewLine &amp; _ "Additional information: " &amp; Message &amp; vbNewLine &amp; vbNewLine End Sub ' The exception that is thrown when a file or directory cannot be found. Public Sub DirectoryNotFoundException(ByVal ParamName As String, ByVal Message As String) Err.Raise 520, , "An exception of type DirectoryNotFoundException was thrown." &amp; vbNewLine &amp; vbNewLine &amp; _ "Additional information: " &amp; Message &amp; vbNewLine &amp; vbNewLine &amp; _ "Parameter: " &amp; ParamName End Sub </code></pre> <p><strong>Tools.bas</strong></p> <pre class="lang-vb prettyprint-override"><code>Option Explicit '@Folder("Lapis") Private Const ModuleName As String = "Tools" '@Ignore EncapsulatePublicField Public Fso As New FileSystemObject ' Returns number of text lines based on the specified Stream. ' Throws an ArgumentNullException when Stream is set to nothing. ' Throws an ArgumentException when Stream is closed. Public Function LinesCount(ByVal Stream As ADODB.Stream) As Long Const MethodName = "LinesCount" If Stream Is Nothing Then Exception.ArgumentNullException "Stream", ModuleName &amp; "." &amp; MethodName End If If Tools.IsStreamClosed(Stream) Then Exception.ArgumentException "Stream", "Stream is closed. " &amp; ModuleName &amp; "." &amp; MethodName End If Dim Ln As Long Stream.Position = 0 Do While Stream.EOS &lt;&gt; True Stream.SkipLine Ln = Ln + 1 Loop LinesCount = Ln End Function ' Determines if TextStream is closed. ' There is no property of TextStream object (like object.IsClosed) to know directly if Stream is closed ' or not. To know TextStream's state, method will attempt to read cursor position. If it fails ' (throws an error), that will mean Stream is not readable (closed). ' Throws an ArgumentNullException when Stream is set to nothing. Public Function IsStreamClosed(ByVal Stream As ADODB.Stream) As Boolean Const MethodName = "IsStreamClosed" If Stream Is Nothing Then Exception.ArgumentNullException "Stream", ModuleName &amp; "." &amp; MethodName End If On Error Resume Next Dim i As Long: i = Stream.Position If Err.Number = 91 Then IsStreamClosed = True On Error GoTo 0 ElseIf Err.Number = 0 Then IsStreamClosed = False Else ' Other, unexpected error occured. This error has to be moved upward. Exception.UnhandledException ModuleName &amp; "." &amp; MethodName End If End Function </code></pre> <p><strong>ArrayH.bas</strong></p> <pre class="lang-vb prettyprint-override"><code>Option Explicit '@Folder("Helper") ' Item parameter has to be a simple type. ' Arr has to have only one dimension. Public Function Exists(ByVal Item As Variant, ByRef Arr As Variant) As Boolean Exists = (UBound(Filter(Arr, Item)) &gt; -1) End Function </code></pre> <hr> <h2>Conclusion</h2> <p><strong>What do you thing about this code?</strong></p> <p>I'm looking forward to hear your thoughts about this piece. Within a week, I will also submit an import functionality for a review. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T16:08:45.210", "Id": "456689", "Score": "4", "body": "Did you know [Rubberduck](http://rubberduckvba.com) provides this bulk import/export functionality out of the box? (no need to trust programmatic access to the VBIDE API library!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:45:18.407", "Id": "457298", "Score": "1", "body": "One more thing - the VBIDE API will export module/member attributes for document modules, but since they can't be imported back in, they shouldn't be exported at all - FYI Rubberduck's bulk-export functionality doesn't have this problem, but [exporting individual modules does](https://github.com/rubberduck-vba/Rubberduck/issues/5319)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T10:27:22.707", "Id": "457359", "Score": "1", "body": "That's correct. When I import back modules into VB Project I use `VBProject.VBComponents.Import(FilePath)`. This this lets me avoid problems with attributes." } ]
[ { "body": "<p>The overall first impression is a very good one. Procedures are small, focused, generally well-named, everything is pretty much in its place - well done!</p>\n\n<p>What follows is a series of observations, and suggestions / how I'd go about \"fixing\" them.</p>\n\n<hr>\n\n<h3>Controlling object lifetime</h3>\n\n<p>In my view, it's important to be able to reliably <em>know</em> whether any object pointer is valid at any given point in the code that needs to dereference that pointer: for any object we create and consume, we want to be able to control when it's created, <em>and when it's destroyed</em>.</p>\n\n<p>So while this is procedural code and we're not going to fuss much about coupling, we can still <a href=\"http://rubberduckvba.com/Inspections/Details/SelfAssignedDeclaration\" rel=\"nofollow noreferrer\">flag the auto-instantiated object</a>:</p>\n\n<blockquote>\n<pre><code>'@Ignore EncapsulatePublicField\nPublic Fso As New FileSystemObject\n</code></pre>\n</blockquote>\n\n<p>While convenient, a global-scope auto-instantiated FSO object isn't something I'd recommend. Kudos for early-binding (side note: consider qualifying the library, e.g. <code>As Scripting.FileSystemObject</code>), but like anything accessing external resources (e.g. database connection, file handle, etc.), IMO its scope and lifetime should be as limited as possible. With a global-scope <code>As New</code> declaration, you give VBA the entire control over that object's actual lifetime.</p>\n\n<p>Alternatively, a <code>With</code> block could hold the object reference in a tight, well-defined local scope, and we wouldn't even need to declare a variable for it:</p>\n\n<pre><code>Private Sub Workbook_AfterSave(ByVal Success As Boolean)\n\n Dim ExportFolder As String\n ExportFolder = ThisWorkbook.Path &amp; \"\\src\"\n\n With New Scripting.FileSystemObject\n If Not .FolderExists(ExportFolder) Then\n .CreateFolder ExportFolder\n End If\n End With\n\n SourceControlH.ExportProjectComponents ThisWorkbook, ExportFolder\n\nEnd Sub\n</code></pre>\n\n<p>Note that the <code>{bool-expression} = False</code> condition is redundant - comparing a Boolean expression to a Boolean literal is always redundant: <code>Not {bool-expression}</code> is more idiomatic, more concise, and more expressive.</p>\n\n<hr>\n\n<h3>Portability</h3>\n\n<p>VBA code that doesn't need to be tied to a particular specific VBA host application's object model library, should avoid such dependencies.</p>\n\n<blockquote>\n<pre><code>Public Sub ExportProjectComponents(ByVal Source As Workbook, ByVal Path As String)\n</code></pre>\n</blockquote>\n\n<p>The <code>Source</code> parameter should be a <code>VBProject</code> object, not a <code>Workbook</code>; by taking in an <code>Excel.Workbook</code> dependency, the module becomes needlessly coupled with the Excel object model: if you needed to reuse this code in the future for, say, a Word VBA project, you'd need to make changes.</p>\n\n<hr>\n\n<h3>Consistency</h3>\n\n<p>Qualifying members is nice! <em>Consistently</em> qualifying members is <em>better</em> :)</p>\n\n<blockquote>\n<pre><code>If Tools.Fso.FolderExists(Path) = False Then\n</code></pre>\n</blockquote>\n\n<p>Why is <em>this</em> <code>Fso</code> qualified with the module name, but not the one in <code>ThisWorkbook</code>? Without Rubberduck to help, a reader would need to navigate to the definition to make sure it's referring to the same object.</p>\n\n<p>But, then again, I'd <code>New</code> up the FSO on the spot, and let VBA claim that pointer as soon as it's no longer needed:</p>\n\n<pre><code>With New Scripting.FileSystemObject\n If Not .FolderExists(Path) Then\n Exception.DirectoryNotFoundException \"Path\", ModuleName &amp; \".\" &amp; MethodName\n End If\nEnd With\n</code></pre>\n\n<hr>\n\n<h3>Other notes</h3>\n\n<p>I like your centralized approach to error-raising very much! I find the term \"exception\" a bit misleading though (if it's an exception, where's my stack trace?), and the procedure names read like properties. I'd propose something like this:</p>\n\n<pre><code> Errors.OnDirectoryNotFound \"Path\", ModuleName &amp; \".\" &amp; MethodName\n</code></pre>\n\n<p>It removes the doubled-up \"Exception\" wording from the instruction, and the <code>On</code> prefix is reminiscent of the .NET convention to name event-raising methods with that prefix.</p>\n\n<p>The <code>Exception</code> module being a class feels a bit wrong, even more so given the <code>@PredeclaredId</code> Rubberduck annotation, which presumably was synchronized and indicates the class has a <code>VB_PredeclaredId = True</code> attribute value: the class is never instantiated, only its default instance is ever invoked. The .NET equivalent is a <code>static class</code> with <code>static</code> methods, and the idiomatic VBA equivalent is a standard procedural module.</p>\n\n<p>Of course <code>Public Sub</code> procedures in a standard module would be visibly exposed as macros in Excel, and using a class module prevents that... but so does <code>Option Private Module</code>!</p>\n\n<p>Side note, there's a spelling error in this message:</p>\n\n<pre><code> Exception.InvalidOperationException \"Source.VBProject.Protection\", _\n \"The VBA project, in this workbook is protected \" &amp; _\n \"therefor, it is not possible to export the components. \" &amp; _\n \"Unlock your VBA project and try again. \" &amp; ModuleName &amp; \".\" &amp; MethodName\n</code></pre>\n\n<p>The comma after <code>The VBA project</code> is superfluous, there should be a dot after <code>is protected</code>, and so <code>therefor</code> should be <code>Therefore</code>, capital-T.</p>\n\n<p>That said, VBA project protection <a href=\"https://stackoverflow.com/a/27508116/1188513\">can easily be programmatically thwarted</a>, so with a little tweaking I think you could make this macro a bad boy that can just unlock a locked project to export it - but yeah, prompting the user with \"oops, it's locked, try again\" is probably the more politically-correct way to go about handling project protection.</p>\n\n<p>I'm not finding any uses for the <code>LinesCount</code> function, and it validating whether the stream is open strikes me as weird: raising this error would clearly only ever happen because of a bug, and should be a <code>Debug.Assert</code> check, if present at all.</p>\n\n<blockquote>\n<pre><code>If ArrayH.Exists(Component.Type, ExportableComponentsTypes) = False Then\n</code></pre>\n</blockquote>\n\n<p>That <code>H</code> again? I'm starting to think it just stands for <code>Helper</code>, which is a code smell in itself. Once more, this condition would read better as <code>If Not ArrayH.Exists(...) Then</code>, but I'd like to point out that these helper methods feel very much like what would be <em>extension methods</em> in .NET-land, and <code>ArrayExt.Exists</code> - or better, a fully spelled-out <code>ArrayExtensions.Exists</code> would raise fewer eyebrows. Kudos for avoiding the trap of just dumping all \"helper\" procedures and functions into some <code>Helpers</code> bag-of-whatever module.</p>\n\n<blockquote>\n<pre><code>' Path to the folder where components will be saved.\nPrivate pExportFolderPath As String\n\n' Indicates if empty components should be exported or not.\nPrivate pExportEmptyComponents As Boolean\n</code></pre>\n</blockquote>\n\n<p>This very much <a href=\"https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/\" rel=\"nofollow noreferrer\">Systems Hungarian</a> <code>p</code> prefix is distracting: there's no Hungarian Notation anywhere in the code and it reads like a charm - yes, <em>naming is hard</em>. Yes, naming is <em>even harder</em> in a case-insensitive language like VBA (or VB.NET).</p>\n\n<p>You could make a simple, private data structure to hold the configuration state, and with that you wouldn't need any prefixing scheme:</p>\n\n<pre><code>Private Type ConfigState\n ExportFolderPath As String\n WillExportEmptyComponents As Boolean\nEnd Type\n\nPrivate Configuration As ConfigState\n</code></pre>\n\n<p>Note that because <code>Export</code> is a <em>noun</em> in the <code>String</code> variable, but a <em>verb</em> in the <code>Boolean</code> one, a distinction is necessary IMO. Adding a <code>Will</code> prefix to the <code>Boolean</code> name clarifies everything I find. And now you can have properties named exactly after the <code>ConfigState</code> members, without any prefixing scheme - note the Rubberduck annotation opportunity for a <code>@Description</code> annotation, too:</p>\n\n<pre><code>'@Description(\"Indicates if empty components should be exported or not.\")\nPublic Property Get WillExportEmptyComponents() As Boolean\n WillExportEmptyComponents = Configuration.WillExportEmptyComponents\nEnd Property\n\nPublic Property Let WillExportEmptyComponents(ByVal Value As Boolean)\n Configuration.WillExportEmptyComponents = Value\nEnd Property\n</code></pre>\n\n<p>Speaking of Rubberduck opportunities, the <code>@Folder</code> organization can be enhanced - <a href=\"https://github.com/rubberduck-vba/Rubberduck/wiki/Using-@Folder-Annotations\" rel=\"nofollow noreferrer\">using @Folder annotations</a> on the project's wiki describes how the annotation can be used to create <em>sub</em>folders:</p>\n\n<blockquote>\n<pre><code>'@Folder(\"Parent.Child.SubChild\")\n</code></pre>\n</blockquote>\n\n<p>We have <code>SourceControlH</code> and <code>ArrayH</code> modules under <code>'@Folder(\"Helper\")</code>, some <code>Tools</code> module (FWIW \"Tools\" has the exact same smell as \"Helper\" does) under <code>'@Folder(\"Lapis\")</code>; the <code>Exception</code> module is under <code>'@Folder(\"Lapis\")</code> as well, which means the tree structure looks like this:</p>\n\n<pre><code>- [Helper]\n - ArrayH\n - SourceControlH\n- [Lapis]\n - Tools\n - Exception\n</code></pre>\n\n<p>Not sure what <code>Lapis</code> means, but the contents of the <code>Tools</code> module has this \"whatever couldn't neatly fit anywhere else\" bag-of-whatever feeling to it. What I wonder though, is why there's no clear dedicated <code>SourceControl</code> folder.</p>\n\n<p>I'm not going to claim a more OOP approach would even be warranted here (procedural is perfectly fine), but the basis for sticking to procedural feels wrong: it's <em>not</em> a self-contained module, it <em>has</em> dependencies and <em>must</em> be packaged as a \"bunch of modules that need to be imported together\" anyway.</p>\n\n<p>Having a <code>Helpers.SourceControl</code> folder would give you the dedicated space to cleanly split responsibilities while keeping the components neatly regrouped (in Rubberduck's Code Explorer toolwindow, that is).</p>\n\n<blockquote>\n<pre><code>' Full name means - name of the component with an extension.\nDim FullName As String: FullName = GetComponentFullName(Component)\n</code></pre>\n</blockquote>\n\n<p>I've seen Microsoft claim using the <code>:</code> instruction separator like this is \"good practice\" and \"helps transition to VB.NET syntax\". I'm not buying it at all. It looks awful and crowded. That comment is also very informative: it reads \"this GetComponentFullName procedure needs a better name\". In the Excel object model, <code>FullName</code> includes not only the file extension, but also the full path: your version of \"full\" isn't quite as \"full\" as it should be. In fact, <code>FullName</code> is actually nothing more than a <code>fileName</code>:</p>\n\n<pre><code>Dim fileName As String\nfileName = GetComponentFileName(Component)\n</code></pre>\n\n<p>Kudos here:</p>\n\n<blockquote>\n<pre><code> .Add vbext_ct_Document, \"doccls\"\n</code></pre>\n</blockquote>\n\n<p>This file extension is compatible with Rubberduck's own handling of document modules. By default, the VBIDE API exports document modules with a .cls file extension, which makes them import as class modules: to import them back into a <code>Worksheet</code> module, or into <code>ThisWorkbook</code>, you need some special handling, and that different file extension works great.</p>\n\n<p>Source-controlling VBA code is hard, because the code in a document module (e.g. <code>Worksheet</code>) can very well include references to objects that exist in the host document, like <code>ListObject</code> tables and whatnot - and these can't really be under source control (not without having the whole host document under source control too!). Worksheet layout can't be restored from source code, unless the worksheet layout is itself actually coded: this means a VBA project restored from source control can't really ever fully restore a project without the original host document anyway. So, kudos for tackling this thorny issue.</p>\n\n<p>Note that the last few pre-release builds of Rubberduck include bulk import/export functionality that does everything your code does, out of the box, without requiring programmatic access to the VBIDE Extensibility library, and without needing to share and manage versions for a <code>SourceControlH</code> module across devs and projects:</p>\n\n<p><img src=\"https://i.stack.imgur.com/WXQCE.png\" alt=\"Rubberduck Code Explorer&#39;s &quot;Sync Project&quot; features\"></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T19:59:43.183", "Id": "233605", "ParentId": "233587", "Score": "2" } }, { "body": "<p>This is my response to <a href=\"https://codereview.stackexchange.com/a/233605/193904\">the answer</a> given by @Mathieu Guindon.</p>\n\n<hr>\n\n<h2>Scope and life time of Scripting.FileSystemObject</h2>\n\n<blockquote>\n <p>(...) but like anything accessing external resources (e.g. database connection, file handle, etc.), IMO its scope and lifetime should be as limited as possible.</p>\n</blockquote>\n\n<p>Can you please also explain why is that? What pitfalls I might fall into while using external resources like <code>Scripting.FileSystemObject</code>? One of the reasons might be when I decide to start testing my methods which are using this global scope pointer. Are there any others?</p>\n\n<hr>\n\n<h2>Unused LinesCount</h2>\n\n<p>That's correct, <code>LinesCount</code> is not used in this context. I was relaying on Rubberduck to tell me if any method which are not used in this example... turns out it doesn't complain about this method. <code>ProcedureNotUsed</code> inspection should be triggered. I do not have this inspection turned off and filters are not enabled in <strong>Code Inspections</strong> window.</p>\n\n<p><a href=\"https://i.stack.imgur.com/xvkor.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xvkor.png\" alt=\"Code quality issues\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/1TVlb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1TVlb.png\" alt=\"Procedure is not referred to is enabled\"></a></p>\n\n<hr>\n\n<p><em>I think, this is the area where I'm expressing my subjective feelings about particular topics rather that hard data.</em></p>\n\n<hr>\n\n<h2>The letter H</h2>\n\n<blockquote>\n <p>That H again? I'm starting to think it just stands for Helper, which is a code smell in itself.</p>\n</blockquote>\n\n<p>That's correct, <code>H</code> stands from <code>Helper</code>. I'm using this abbreviation to try mitigate a situation where invocation of a method would be predominantly a module name. I think, what I'm aiming at, is to minimize the noise around my helper/extension calls. IMO, it does not take too long to figure out, what <code>H</code> stands for, even when you this piece of code for the first time.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub Start()\n\n Const TestValue As String = \"bbaabb\"\n\n ' Case 1: Methods, which are helping dealing with string data type\n ' are collected in the StringExtensions module.\n If StringExtensions.Contains(TestValue, \"a\") _\n And StringExtensions.StartsWith(TestValue, \"b\") _\n And StringExtensions.EndsWith(TestValue, \"b\") Then\n\n ' ...\n End if\n\n ' Case 2: The same methods are now in the StringExt module.\n If StringExt.Contains(TestValue, \"a\") _\n And StringExt.StartsWith(TestValue, \"b\") _\n And StringExt.EndsWith(TestValue, \"b\") Then\n\n ' ...\n End if\n\n ' Case 3: ... and now, they are in the StringH module.\n If StringH.Contains(TestValue, \"a\") _\n And StringH.StartsWith(TestValue, \"b\") _\n And StringH.EndsWith(TestValue, \"b\") Then\n\n ' ...\n End if\nEnd Sub\n</code></pre>\n\n<hr>\n\n<h2>Hungarian notation</h2>\n\n<p>Yes, I'm actively against using Hungarian notation... But, this one is exception. I used this <code>p</code> (private) prefix here because:</p>\n\n<ul>\n<li>The same reasons why you would use <code>_</code> in C#</li>\n<li>To avoid hassle of creating an additional private data structure</li>\n<li>To speed up a process of creating new variables\n\n<ul>\n<li>Right now, I have small code snippet in VS Code which lets me create module/class variable, property Get and Let in a few keyboard strokes. I don't see now the way how I could do it with custom data type.</li>\n</ul></li>\n</ul>\n\n<pre><code>{\n \"New property\":{\n \"prefix\": \"prop\",\n \"body\": [\n \"Private p${1:name} As ${2:type}\",\n \"\",\n \"Public Property Get ${1:name} () As ${2:type}\",\n \" ${1:name} = p${1:name}\",\n \"End Property\",\n \"\",\n \"\",\n \"Public Property Let ${1:name} (ByVal Value As ${2:type})\",\n \" p${1:name} = Value\",\n \"End Property\",\n ],\n \"description\": \"Creates a new property.\"\n }\n}\n</code></pre>\n\n<ul>\n<li>Rubberduck also does not provide a accessors builder for the members of data structures and maybe there are good reasons for it.</li>\n</ul>\n\n<hr>\n\n<h2>Case for the \":\"</h2>\n\n<p>The only place where I would use the <code>:</code> is where declaration of a variable AND value assignment is short. Lets say no longer than 65 characters (mine has 67, I know ).</p>\n\n<p>Things which I haven't touched on in this answer, I completely agree with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:46:35.787", "Id": "456862", "Score": "0", "body": "*Rubberduck also does not provide a accessors builder for the members of data structures and maybe there are good reasons for it.* - reason being, [it just hasn't been implemented *yet*](https://github.com/rubberduck-vba/Rubberduck/issues/4985).. but it's definitely planned - VSC is cheating! ;-) ...the global FSO is probably perfectly fine, pragmatically speaking. However it's unnecessary, and in any other language would be considered sloppy coding, and in .NET it would be leaking unmanaged resources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:50:04.260", "Id": "456863", "Score": "1", "body": "Now with that said, as a moderator I have to point out that this discussion forum-style of answer-to-an-answer isn't how Stack Exchange Q&A works; answers should respond to the OP, not to other answers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:40:35.537", "Id": "456876", "Score": "0", "body": "Got it. Thank you for your time!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T11:33:32.880", "Id": "233621", "ParentId": "233587", "Score": "2" } } ]
{ "AcceptedAnswerId": "233605", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T12:45:59.570", "Id": "233587", "Score": "6", "Tags": [ "vba" ], "Title": "Source Control and custom VBA Code Exporter" }
233587
<p>This code will generate a pseudorandom alphanumeric string of given length. I would welcome suggestions on how to make it more random. Beyond that, have I made any convention violations, Exception cases, and the like? Also, is there any way to make it faster?</p> <pre><code>public class Test { public static String getRandomAlphaNum(int length) { String charstring = "abcdefghijklmnopqrstuvwxyz0123456789"; String randalphanum = ""; double randroll; char randchar; for (double i = 0; i &lt; length; i++) { randroll = Math.random(); randchar = '@'; for (int j = 1; j &lt;= 36; j++) { if (randroll &lt;= (1.0 / 36.0 * j)) { randchar = charstring.charAt(j - 1); break; } } randalphanum += randchar; } return randalphanum; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T17:15:49.983", "Id": "456692", "Score": "1", "body": "Use StringBuilder to concatenate strings. += Creates new string every time and it is expensive operation to do in a loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T01:08:38.220", "Id": "456707", "Score": "1", "body": "Please do not use all caps... that would indicate that each letter stands for something (an acronym). That is not the case with Java" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T12:42:09.770", "Id": "456724", "Score": "1", "body": "using `double` as type of the counter variable is dangerous because primitive *floating point* numbers cannot be represented exactly (when they have fractions). Avoid primitive *floating point* types unless accuracy is less important the speed in your calculations." } ]
[ { "body": "<h3>Separate random generator</h3>\n\n<p>I would either extract the <em>random number generator</em> into an <strong>extra method</strong>, or simply use <code>new Random().nextInt(36)</code> from package <code>java.util</code> to generate a random integer between 0 and 35 (both inclusive).</p>\n\n<p>You could also make the method more generic by adding boundary parameters (min, max). So you can reuse within other limitations.</p>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/7961788/math-random-explanation\">Math.random() explanation</a></p>\n\n<h3>Variable names</h3>\n\n<p>Typical Java convention would name things using <a href=\"https://en.m.wikipedia.org/wiki/Camel_case\" rel=\"noreferrer\">Camel-case</a>. Also following Cleancode would put as much meaning into their names.</p>\n\n<p>So variables (except simple loop counters) can be renamed:</p>\n\n<ul>\n<li><code>characterOptions</code> or <code>possibleCharacters</code> or <code>alphaNumericChars</code></li>\n<li><code>randomCharacterChoice</code> or <code>randomCharIndex</code></li>\n<li><code>randomString</code> or <code>randomAlphaNumericSequence</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T14:35:32.713", "Id": "233595", "ParentId": "233588", "Score": "6" } }, { "body": "<pre><code>for\n (double i = 0; i &lt; length; i++)\n</code></pre>\n\n<p>And related loops should have the \"for\" on the same line (as this is a common coding convention.)</p>\n\n<pre><code>(randroll &lt;= (1.0 / 36.0 * j))\n</code></pre>\n\n<p>This doesn't have to be a double; instead, the random number can be generated as an integer (to select which element from the array.)</p>\n\n<pre><code>randchar = '@';\n</code></pre>\n\n<p>Unless the random string is not random, I would not initialize the variables with sample data. I'd just leave them blank and then adjust the loop to always run at least once (a do-while loop) so that it becomes initialized.</p>\n\n<pre><code>for\n (int j = 1; j &lt;= 36; j++)\n {\n if\n (randroll &lt;= (1.0 / 36.0 * j))\n {\n randchar = charstring.charAt(j - 1);\n break;\n }\n }\n</code></pre>\n\n<p>I would remove the inner if-statement and un-hardcode the values so it can work with strings with any size. Applying these suggestions, it can be simplified to:</p>\n\n<pre><code>import java.util.Random;\nclass Main {\n public static void main(String[] args) {\n int strLen = 100;\n String randString = \"\";\n Random r = new Random();\n String[] chars = \"abcdefghijklmnopqrstuvwxyz0123456789\".split(\"\");\n while (randString.length() &lt; strLen)\n randString += chars[randBetween(r, 0, chars.length - 1)];\n\n System.out.println(randString);\n }\n\n /*\n Generates a random number from min to max inclusive\n */\n public static int randBetween(Random r, int min, int max) {\n return r.nextInt((max - min) + 1) + min;\n }\n}\n</code></pre>\n\n<p>This approach is not optimal as the string is constantly being appended to, meaning that the string has to be re-copied every iteration.</p>\n\n<p>Java introduced Streams, which allows reading forever from certain generators. Knowing this, we can read a stream of random numbers up until the string length that the user wants, and then get the character at the random string length:</p>\n\n<pre><code>import java.util.Random;\nclass Main {\n public static void main(String[] args) {\n int strLen = 100;\n String chars = \"abcdefghijklmnopqrstuvwxyz0123456789\";\n\n StringBuilder randomOutput = new StringBuilder();\n new Random().ints(strLen, 0, chars.length())\n .forEach(c -&gt; randomOutput.append(chars.charAt(c)));\n\n System.out.println(randomOutput);\n }\n}\n</code></pre>\n\n<p><code>StringBuilder</code> is used to append the random character as it doesn't have to be re-copied for every loop iteration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T17:37:46.823", "Id": "233599", "ParentId": "233588", "Score": "7" } }, { "body": "<p>here is my recommendation for your code.</p>\n\n<p>1) Use int instead of a double in the loop; the integer takes less memory than the double.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n char randchar;\n for (int i = 0; i &lt; length; i++) {\n //[...]\n }\n</code></pre>\n\n<p>2) Use a StringBuilder to accumulate the result, instead of a string + concatenation (randalphanum).\nThe StringBuilder is always a better choice when building string in a loop.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n String randalphanum = \"\";\n</code></pre>\n\n<p>3) Create one constant to hold the possible values, as a char array instead of using \"charAt\" on a string; the computation will be the same, but in my opinion, this will make the code shorter and more readable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static final char[] CHARSTRING = {\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', \n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', \n 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //(3)\n\n //[...]\n public static String getRandomAlphaNum(final int length) {\n final StringBuilder randalphanum = new StringBuilder(); //(2)\n double randroll;\n char randchar;\n for (int i = 0; i &lt; length; i++) { //(1)\n randroll = Math.random();\n randchar = '@';\n for (int j = 1; j &lt;= 36; j++) {\n if (randroll &lt;= (1.0 / 36.0 * j)) {\n randchar = CHARSTRING[j - 1]; //(3)\n break;\n }\n }\n randalphanum.append(randchar);\n }\n return randalphanum.toString();\n }\n</code></pre>\n\n<p><strong>Potential refactor</strong></p>\n\n<p>A) Instead of using the for loop with index and not using it, I suggest that you use a \"while\" loop, and decrement the index in the loop.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>while (length &gt; 0) {\n length--;\n}\n</code></pre>\n\n<p>B) Instead of calculating the position, you can generate a random int, in the range [0, 26]; using the <code>java.util.Random#nextInt(int)</code> method.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>RANDOM.nextInt(CHARSTRING.length); // between 0 and 25\n</code></pre>\n\n<p>Complete example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static final char[] CHARSTRING = {\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',\n '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n public static final Random RANDOM = new Random();\n\n public static void main(final String[] args) {\n System.out.println(getRandomAlphaNum(15));\n }\n\n public static String getRandomAlphaNum(int length) {\n\n final StringBuilder accString = new StringBuilder();\n\n while (length &gt; 0) { //(A)\n final int selectedPosition = RANDOM.nextInt(CHARSTRING.length); //(B)\n accString.append(CHARSTRING[selectedPosition]);\n length--; //(A)\n }\n\n return accString.toString();\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:44:08.910", "Id": "456879", "Score": "1", "body": "Great first post, good job!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:27:25.047", "Id": "233691", "ParentId": "233588", "Score": "5" } }, { "body": "<p>Here is my solution to your problem, I used a StringBuilder so I didn't have to create a new string and then, used an array of chars to make it super easy to get the value I wanted. The code would probably be slightly more readable if you created the character array by hand but I was lazy today</p>\n\n<pre><code>public static String getRandomALphaNum(int length) {\n char[] charArr = new char[36];\n String alpha = \"abcdefghijklmnopqrstuvwxyz0123456789\";\n StringBuilder output = new StringBuilder();\n for (int i = 0; i &lt; alpha.length(); i++) {\n charArr[i] = alpha.charAt(i);\n }\n Random r = new Random();\n int randRoll;\n for (int i = 0; i &lt; length; i++) {\n randRoll = r.nextInt(charArr.length);\n output.append(charArr[randRoll]);\n }\n return output.toString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:47:30.723", "Id": "233711", "ParentId": "233588", "Score": "1" } } ]
{ "AcceptedAnswerId": "233599", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T13:00:35.587", "Id": "233588", "Score": "5", "Tags": [ "java", "performance", "beginner", "random" ], "Title": "Program in JAVA to generate random alphanumeric string" }
233588
<p>I'm also doing the fun little Advent of Code challenges in order to learn Rust. Until now things went quite smoothly, but while I'm proceeding with the tasks I'd love to learn where I can actually improve my Rust coding (and not only getting the correct results).</p> <p>I'm specifically looking for feedback where I'm violating <strong>Rust idioms</strong> or suggestions e.g. for simplifications as my knowledge of the Rust STD library features is still quite limited. On the other hand in context of those coding challenges I don't really care too much about stuff like input validation/stability/error handling or even performance (as you would in actual production code).</p> <p>As requested, a small summary of what the program does, as the linked description is admittedly a little exhaustive:</p> <p>The program basically simulates very basic machine code. A set of instructions represented as a list of integers values is given by a text file (comma delimited values).</p> <p>Instructions start with an "<strong>opcode</strong>", describing the operations. In our case this may either be an <strong>addition (1)</strong>, <strong>multiplication (2)</strong> or <strong>program end (99)</strong>. All other values are deemed invalid as an opcode. The 3 integers following the opcodes are the <strong>parameters</strong>, giving the <strong>addresses</strong> of the <strong>operands</strong> (offset 1 and 2), as well as the target address to store the <strong>result</strong> (offset 3).</p> <p>The result of the program is defined to be stored at address 0. In the 2nd part of the task one is given a program result (target_value 19690720) and is supposed to figure out which values need to reside at the memory addresses at 1 and 2 before starting the program (which are in this context called "noun" and "verb") in order to get this result.</p> <p>Here's my implementation part 2 of <a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">day 2</a>:</p> <pre class="lang-rust prettyprint-override"><code>use std::fs; fn add_values (value_a: i32, value_b: i32, target: &amp;mut i32) { *target = value_a + value_b } fn multiply_values (value_a: i32, value_b: i32, target: &amp;mut i32) { *target = value_a * value_b } fn run_program(memory: &amp;mut Vec&lt;i32&gt;) -&gt; i32 { let command_stride = 4; let mut current_pos = 0; while current_pos &lt; memory.len() { let current_instruction = memory[current_pos]; let address_a = memory[current_pos + 1] as usize; let address_b = memory[current_pos + 2] as usize; let address_target = memory[current_pos + 3] as usize; match current_instruction { 1 =&gt; add_values(memory[address_a], memory[address_b], &amp;mut memory[address_target]), 2 =&gt; multiply_values(memory[address_a], memory[address_b], &amp;mut memory[address_target]), 99 =&gt; break, _ =&gt; panic!("Invalid command value!") } current_pos += command_stride; } //return result of the program stored at address 0 memory[0] } fn main() { let contents = fs::read_to_string("input.txt") .expect("Something went wrong reading the file"); let split_codes = contents.split_terminator(','); let codes : Vec&lt;i32&gt; = split_codes.filter_map(|v| v.parse::&lt;i32&gt;().ok()).collect(); let target_value = 19690720; for noun in 0..100 { for verb in 0..100 { let mut current_memory = codes.clone(); //init noun and verb current_memory[1] = noun; current_memory[2] = verb; let current_result = run_program(&amp;mut current_memory); if current_result == target_value { println!("Target value reached, noun: {}, verb {}", noun, verb); println!("Result = {}", 100*noun + verb); break; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T20:40:04.080", "Id": "456699", "Score": "0", "body": "Thx for your comments - I've added a little summary of what the program does. Hope this helps understanding." } ]
[ { "body": "<p>Some things you could do :</p>\n\n<ul>\n<li>remove these \"add\" and \"multiply\" functions </li>\n<li>group operations when you read the file and when you split the input</li>\n<li>use iterators on your splitted input</li>\n<li>assign using the match statement</li>\n<li>declare all your variables at once (it's debatable, but if you find it easier to read then go for it ! )</li>\n<li>put info in your error message for the code (although it might not help much if you have a bug here, I admit)</li>\n</ul>\n\n<p>It could look something like :</p>\n\n<pre><code>use std::fs;\n\nfn run_program(memory: &amp;mut Vec&lt;i32&gt;) -&gt; i32 {\n for i in (0..memory.len()).step_by(4) {\n let (address_a, address_b, pos) = (memory[i + 1] as usize, memory[i + 2] as usize, memory[i + 3] as usize);\n memory[pos] = match memory[i] {\n 1 =&gt; {\n memory[address_a] + memory[address_b]\n }\n 2 =&gt; {\n memory[address_b] * memory[address_b]\n }\n 99 =&gt; {\n return memory[0];\n }\n c =&gt; panic!(\"Invalid command value : {}\", c)\n }\n }\n //return result of the program stored at address 0\n memory[0]\n}\n\nfn main() {\n let codes:Vec&lt;i32&gt; = fs::read_to_string(\"input.txt\")\n .expect(\"Something went wrong reading the file\")\n .split(',')\n .filter_map(|v| v.parse::&lt;i32&gt;().ok())\n .collect();\n\n let target_value = 19690720;\n\n for noun in 0..100 {\n for verb in 0..100 {\n let mut current_memory = codes.clone();\n //init noun and verb\n current_memory[1] = noun;\n current_memory[2] = verb;\n\n let current_result = run_program(&amp;mut current_memory);\n\n if current_result == target_value {\n println!(\"Target value reached, noun: {}, verb {}\", noun, verb);\n println!(\"Result = {}\", 100*noun + verb);\n break;\n }\n }\n }\n}\n</code></pre>\n\n<p>Note : the \".ok()\" filter might be dangerous in your stream ! I had a problem for day 5 where I had used wrong types for the instructions, and when the parsing failed they were discarded : I was missing instructions in my \"codes\" Vec !\nYou might want to fail if this happens instead, it's way easier to debug...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:19:09.667", "Id": "456847", "Score": "0", "body": "Nice review. Welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:03:55.947", "Id": "456911", "Score": "0", "body": "Yes, thanks a lot for taking the time doing the review! That's indeed very helpful to me :) \nAlso good point regarding the input parsing - didn't have any issues yet (starting day 4 next), but since the input files tend to be quite long this might indeed be tedious to debug otherwise!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:12:32.683", "Id": "233677", "ParentId": "233589", "Score": "2" } } ]
{ "AcceptedAnswerId": "233677", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T13:27:49.447", "Id": "233589", "Score": "2", "Tags": [ "beginner", "rust" ], "Title": "Advent of Code 2019 Day 2 in Rust" }
233589
<p>I've written a lock-free state machine in go and I would love to receive some feedback on it.</p> <p>Writing this library my main concerns are keeping it lock-free and very light-weight (no bells and whistles like hooks and such).</p> <p>Because this is lock-free I had to use <code>atomic.CompareAndSwap</code> which meant that the underlining state had to be a number, I choose unsigned because I saw no reason for a negative state, and I choose <code>uint32</code> because it was the smallest <code>CompareAndSwap</code> operand available.</p> <p>Later I added an option to label each state via an <code>option</code> function that can be passed to the initialization function.</p> <p>The initial state defaults to <code>0</code> (zero value of <code>uint32</code>), but it too can be changed via an <code>option</code> function.</p> <p><em><code>option</code> functions are not exported because they should only be used during initialization.</em></p> <p>There are 2 ways of changing the current state <code>Transition(...)</code> and <code>TransitionFrom(...)</code>. Transition uses the current state as the source node. And with <code>TransitionFrom(...)</code> you provide both source and destination nodes.<br> Providing the source node is important if you can get to the destination node from more than one source, and you want to make sure that the source was a specific node.</p> <pre class="lang-golang prettyprint-override"><code>package lfsm import ( "fmt" "strconv" "sync/atomic" ) type transition struct { src, dst uint32 stateNames StateNameMap } type transitionMap map[uint32]map[uint32]bool type State struct { current uint32 transitions transitionMap stateNames StateNameMap initial uint32 } // Current returns the current state. func (s *State) Current() uint32 { return atomic.LoadUint32(&amp;s.current) } // CurrentName returns the alias for the current state. // If no alias is defined, the state integer will be returned in its string version. func (s *State) CurrentName() string { return s.stateNames.find(atomic.LoadUint32(&amp;s.current)) } // TransitionFrom tries to change the state. // Returns an error if the transition failed. func (s *State) TransitionFrom(src, dst uint32) error { if _, ok := s.transitions[src][dst]; !ok { return &amp;InvalidTransitionError{src, dst, s.stateNames} } if !atomic.CompareAndSwapUint32(&amp;s.current, src, dst) { return &amp;TransitionError{src, dst, s.stateNames} } return nil } // Transition tries to change the state. // It uses the current state as the source state, if you want to specify the source state use TransitionFrom instead. // Returns an error if the transition failed. func (s *State) Transition(dst uint32) error { return s.TransitionFrom(atomic.LoadUint32(&amp;s.current), dst) } // NewState creates a new State Machine. func NewState(m Constraints, opts ...option) *State { s := State{ transitions: make(transitionMap, len(m)), stateNames: make(StateNameMap, len(m)), } for src, dsts := range m { s.transitions[src] = make(map[uint32]bool) for _, dst := range dsts { s.transitions[src][dst] = true } } for _,o := range opts { o.apply(&amp;s) } return &amp;s } // Constraints defines the possible transition for this state machine. // // The map keys describe the source states, and their values are the valid target destinations. type Constraints map[uint32][]uint32 // StateNameMap holds a mapping between the state (in its integer form) to its alias. type StateNameMap map[uint32]string func (m StateNameMap) find(v uint32) string { name, ok := m[v] if !ok { name = strconv.Itoa(int(v)) } return name } // Can be used to alter the state struct during initialization. type option func(s *State) // InitialState sets the initial state of the state machine func InitialState(v uint32) option { return func(s *State) { s.initial = v s.current = v } } // StateName sets an alias to a state integer. func StateName(v uint32, name string) option { return func(s *State) { s.stateNames[v] = name } } // StateNames is like StateName but sets aliases to multiple state integers. func StateNames(m StateNameMap) option { return func(s *State) { for v,name := range m { s.stateNames[v] = name } } } type TransitionError transition func (f TransitionError) Error() string { return fmt.Sprintf("transition failed (%s -&gt; %s)", f.stateNames.find(f.src), f.stateNames.find(f.dst)) } type InvalidTransitionError TransitionError func (f InvalidTransitionError) Error() string { return fmt.Sprintf("invalid transition (%s -&gt; %s)", f.stateNames.find(f.src), f.stateNames.find(f.dst)) } </code></pre> <ul> <li><a href="https://github.com/Eyal-Shalev/lfsm" rel="nofollow noreferrer">LFSM - GitHub</a></li> <li><a href="https://play.golang.org/p/nyjR6fvPa-0" rel="nofollow noreferrer">Basic Example - Go Playground</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T05:50:39.887", "Id": "456711", "Score": "1", "body": "What's the reason behind making transition functions, saving them in a map, and then retrieving and calling them? Is that so you're able to \"decorate\" them (to add functionality)? Otherwise you could just do the thing directly in `TransitionFrom`, and use a map of bools or something like that to know which transitions are allowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T08:51:18.603", "Id": "456715", "Score": "0", "body": "@kyrill the reason it's that when i started this code, I thought that calling transition will also return a map of available transitions. Later I decided to remove this functionality but kept the construction. I think I'll take your advice and switch to a map of booleans." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T13:57:10.867", "Id": "233591", "Score": "2", "Tags": [ "go", "state-machine", "lock-free" ], "Title": "Lock-free state machine" }
233591
<p>I'd like to know there's a better code than I did.</p> <pre><code>interface AnswerProps{ itemId: string; value: Array&lt;string&gt; } </code></pre> <p>This code works like checkbox. If <code>answers</code> has a value, I try to put the same value again. It would be deleted like toggle.</p> <pre><code>const App = () =&gt; { const [answers, SetAnswers] = React.useState&lt;AnswerProps[]&gt;([]); /* */ const handleAnswers = (value: string, answerIndex: number) =&gt; { let i = answers[answerIndex].value.indexOf(value); if(i === -1){ setAnswers(answers.map((el: AnswerProps, index: number)=&gt;{ if(index === answerIndex) return {...el, value: el.value.concat(value); else return { ...el } })); } } (...) } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T14:20:05.803", "Id": "233593", "Score": "2", "Tags": [ "javascript", "react.js", "immutability" ], "Title": "Set values with keeping immutability in React FC" }
233593
<p>I have two datasets. The first dataset “insideMarke1” contains the Best Bid / Best Ask (=BBA) data for a given day, starting at 8.00 am. Every time the BBA is updated, there is a new row with a new timestamp.</p> <p>The second dataset “orders1” contains order data. The order entry timestamps (‘Entry date and time’) in this dataset could be older than the oldest timestamp in the “insideMarke1” dataset. Each row contains one order. There are more orders in “orders1” than BBAs in “insideMarket1” (because not every order entry leads to a BBA update).</p> <p>What I want to achieve is to create a new dataset “orders1Complete”, with is a combination of both datasets: For every order in “orders1”, I want the Best Bid / Best Ask Price at the moment when the order was entered. If the order entry timestamp is older than the oldest timestamp in the “insideMarke1” dataset, I just want the oldest BBA for these orders.</p> <p>Therefore, I first added a new column to the “orders1” dataset, called ‘BBA_Timestamp’. And then I merged both datasets on this column. As a want the BBA timestamp at the moment before the order was entered, it is necessary to consider that the BBA timestamp has to be older than the order ‘Entry Date and Time’ timestamp.</p> <p>Below stands my code:</p> <pre><code>import pandas as pd insideMarke1 = pd.DataFrame({'Timestamp':['2019-12-01 08:00:00.123456', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:05.123456'], 'bestBidQnt':[100, 100, 50, 50, 100], 'bestBidPrice':[50.01, 50.01, 50.02, 50.02, 50.01], 'bestAskPrice':[51.00, 50.99, 50.99, 50.50, 50.50], 'bestAskQnt':[200, 100, 100, 200, 200]}) orders1 = pd.DataFrame({'Entry Date and Time':['2019-11-30 17:29:50.000000','2019-12-01 07:30:01.112233', '2019-12-01 08:00:00.123456', '2019-12-01 08:00:00.512341', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:02.987654', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:04.000000', '2019-12-01 08:00:05.123456'], 'Bid':['True', 'True', 'False', 'False', 'False', 'True', 'True', 'False', 'True', 'True'], 'Price':[49.00, 49.50, 51.00, 51.50, 50.99, 50.02, 48.00, 50.50, 49.00, 50.01 ], 'Qnt':[50, 100, 200, 150, 100, 50, 10, 200, 80, 100 ]}) insideMarke1[['Timestamp']] = insideMarke1[['Timestamp']].apply(pd.to_datetime, unit='ns') orders1[['Entry Date and Time']] = orders1[['Entry Date and Time']].apply(pd.to_datetime, unit='ns') orders1['BBA_Timestamp'] = 0 i = 0 minInsideMarke1 = min(insideMarke1['Timestamp']) for i in range(len(orders1['Entry Date and Time'])): if orders1['Entry Date and Time'][i] &lt;= minInsideMarke1: orders1['BBA_Timestamp'][i] = minInsideMarke1 else: insideMarke1_temp = insideMarke1.loc[(insideMarke1['Timestamp'] &lt; orders1['Entry Date and Time'][i])] orders1['BBA_Timestamp'][i] = min(insideMarke1_temp['Timestamp'], key=lambda x: abs(orders1['Entry Date and Time'][i]-x)) orders1 = orders1.reset_index(drop=True) insideMarke1 = insideMarke1.reset_index(drop=True) insideMarke1 = insideMarke1.drop_duplicates('Timestamp', keep='last') insideMarke1.rename(columns={'Timestamp': 'BBA_Timestamp'}, inplace=True) insideMarke1[['BBA_Timestamp']] = insideMarke1[['BBA_Timestamp']].apply(pd.to_datetime, unit='ns') insideMarke1 = insideMarke1.sort_values(by=['BBA_Timestamp']).reset_index(drop=True) orders1[['BBA_Timestamp']] = orders1[['BBA_Timestamp']].apply(pd.to_datetime, unit='ns') orders1 = orders1.sort_values(by=['BBA_Timestamp']).reset_index(drop=True) orders1Complete = pd.merge_asof(orders1, insideMarke1, on='BBA_Timestamp') </code></pre> <p>The code works fine, but it is soooo sloooow. My data sets contain several thousand lines and I have to do this for several of those data sets...</p> <p>I would be very very glad for any help, tips, advices,... </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T15:48:17.327", "Id": "456686", "Score": "2", "body": "Have you considered using a database such as MySQL? Databases are pretty good for this kind of thing. BTW Welcome to code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:16:56.267", "Id": "456886", "Score": "0", "body": "@pacmaninbw: It is more convenient for me to stick to pyhton, as I already have some code, which I use after having merged the to data sets. But thanks for the suggestion anyways!" } ]
[ { "body": "<p>This seems to work.</p>\n\n<p>Use <code>numpy.searchsorted()</code> to get the indices of the BBA for each order. Add the indices as a new column to the order1 dataframe. It's like <code>bisect</code> in the standard library.</p>\n\n<p>Then merge the two dataframes on the <code>insideMarke1</code> index and the <code>order1</code> 'BBA Index' column.</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\ninsideMarke1 = pd.DataFrame({'Timestamp':['2019-12-01 08:00:00.123456', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:05.123456'],\n 'bestBidQnt':[100, 100, 50, 50, 100],\n 'bestBidPrice':[50.01, 50.01, 50.02, 50.02, 50.01],\n 'bestAskPrice':[51.00, 50.99, 50.99, 50.50, 50.50],\n 'bestAskQnt':[200, 100, 100, 200, 200]})\n\norders1 = pd.DataFrame({'Entry Date and Time':['2019-11-30 17:29:50.000000','2019-12-01 07:30:01.112233', '2019-12-01 08:00:00.123456', '2019-12-01 08:00:00.512341', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:02.987654', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:04.000000', '2019-12-01 08:00:05.123456'],\n 'Bid':['True', 'True', 'False', 'False', 'False', 'True', 'True', 'False', 'True', 'True'],\n 'Price':[49.00, 49.50, 51.00, 51.50, 50.99, 50.02, 48.00, 50.50, 49.00, 50.01 ],\n 'Qnt':[50, 100, 200, 150, 100, 50, 10, 200, 80, 100 ]})\n\n\ninsideMarke1[['Timestamp']] = insideMarke1[['Timestamp']].apply(pd.to_datetime, unit='ns') \norders1[['Entry Date and Time']] = orders1[['Entry Date and Time']].apply(pd.to_datetime, unit='ns')\n\nBBA_Index = np.searchsorted(insideMarke1['Timestamp'], orders1['Entry Date and Time'], 'left')\norders1['BBA Index'] = (BBA_Index - 1).clip(0, len(insideMarke1))\n\norders1Complete = insideMarke1.merge(orders1, left_index=True, right_on='BBA Index')\n</code></pre>\n\n<p>result:</p>\n\n<pre><code> Timestamp bestBidQnt bestBidPrice bestAskPrice bestAskQnt Entry Date and Time Bid Price Qnt BBA Index\n0 2019-12-01 08:00:00.123456 100 50.01 51.00 200 2019-11-30 17:29:50.000000 True 49.00 50 0\n1 2019-12-01 08:00:00.123456 100 50.01 51.00 200 2019-12-01 07:30:01.112233 True 49.50 100 0\n2 2019-12-01 08:00:00.123456 100 50.01 51.00 200 2019-12-01 08:00:00.123456 False 51.00 200 0\n3 2019-12-01 08:00:00.123456 100 50.01 51.00 200 2019-12-01 08:00:00.512341 False 51.50 150 0\n4 2019-12-01 08:00:00.123456 100 50.01 51.00 200 2019-12-01 08:00:01.123456 False 50.99 100 0\n5 2019-12-01 08:00:01.123456 100 50.01 50.99 100 2019-12-01 08:00:02.123456 True 50.02 50 1\n6 2019-12-01 08:00:02.123456 50 50.02 50.99 100 2019-12-01 08:00:02.987654 True 48.00 10 2\n7 2019-12-01 08:00:02.123456 50 50.02 50.99 100 2019-12-01 08:00:03.123456 False 50.50 200 2\n8 2019-12-01 08:00:03.123456 50 50.02 50.50 200 2019-12-01 08:00:04.000000 True 49.00 80 3\n9 2019-12-01 08:00:03.123456 50 50.02 50.50 200 2019-12-01 08:00:05.123456 True 50.01 100 3\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:13:31.143", "Id": "456884", "Score": "0", "body": "Perfect, thank you so much! This works fine and it is a million times faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T06:39:00.410", "Id": "233617", "ParentId": "233594", "Score": "3" } } ]
{ "AcceptedAnswerId": "233617", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T14:25:48.383", "Id": "233594", "Score": "2", "Tags": [ "python", "performance", "beginner", "pandas" ], "Title": "Finding the market price for each order at the time it was placed" }
233594
<p>The goal of this code is to handle processes in multiple platforms, Linux initially. Windows later. The high level handler starts and stops a process or a list of processes. The platform specific drivers must conform to the following interface: <code>open()</code>, <code>close()</code> and <code>is_open()</code>. This system is used in test automation.</p> <p>My objective is creating a reusable, unit-testable and extensible component. It already works and passes a test suite with > 80% coverage.</p> <p>Please review code and provide feedback.</p> <p><strong>typical use case</strong></p> <pre class="lang-py prettyprint-override"><code> local_directory = dirname(abspath(__file__)) processes_list = ['./test_process_a.py', './test_process_b.py', './test_process_c.py'] processes = ProcessHandler(processes_list, local_directory) processes.start() # The processes do some work processes.stop() </code></pre> <p><strong>process_handler.py</strong></p> <pre class="lang-py prettyprint-override"><code>from process.linux_process_driver import * from logger.logger_init import * import argparse class ProcessHandler: """ Class that handles that start and stop of a set of processes. """ def __init__(self, process_path, cwd, process_driver = LinuxProcessDriver): self.__process_path = process_path self.__cwd = cwd self.__process_driver = process_driver self.__logger = logging.getLogger(self.__class__.__name__) def start(self): """ Start process(es) """ self.__logger.debug('--&gt; start()') process_list = self.set_process_state(True, self.__process_path) self.__logger.debug('&lt;-- start()') return process_list def stop(self): """ Stop process(es) in reverse order. """ self.__logger.debug('--&gt; stop()') reversed_process_list = list(reversed(self.__process_path)) process_list = self.set_process_state(False, reversed_process_list) self.__logger.debug('&lt;-- stop()') return process_list def set_process_state(self, state, process_list): """ Set process(es) state """ check_open_retries = 3 self.__logger.debug('--&gt; set_process_state()') try: for process_path in process_list: process = self.__process_driver(process_path, self.__cwd) process.close() while(process.is_open()): # Sometimes the process is closed and this check is done so fast, that the process still appears open. if(check_open_retries &gt; 0): self.__logger.error('Check open atempts left: ' + str(check_open_retries) + '. Process: ' + process_path + ' could not be closed.') check_open_retries -= 1 continue else: raise RuntimeError('Process: ' + process_path + ' could not be closed.') if(state == True): process.open() if(not process.is_open()): raise RuntimeError('Process: ' + process_path + ' could not be opened.') except Exception as exception: self.__logger.error(exception) raise self.__logger.debug('&lt;-- set_process_state()') return process_list </code></pre> <p><strong>linux_process_driver.py</strong></p> <pre class="lang-py prettyprint-override"><code>import os, signal from subprocess import Popen, PIPE from os.path import abspath, dirname, join from logger.logger_init import * class LinuxProcessDriver: local_directory = dirname(abspath(__file__)) def __init__(self, process_path, cwd = local_directory, os_handler = os): self.__logger = logging.getLogger(self.__class__.__name__) self.__logger.debug('process path input param: ' + process_path) last_index = process_path.rindex('/') self.__process_name = process_path[last_index + 1:] self.__process_path = process_path self.__cwd = cwd self.__os_handler = os_handler self.__logger.debug('process name: ' + self.__process_name) self.__logger.debug('process path: ' + self.__process_path) self.__logger.debug('process execution directory: ' + self.__cwd) def open(self): self.__logger.debug('--&gt; open()') self.__process = Popen(self.__process_path, cwd = self.__cwd).pid self.__logger.info('Opened process ' + self.__process_path + ' at directory ' + self.__cwd) self.__logger.debug('&lt;-- open()') def close(self): self.__logger.debug('--&gt; close()') if not self.is_open(): self.__logger.info('Process ' + self.__process_path + ' was not running.') return try: for pid in reversed(self.__pid_list): if(pid != ''): self.__os_handler.kill(int(pid), signal.SIGKILL) self.__logger.info('Closed process: ' + self.__process_path + ' with PID ' + pid) except Exception as exception: self.__logger.error(exception) raise self.__logger.debug('&lt;-- close()') def is_open(self): self.__logger.debug('--&gt; is_open()') self.__get_pid() result = False if(len(self.__pid_list) != 0 and self.__pid_list[0].isdigit()): result = True self.__logger.debug('Process ' + self.__process_path + ' running? ' + str(result)) self.__logger.debug('&lt;-- is_open()') return result def __get_pid(self): self.__logger.debug('--&gt; __get_pid()') linux_cmd_find_pid = 'ps -eo pid,cmd | grep "{0}" | grep -v grep'.format(self.__process_name) linux_cmd_find_pid = linux_cmd_find_pid + ' | awk \'{print $1}\'' process = Popen(linux_cmd_find_pid, shell = True, stdout = PIPE) pid, garbage = process.communicate() self.__logger.debug('linux output: ' + pid.strip()) self.__pid_list = pid.splitlines() self.__logger.debug('Length of pid list: ' + str(len(self.__pid_list))) for pid in self.__pid_list: self.__logger.debug('Found process: ' + self.__process_name + ' with PID ' + str(pid)) self.__logger.debug('&lt;-- __get_pid()') if __name__ == "__main__": """ Script to show usage and test basic functionality. """ # Create paths local_directory = dirname(abspath(__file__)) logs_directory_relative = "logs" logs_directory_absolute = os.path.join(local_directory, logs_directory_relative) log_filename = "log_linux_process_driver.py" # Create logger logger_init(logs_directory_absolute, log_filename) logger = logging.getLogger("LOGGER INIT TEST") process_path = raw_input('Enter process name: ') process = linux_process_driver(process_path) process.open() if(process.is_open()): logger.info('The process was opened.') else: logger.info('The process could not be opened.') process.close() if(not process.is_open()): logger.info('The process was closed.') else: logger.info('The process could not be closed.') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T15:01:04.687", "Id": "456683", "Score": "1", "body": "Are you trying to recreate something akin to [`psutil`](https://psutil.readthedocs.io/en/latest/)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T15:27:42.097", "Id": "456684", "Score": "0", "body": "@409_Conflict, I did not know of psutil's existence. psutil looks great and is very much what I intended to do. I will defininetly look into it. On the other hand, I'm new to python and I'm also very interested in having my code reviewed so I can get feedback of how I'm doing. Please review my code and let me know of any feedback you may think. For example, how readable (easy, medium, hard) is my code? Thank you !!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T20:42:46.303", "Id": "456769", "Score": "1", "body": "`if(state == True)` is a rather strange style. I personally don't like it even in languages where parentheses around a condition are mandatory (eg. C, Java, etc.). In those languages I prefer a space between the keyword and left parenthesis: `if (state == True)`. In Pyhon, however, parentheses are not necessary, so it would seem more appropriate to write `if state == True`. Here you can notice that you are comparing a boolean value with `True`, which is superfluous. You can just write `if state`. At this point it's apparent that `state` is not a great name. A better name would be `is_running`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T23:43:03.423", "Id": "456789", "Score": "0", "body": "Hi @kyrill, thank you for your observation. Very nice refactoring. I come from a C/C++ backgorund. Now, let me ask you if I may, how readable (easy, medium, hard) do you find my code? Thank you!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T00:07:32.203", "Id": "456792", "Score": "1", "body": "I'd say medium. I like to insert empty lines to separate logically coherent chunks of code. But what I find more problematic is things like `set_process_state` where you perform some operation for a number of elements but break out of the loop as soon as the first error occurs. Maybe it would be better to put the `try` block inside the `for` loop and not the other way around. Another problem here is that if you call `set_process_state` with `state == True`, it will kill the process, which may not be what the user wants or expects. It would be useful to mention this in the docstring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:26:58.730", "Id": "459457", "Score": "1", "body": "Similiar to @kyrill's advice above, you can also change `if(len(self.__pid_list) != 0)` to be simply `if self.__pid_list` since Python will check for nonzero size of array when evaluating an array as a boolean." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T14:51:08.110", "Id": "233596", "Score": "4", "Tags": [ "python", "design-patterns" ], "Title": "Multi-platfform process handling" }
233596
<p>I am attempting to construct a background service for an IIS-hosted ASP.NET Core project that basically queues tasks and runs them, and I decided to go with the <code>IHostedService</code> interface in Core 2.1 because of <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1&amp;tabs=visual-studio#queued-background-tasks" rel="nofollow noreferrer">this tutorial</a>. The tutorial does describe the case of running tasks <em>one-by-one</em> and in the order received, very well, and it does suffice for my purposes, but I was wondering whether it would be possible to run tasks <em>in parallel</em> via the same implementation of a <code>BackgroundService</code>, in such a way that one may control the maximum number of tasks running concurrently.</p> <p>I found <a href="https://stackoverflow.com/questions/51349826/parallel-queued-background-tasks-with-hosted-services-in-asp-net-core">this question</a> on SO, but was unable to get the proposed solution to work for the following task creation loop:</p> <pre><code>for (var i = 0; i &lt; 20; i++) { var j = i; await _queue.QueueBackgroundWorkItem(async token =&gt; { int s = j % 2 == 0 ? 5 : 1; Thread.Sleep(s * 1000); Debug.WriteLine(&quot;Processed &quot; + j + &quot; in &quot; + s + &quot; seconds&quot;); } } </code></pre> <p>where <code>_queue</code> is the <code>IBackgroundTaskQueue</code> defined in the tutorial. Indeed, for the <code>SemaphoreSlim</code> in the solution, but with the <code>initialCount</code> setting set to 4, I still receive the numbers 0, 1, 2, 3, etc. in order.</p> <p>I then tried to implement my own version of the <code>QueueBackgroundWorkItem</code> and <code>DequeueAsync</code> methods as an implemenation of <code>IBackgroundTaskQueue</code> called <code>NewMultiThreadBackgroundTaskQueue</code>:</p> <pre><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace QueueSystem.Queue { public class NewMultiThreadBackgroundTaskQueue : IBackgroundTaskQueue { private readonly ConcurrentQueue&lt;Func&lt;CancellationToken, Task&gt;&gt; _workItems = new ConcurrentQueue&lt;Func&lt;CancellationToken, Task&gt;&gt;(); private readonly List&lt;Task&gt; _runItems = new List&lt;Task&gt;(); private readonly SemaphoreSlim _signal; private const int InitialCount = 4; public NewMultiThreadBackgroundTaskQueue() { _signal = new SemaphoreSlim(InitialCount); } public Task QueueBackgroundWorkItem(Func&lt;CancellationToken, Task&gt; workItem) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } _workItems.Enqueue(async token =&gt; { await _signal.WaitAsync(token); try { await workItem(token); } finally { _signal.Release(); } }); return Task.CompletedTask; } public async Task&lt;Func&lt;CancellationToken, Task&gt;&gt; DequeueAsync(CancellationToken cancellationToken) { while (!_workItems.IsEmpty &amp;&amp; _runItems.Count &lt; InitialCount) { _workItems.TryDequeue(out var workItem); if (workItem != null) { _runItems.Add(Task.Run(async () =&gt; await workItem(cancellationToken), cancellationToken)); } } if (!_runItems.Any()) return async token =&gt; await Task.CompletedTask; var completed = await Task.WhenAny(_runItems); _runItems.Remove(completed); return async token =&gt; await completed; } } } </code></pre> <p>I use the <code>DequeueAsync</code> method in a <code>QueueHostedService</code> just as in the mentioned tutorial (i.e., nothing has changed):</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using QueueSystem.Queue; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace QueueSystem.Services { public class QueueHostedService : BackgroundService { private readonly ILogger _logger; public QueueHostedService(IBackgroundTaskQueue taskQueue, ILoggerFactory loggerFactory) { TaskQueue = taskQueue; _logger = loggerFactory.CreateLogger&lt;QueueHostedService&gt;(); } public IBackgroundTaskQueue TaskQueue { get; } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation(&quot;Queued Hosted Service is starting.&quot;); while (!cancellationToken.IsCancellationRequested) { var workItem = await TaskQueue.DequeueAsync(cancellationToken); try { await workItem(cancellationToken); } catch (Exception ex) { _logger.LogError(ex, &quot;Error occurred executing {WorkItem}.&quot;, nameof(workItem)); } } _logger.LogInformation(&quot;Queued Hosted Service is stopping.&quot;); } } } </code></pre> <p>The <code>DequeueAsync</code> method does work as intended in the above background service, but I fear that I'm not using the <code>CancellationToken</code> correctly and my usage of <code>Task.CompletedTask</code> is a bit on the frivolous side.</p> <p><strong>EDIT:</strong></p> <p>Following <a href="https://codereview.stackexchange.com/questions/233597/hosted-service-for-queuing-and-running-tasks-in-parallel-in-asp-net-core#comment503261_233597">this comment</a>, I have changed the content of the <code>QueueBackgroundWorkItem</code> and <code>DequeueAsync</code> methods:</p> <pre><code>public void QueueBackgroundWorkItem(Func&lt;CancellationToken, Task&gt; workItem) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } _workItems.Enqueue(workItem); } public async Task&lt;Func&lt;CancellationToken, Task&gt;&gt; DequeueAsync(CancellationToken cancellationToken) { if (_workItems.IsEmpty) return async token =&gt; await Task.CompletedTask; var removed = _runItems.RemoveAll(x =&gt; x.IsCompleted); while (!_workItems.IsEmpty &amp;&amp; _runItems.Count &lt; InitialCount) { _workItems.TryDequeue(out var workItem); if (workItem != null) { _runItems.Add(Task.Run(() =&gt; workItem(cancellationToken), cancellationToken)); } } return async token =&gt; await Task.WhenAny(_runItems); } </code></pre> <p>This still works (it dequeues and runs at most <code>InitialCount</code> tasks in parallel), but I'm still curious if there are any obvious improvements that I'm missing.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T16:47:28.323", "Id": "456690", "Score": "2", "body": "Hi! The code is working as intended and tasks are executed in parallel, I'm sorry if that wasn't clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T18:02:50.257", "Id": "456696", "Score": "0", "body": "For anyone in the Close Queue, the author believes the code is working as intended, do not close for that reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-23T12:25:16.177", "Id": "503261", "Score": "1", "body": "`_workItems.Enqueue(async token =>\n {\n await _signal.WaitAsync(token);\n try\n {\n await workItem(token);\n }\n finally\n {\n _signal.Release();\n }\n });`why? why this is this being done... not even sure what its about. surely it should take a task and thats it? the rest is handled by the dequeue, could you explain this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-24T14:44:44.327", "Id": "503395", "Score": "0", "body": "Thanks for your comment! It might work without the SemaphoreSlim, but I don't know for sure. I guess it probably will due to the SemaphoreSlim-free handling of the dequeueing of tasks (which means that I see what you see). I'll get back to you. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T07:45:16.003", "Id": "504349", "Score": "0", "body": "You are correct - SemaphoreSlim is irrelevant. Also, I figured it would be nicer to check if the ConcurrentQueue is empty in the beginning of the `DequeueAsync` method and return a completed task if it is - then remove all completed tasks at the start of the while loop and return the `Task.WhenAny(_runItems)` after the while loop. That looks much better. Thanks for the feedback!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T15:35:56.640", "Id": "233597", "Score": "3", "Tags": [ "c#", "asp.net", "concurrency", "async-await", "asp.net-core" ], "Title": "Hosted service for queuing and running tasks in parallel in ASP.NET Core" }
233597
<p>I dont now how to optimize me code. The game i created lags 15 fps, how i can it be reduced and optimize.This my code, I try to do optimize, but i cant. Please help:</p> <pre class="lang-py prettyprint-override"><code> import pygame from random import randint import time import os pygame.init() name = os.getlogin() path = r'C:\\Users\\' + name + r'\\Desktop\\WHITE\\' imhero = path + r'hero.png' imfloor = path + r'floor.png' imeasybutton = path + r'easy_button.png' imnormbutton = path + r'normal_button.png' imhardbutton = path + r'hard_button.png' imheart = path + r'heart.png' imstart = path + r'start_button.png' imbackground = path + r'background.png' imbonus_1 = path + r'heart_bonus.png' imbackground_start = path + r'background_start.png' picture = [path + "object_1.png", path + "object_2.png",path + "object_3.png",path + "object_4.png"] point = 0 life_count = 0 y_start = 375 SCREEN = (600, 500) x = randint(1,500) BLACK = (0,0,0) WHITE = (255,255,255) BLUE = (0,255, 220) Salmon = (255, 160, 122) speed = 0 FPS = 30 motion = "STOP" clock = pygame.time.Clock() sc = pygame.display.set_mode((SCREEN)) pygame.display.set_caption("Game") y = y_start y_object_1 = 0 y_heart_1 = y_object_1 start = True choise = False easy = False normal = False hard = False button = pygame.Surface((300,100)) sc.blit(button,(50,50)) difficlt = "" background = pygame.sprite.Group() hearts = pygame.sprite.Group() object_group = pygame.sprite.Group() hero_group = pygame.sprite.Group() game_over_text = pygame.font.SysFont('arial', 36).render("GAME OVER", 1, (255, 0, 0)) game_over_rect = game_over_text.get_rect(center=(SCREEN[0]//2, SCREEN[1]//2)) class Background(pygame.sprite.Sprite): def __init__(self,filename,group): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename) self.rect= self.image.get_rect(center = (SCREEN[0]//2,SCREEN[0]//2)) self.add(group) class Object(pygame.sprite.Sprite): class box(pygame.sprite.Sprite): def __init__(self,filename,group,y_object_1): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.image.set_colorkey((255,255,255)) self.rect = self.image.get_rect(center = (randint(1,SCREEN[0]), y_object_1)) self.add(group) def update(self, *args): if y_object_1 &lt; SCREEN[1]: self.rect[1]+=speed time.sleep(0.001) class floor (pygame.sprite.Sprite): def __init__(self,filename,group,x_floor,y_floor): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.rect = self.image.get_rect(center = (x_floor, y_floor)) self.add(group) class Hero(pygame.sprite.Sprite): def __init__(self,filename,group,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.rect = self.image.get_rect(center =(x,y)) self.add(group) def update_hero(self, move): if move == "LEFT": self.rect[0] -= 30 elif move == "RIGHT": self.rect[0] += 30 if self.rect[0] &gt; SCREEN[0]: self.rect[0]= 10 if self.rect[0] &lt;10: self.rect[0]= 590 class Heart(pygame.sprite.Sprite): def __init__(self,filename,group,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.rect = self.image.get_rect(center =(x,y)) self.add(group) class Buttons(pygame.sprite.Sprite): def __init__(self,filename,group,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.rect = self.image.get_rect(center=(x,y)) self.add(group) def pressed(self, mouse): if mouse[0] &gt; self.rect.topleft[0]: if mouse[1] &gt; self.rect.topleft[1]: if mouse[0] &lt; self.rect.bottomright[0]: if mouse[1] &lt; self.rect.bottomright[1]: return True else: return False else: return False else: return False else: return False class bonus(pygame.sprite.Sprite): class Heart_Bonus(pygame.sprite.Sprite): def __init__(self,filename,group,y_heart_1): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(filename).convert_alpha() self.image.set_colorkey((255,255,255)) self.rect = self.image.get_rect(center = (randint(1,SCREEN[0]), y_heart_1)) self.add(group) def update(self, *args): if y_heart_1 &lt; SCREEN[1]: self.rect[1]+=speed time.sleep(0.001) def update(): object_group.update() bonus_group.update() background.draw(sc) hero_group.draw(sc) object_group.draw(sc) hearts.draw(sc) bonus_group.draw(sc) buttons = pygame.sprite.Group() start = pygame.sprite.Group() bonus_group = pygame.sprite.Group() fon_start = Background(imbackground_start,start) start_button = Buttons(imstart,start,SCREEN[0]//2, SCREEN[1]//2) while start: start.draw(sc) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: start = False if event.type == pygame.MOUSEBUTTONDOWN: if start_button.pressed(pygame.mouse.get_pos()) == True : start_button.kill() choise = True start = False while choise: easy_button = Buttons(imeasybutton,buttons,300,150) normal_button = Buttons(imnormbutton,buttons,300,300) hard_button = Buttons(imhardbutton,buttons,300,450) sc.fill(Salmon) buttons.draw(sc) choise_text = pygame.font.SysFont('arial', 30).render("ВЫБЕРИТЕ УРОВЕНЬ СЛОЖНОСТИ" , 1, (BLACK)) сhoise_rect = choise_text.get_rect(center=(SCREEN[0]//2,50)) sc.blit(choise_text,сhoise_rect) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: choise = False if event.type == pygame.MOUSEBUTTONDOWN: if easy_button.pressed(pygame.mouse.get_pos()) == True : difficlt = "easy" life_count = 3 choise = False break if normal_button.pressed(pygame.mouse.get_pos()) == True : difficlt = "normal" life_count = 2 choise = False break if hard_button.pressed(pygame.mouse.get_pos()) == True : difficlt = "hard" life_count = 1 choise = False break if difficlt == "easy": speed = 15 easy_button.kill() normal_button.kill() hard_button.kill() easy = True normal = False hard = False object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) heart1 = Heart(imheart,hearts,50,450) heart2 = Heart(imheart,hearts,100,450) heart3 = Heart(imheart,hearts,150,450) if difficlt == "normal": speed = 20 easy_button.kill() normal_button.kill() hard_button.kill() easy = False normal = True hard = False object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) object6 = Object.box(picture[randint(0,3)], object_group, y_object_1) heart1 = Heart(imheart,hearts,50,450) heart2 = Heart(imheart,hearts,100,450) if difficlt == "hard": speed = 25 easy_button.kill() normal_button.kill() hard_button.kill() easy = False normal = False hard = True object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) object6 = Object.box(picture[randint(0,3)], object_group, y_object_1) object7 = Object.box(picture[randint(0,3)], object_group, y_object_1) heart1 = Heart(imheart,hearts,50,450) floor = Object.floor(imfloor,background,300,450) hero = Hero(imhero,hero_group,x,y) fon = Background(imbackground,background) while easy: for event in pygame.event.get(): if event.type == pygame.QUIT: easy = False keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT] and hero.rect[0] &lt; SCREEN[0]: hero.update_hero('RIGHT') if keys[pygame.K_LEFT] and hero.rect[0] &gt; 0: hero.update_hero('LEFT') update() pygame.display.update() if pygame.sprite.spritecollideany(floor,object_group): object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) point+=1 if pygame.sprite.spritecollideany(hero,object_group): life_count-=1 if life_count == 2 : heart3.kill() object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) if life_count == 1 : heart2.kill() object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) if life_count == 0: sc.fill(BLUE) heart1.kill() game_over_text = pygame.font.SysFont('arial', 36).render("GAME OVER" , 1, (255, 0, 0)) game_over_text2 = pygame.font.SysFont('arial', 36).render( "SCORE: " + str(point) , 1, (255, 0, 0)) game_over_rect = game_over_text.get_rect(center=(SCREEN[0]//2, SCREEN[1]//2)) game_over_rect2 = game_over_text.get_rect(center=(SCREEN[0]//2, (SCREEN[1]//2)+50)) sc.blit(game_over_text,game_over_rect) sc.blit(game_over_text2,game_over_rect2) pygame.display.update() time.sleep(5) break point_text = pygame.font.SysFont('arial', 36).render("SCORE" + str(point), 1, (255, 0, 0)) point_rect = point_text.get_rect(center=(450,450)) sc.blit(point_text, point_rect) pygame.display.update() pygame.time.Clock().tick(FPS) while normal: for event in pygame.event.get(): if event.type == pygame.QUIT: normal = False keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT] and hero.rect[0] &lt; SCREEN[0]: hero.update_hero('RIGHT') if keys[pygame.K_LEFT] and hero.rect[0] &gt; 0: hero.update_hero('LEFT') update() pygame.display.update() p = randint(1,10) if pygame.sprite.spritecollideany(floor,object_group): object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object6.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) if p%2 == 0: object6 = bonus.Heart_Bonus(imbonus_1, bonus_group,y_heart_1) point+=1 if pygame.sprite.spritecollideany(hero,bonus_group): if life_count ==1: life_count+=1 heart2 = Heart(imheart,hearts,100,450) object6.kill() if pygame.sprite.spritecollideany(hero,object_group): life_count-=1 if life_count == 1 : heart2.kill() object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object6.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) object6 = Object.box(picture[randint(0,3)], object_group, y_object_1) if life_count == 0: sc.fill(BLUE) heart1.kill() game_over_text = pygame.font.SysFont('arial', 36).render("GAME OVER" , 1, (255, 0, 0)) game_over_text2 = pygame.font.SysFont('arial', 36).render( "SCORE: " + str(point) , 1, (255, 0, 0)) game_over_rect = game_over_text.get_rect(center=(SCREEN[0]//2, SCREEN[1]//2)) game_over_rect2 = game_over_text.get_rect(center=(SCREEN[0]//2, (SCREEN[1]//2)+50)) sc.blit(game_over_text,game_over_rect) sc.blit(game_over_text2,game_over_rect2) pygame.display.update() time.sleep(5) break point_text = pygame.font.SysFont('arial', 36).render("SCORE" + str(point), 1, (255, 0, 0)) point_rect = point_text.get_rect(center=(450,450)) sc.blit(point_text, point_rect) pygame.display.update() pygame.time.Clock().tick(FPS) time.sleep(1) while hard: for event in pygame.event.get(): if event.type == pygame.QUIT: hard = False keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT] and hero.rect[0] &lt; SCREEN[0]: hero.update_hero('RIGHT') if keys[pygame.K_LEFT] and hero.rect[0] &gt; 0: hero.update_hero('LEFT') update() pygame.display.update() if pygame.sprite.spritecollideany(floor,object_group): object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object6.kill() object7.kill() object1 = Object.box(picture[randint(0,3)], object_group, y_object_1) object2 = Object.box(picture[randint(0,3)], object_group, y_object_1) object3 = Object.box(picture[randint(0,3)], object_group, y_object_1) object4 = Object.box(picture[randint(0,3)], object_group, y_object_1) object5 = Object.box(picture[randint(0,3)], object_group, y_object_1) object6 = Object.box(picture[randint(0,3)], object_group, y_object_1) object7 = Object.box(picture[randint(0,3)], object_group, y_object_1) point+=1 if pygame.sprite.spritecollideany(hero,object_group): life_count-=1 if life_count == 0: object1.kill() object2.kill() object3.kill() object4.kill() object5.kill() object6.kill() object7.kill() sc.fill(BLUE) heart1.kill() game_over_text = pygame.font.SysFont('arial', 36).render("GAME OVER" , 1, (255, 0, 0)) game_over_text2 = pygame.font.SysFont('arial', 36).render( "SCORE: " + str(point) , 1, (255, 0, 0)) game_over_rect = game_over_text.get_rect(center=(SCREEN[0]//2, SCREEN[1]//2)) game_over_rect2 = game_over_text.get_rect(center=(SCREEN[0]//2, (SCREEN[1]//2)+50)) sc.blit(game_over_text,game_over_rect) sc.blit(game_over_text2,game_over_rect2) pygame.display.update() time.sleep(5) break point_text = pygame.font.SysFont('arial', 36).render("SCORE" + str(point), 1, (255, 0, 0)) point_rect = point_text.get_rect(center=(450,450)) sc.blit(point_text, point_rect) pygame.display.update() pygame.time.Clock().tick(FPS) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:54:00.273", "Id": "456750", "Score": "3", "body": "The question needs a description of what the code does. It is very difficult to write a good code review when we don't know what the code is supposed to do, and don't know what the expected output is." } ]
[ { "body": "<p>There's too much code here to be able to quickly review it to find your performance bottlenecks. I'd recommend running it under a performance profiler to see which specific functions your program spends the most time executing so you can focus your optimization on those functions:</p>\n\n<p><a href=\"https://docs.python.org/3/library/profile.html\" rel=\"noreferrer\">https://docs.python.org/3/library/profile.html</a></p>\n\n<p>This did jump out at me, though:</p>\n\n<pre><code>time.sleep(0.001)\n</code></pre>\n\n<p>because it's executed in the <code>update</code> function of each individual object, and since this program is single-threaded, everything else is going to be paused while that sleep is happening, so the more objects you have in the game, the slower each update cycle will be. If you have a hundred objects, it'll take a tenth of a second to update them all, and if your screen refresh is blocked on that, that means you're getting at best 10fps. </p>\n\n<p>What you probably want to do is have a single timer that triggers an update on all the objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T20:38:40.980", "Id": "233606", "ParentId": "233602", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T19:39:42.757", "Id": "233602", "Score": "-1", "Tags": [ "python" ], "Title": "NOt optimized code,how can i fix it?" }
233602
<h2>Motivation</h2> <p>Python's Abstract Base Classes in the <code>collections.abc</code> module work as mixins and also define abstract interfaces that invoke common functionality in Python's objects.</p> <p>While reading the actual source is quite enlightening, viewing the hierarchy as a graph would be a useful thing for Python programmers.</p> <p>Unified Modeling Language (UML) is a way of visualizing system design.</p> <h2>Libraries</h2> <p>Graphviz is a natural choice for this kind of output. One can find many examples of people generating these kinds of outputs using Graphviz. </p> <p>But, to ensure correctness and completeness, and easy tweakability of the logic used to create them, we need a way to feed the Python classes into Graphviz.</p> <p>A natural choice is python-graphviz, but we'll need to pipeline the Python into the graphviz interface.</p> <h2>Our grammar of graphics</h2> <p>UML communicates features that Python does not have. Using a smaller subset of the relevant features will give us a graph that is cleaner and easier for those less familiar with UML to understand.</p> <p>Our subset will be class diagrams where:</p> <ul> <li>Abstract classes' names, data members, and methods are italicized, concrete implementations are not.</li> <li>Edges (lines) are dashed when the subclass is abstract, and not dashed when the relationship is a specialization.</li> <li>We only show <strong>is-a</strong> relationships (class hierarchy) not <strong>has-a</strong> relationships (composition), because it doesn't really apply for our use-case and because the <code>abc</code> module doesn't have such relevant annotations (if we did have annotations showing this relationship we could support it, but I do not here).</li> </ul> <h2>Avoiding information overload in the output</h2> <p>We exclude most of the default methods and members in <code>object</code>. We also specifically hide other members that relate to class relationships and implementations that don't directly affect users.</p> <p>We do not show return types (e.g. <code>: type</code>) because we lack the annotations in the module.</p> <p>We do not show <code>+</code> (public), <code>-</code> (private), and <code>#</code> (protected) symbols, because in Python everything is accessible, and it is merely convention that indicates users should avoid interfaces prefixed with underscores (<code>_</code>).</p> <h2>The code</h2> <p>I got this environment with Anaconda, which used a fresh install and required </p> <pre><code>$ conda install graphviz python-graphviz </code></pre> <p>And I did my construction in a notebook using Jupyter Lab.</p> <p>First we import the python-graphviz Digraph object, some functions from the standard library, the <code>collections.abc</code> module for the abstract base classes that we want to study, and some types we'll want to use to discriminate between objects.</p> <p>We also put types or methods and members that we want to exclude in a tuple, and put the names of methods we also intentionally hide in a set.</p> <pre class="lang-py prettyprint-override"><code>from graphviz import Digraph from inspect import getclasstree, isabstract, classify_class_attrs, signature import collections.abc from html import escape from abc import ABCMeta from types import WrapperDescriptorType, MethodDescriptorType, BuiltinFunctionType # usually want to hide default (usually unimplemented) implementations: # ClassMethodDescriptorType includes dict.fromkeys - interesting/rare- enough? EXCLUDED_TYPES = ( WrapperDescriptorType, # e.g. __repr__ and __lt__ MethodDescriptorType, # e.g. __dir__, __format__, __reduce__, __reduce_ex__ BuiltinFunctionType, # e.g. __new__ ) HIDE_METHODS = { '__init_subclass__', # error warning, can't get signature '_abc_impl', '__subclasshook__', # why see this? '__abstractmethods__', } </code></pre> <p>Now we must create the table (labels) for the graphviz nodes. Graphviz uses a syntax that looks like html (but isn't). </p> <p>Here we create a function that takes the class and returns the table from the information that we can derive from the class.</p> <pre class="lang-py prettyprint-override"><code>def node_label(cls, show_all=False, hide_override=set()): italic_format = '&lt;i&gt;{}&lt;/i&gt;'.format name_format = italic_format if isabstract(cls) else format attributes = [] methods = [] abstractmethods = getattr(cls, "__abstractmethods__", ()) for attr in classify_class_attrs(cls): if ((show_all or attr.name[0] != '_' or attr.name in abstractmethods) and not isinstance(attr.object, EXCLUDED_TYPES) and attr.name not in hide_override): if name in abstractmethods: name = italic_format(attr.name) else: name = attr.name if attr.kind in {'property', 'data'}: attributes.append(name) else: try: args = escape(str(signature(attr.object))) except (ValueError, TypeError) as e: print(f'was not able to get signature for {attr}, {repr(e)}') args = '()' methods.append(name + args) td_align = '&lt;td align="left" balign="left"&gt;' line_join = '&lt;br/&gt;'.join attr_section = f"&lt;hr/&gt;&lt;tr&gt;{td_align}{line_join(attributes)}&lt;/td&gt;&lt;/tr&gt;" method_section = f"&lt;hr/&gt;&lt;tr&gt;{td_align}{line_join(methods)}&lt;/td&gt;&lt;/tr&gt;" return f"""&lt; &lt;table border="1" cellborder="0" cellpadding="2" cellspacing="0" align="left"&gt; &lt;tr&gt;&lt;td align="center"&gt; &lt;b&gt;{name_format(cls.__name__)}&lt;/b&gt; &lt;/td&gt;&lt;/tr&gt; {attr_section} {method_section} &lt;/table&gt;&gt;""" </code></pre> <p>The code above gives us a way to create the tables for the nodes.</p> <p>Now we define a function that takes a classtree (the kind returned by <code>inspect.getclasstree(classes)</code>) and returns a fully instantiated <code>Digraph</code> object suitable to display an image.</p> <pre class="lang-py prettyprint-override"><code>def generate_dot( classtree, show_all=False, hide_override=HIDE_METHODS, show_object=False): """recurse through classtree structure and return a Digraph object """ dot = Digraph( name=None, comment=None, filename=None, directory=None, format='svg', engine=None, encoding='utf-8', graph_attr=None, node_attr=dict(shape='none'), edge_attr=dict( arrowtail='onormal', dir='back'), body=None, strict=False) def recurse(classtree): for classobjs in classtree: if isinstance(classobjs, tuple): cls, bases = classobjs if show_object or cls is not object: dot.node( cls.__name__, label=node_label(cls, show_all=show_all, hide_override=hide_override)) for base in bases: if show_object or base is not object: dot.edge(base.__name__, cls.__name__, style="dashed" if isabstract(base) else 'solid') if isinstance(classobjs, list): recurse(classobjs) recurse(classtree) return dot </code></pre> <p>And the usage:</p> <pre class="lang-py prettyprint-override"><code>classes = [c for c in vars(collections.abc).values() if isinstance(c, ABCMeta)] classtree = getclasstree(classes, unique=True) dot = generate_dot(classtree, show_all=True, show_object=True) #print(dot.source) # far too verbose... dot </code></pre> <p>We do <code>show_object=True</code> here, but since everything is an object in Python, it's a little redundant and will be at the top of every class hierarchy, so I think it's safe to use the default <code>show_object=False</code> for regular usage.</p> <pre class="lang-py prettyprint-override"><code>dot.render('abcs', format='png') </code></pre> <p>Gives us the following PNG file (since Stack Overflow does not let us show SVGs.):</p> <p><a href="https://i.stack.imgur.com/GemQf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GemQf.png" alt="ABC class hierarchy"></a></p> <h2>Suggestions for further work</h2> <p>An expert in Python or Graphviz might find important things we've missed here.</p> <p>We <em>could</em> factor out some functionality and write some unittests.</p> <p>We could also look for and handle annotations for data members normally held in <code>__dict__</code>.</p> <p>We might also not be handling all ways of creating Python objects as we should. </p> <p>I mostly used the following sample code to model the classes for building the node table:</p> <pre><code>from abc import abstractmethod, ABCMeta from inspect import isabstract, isfunction, classify_class_attrs, signature class NodeBase(metaclass=ABCMeta): __slots__ = 'slota', 'slotb' @abstractmethod def abstract_method(self, bar, baz=True): raise NotImplementedError def implemented_method(self, bar, baz=True): return True @property @abstractmethod def abstract_property(self): raise NotImplementedError @property def property(self): return False class NodeExample(NodeBase): __slots__ = 'slotc' NE = NodeExample </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T12:56:39.517", "Id": "456725", "Score": "0", "body": "Could you provide your code in one code block? I'm interested in this, but I don't copy multiple code blocks. Also do you think there are class attributes, not instance attributes, that are defined in `__dict__` but not on the type?" } ]
[ { "body": "<h2>Formatting</h2>\n\n<p>There are some statements with non-standard format in here that I'm not too bothered by, but this one makes my eye twitch:</p>\n\n<pre><code>EXCLUDED_TYPES = ( \n WrapperDescriptorType, # e.g. __repr__ and __lt__\n MethodDescriptorType, # e.g. __dir__, __format__, __reduce__, __reduce_ex__\n BuiltinFunctionType, # e.g. __new__\n ) \nHIDE_METHODS = {\n '__init_subclass__', # error warning, can't get signature\n '_abc_impl', '__subclasshook__', # why see this?\n '__abstractmethods__',\n }\n</code></pre>\n\n<p>Ending parens and braces should be at the level of indentation of the beginning of the first line of the statement, not the level of indentation of the opening paren/brace. If you run <code>pylint</code> on your code, it will produce this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>C0330: Wrong hanging indentation.\n )\n| | ^ (bad-continuation)\n</code></pre>\n\n<p>In other words,</p>\n\n<pre><code>EXCLUDED_TYPES = ( \n WrapperDescriptorType, # e.g. __repr__ and __lt__\n MethodDescriptorType, # e.g. __dir__, __format__, __reduce__, __reduce_ex__\n BuiltinFunctionType, # e.g. __new__\n) \nHIDE_METHODS = {\n '__init_subclass__', # error warning, can't get signature\n '_abc_impl', '__subclasshook__', # why see this?\n '__abstractmethods__',\n}\n</code></pre>\n\n<h2>Bug</h2>\n\n<p>This line:</p>\n\n<pre><code> if name in abstractmethods:\n</code></pre>\n\n<p>references <code>name</code> before it has been defined. Below I assume that you meant <code>attr.name</code>.</p>\n\n<h2>False positives</h2>\n\n<p>I do not think that <code>MethodDescriptorType</code> should be included in <code>EXCLUDED_TYPES</code>. When I passed <code>str</code> in, all but one of its instance methods were this type and were erroneously excluded.</p>\n\n<h2>Confusing signature defaults</h2>\n\n<p>When you fail to get a signature you display it as <code>()</code>, but that's misleading because it is a valid signature. Instead consider something like <code>(?)</code>.</p>\n\n<h2>Mutable defaults</h2>\n\n<p>Don't assign <code>hide_override</code> a default of <code>set()</code>, because that does not create a new set every time - it reuses the same set. If your function were to modify it it would contaminate future calls. For this reason many linters flag this and instead recommend that you give it a default of <code>None</code> and assign an empty set in the method itself.</p>\n\n<h2>Templating</h2>\n\n<p>Looking at your <code>node_label</code>, you could get a lot of mileage out of a templating engine like <a href=\"https://jinja.palletsprojects.com/en/2.11.x/\" rel=\"nofollow noreferrer\">Jinja</a>. From their documentation,</p>\n\n<blockquote>\n <p>Jinja is a general purpose template engine and not only used for HTML/XML generation. For example you may generate LaTeX, emails, CSS, JavaScript, or configuration files.</p>\n</blockquote>\n\n<p>So you should be able to handle GraphViz markup just fine. This will provide you with a cleaner way to separate your presentation layer.</p>\n\n<p>Here is some example code of what this could look like. First, the Python:</p>\n\n<pre><code>from html import escape\nfrom inspect import (\n isabstract,\n classify_class_attrs,\n signature,\n)\nfrom jinja2 import Template, FileSystemLoader, Environment\nfrom types import (\n WrapperDescriptorType,\n BuiltinFunctionType,\n)\nfrom typing import Type, Optional, Set\n\n\nEXCLUDED_TYPES = (\n WrapperDescriptorType, # e.g. __repr__ and __lt__\n # This does NOT only apply to functions like __dir__, __format__, __reduce__, __reduce_ex__\n # MethodDescriptorType,\n BuiltinFunctionType, # e.g. __new__\n)\n\n\ndef load_template(filename: str) -&gt; Template:\n # See https://stackoverflow.com/a/38642558/313768\n loader = FileSystemLoader(searchpath='./')\n env = Environment(loader=loader, autoescape=True)\n return env.get_template(filename)\n\n\nTEMPLATE = load_template('class.jinja')\n\n\ndef node_label(\n cls: Type,\n show_all: bool = False,\n hide_override: Optional[Set[str]] = None,\n) -&gt; str:\n if hide_override is None:\n hide_override = set()\n\n attributes, methods = [], []\n abstract_methods = set(getattr(cls, \"__abstractmethods__\", ()))\n\n for attr in classify_class_attrs(cls):\n if (\n (\n show_all\n or attr.name[0] != '_'\n or attr.name in abstract_methods\n )\n and not isinstance(attr.object, EXCLUDED_TYPES)\n and attr.name not in hide_override\n ):\n is_abstract = attr.name in abstract_methods\n\n if attr.kind in {'property', 'data'}:\n attributes.append((attr.name, is_abstract))\n else:\n try:\n args = escape(str(signature(attr.object)))\n except (ValueError, TypeError) as e:\n print(f'unable to get signature for {attr}, {repr(e)}')\n args = '(?)'\n methods.append((attr.name, args, is_abstract))\n\n attributes.sort()\n methods.sort()\n\n return TEMPLATE.render(\n name=cls.__name__,\n is_abstract=isabstract(cls),\n attributes=attributes,\n methods=methods,\n )\n\n\nfrom abc import ABC, abstractmethod\nclass NodeBase(ABC):\n __slots__ = 'slota', 'slotb'\n @abstractmethod\n def abstract_method(self, bar, baz=True):\n raise NotImplementedError\n def implemented_method(self, bar, baz=True):\n return True\n @property\n @abstractmethod\n def abstract_property(self):\n raise NotImplementedError\n @property\n def property(self):\n return False\n\n\nprint(node_label(AbstractExample))\n</code></pre>\n\n<p>And the template:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;\n &lt;table border=\"1\" cellborder=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"left\"&gt;\n &lt;tr&gt;\n &lt;td align=\"center\"&gt;\n &lt;b&gt;\n {%- if is_abstract -%}\n &lt;i&gt;{{name}}&lt;/i&gt;\n {%- else -%}\n {{name}}\n {%- endif -%}\n &lt;/b&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;tr&gt;\n &lt;td align=\"left\" balign=\"left\"&gt;\n {% for a_name, a_abstract in attributes %}\n {%- if a_abstract -%}\n &lt;i&gt;{{a_name}}&lt;/i&gt;\n {%- else -%}\n {{a_name}}\n {%- endif -%}\n &lt;br/&gt;\n {% endfor %}\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;tr&gt;\n &lt;td align=\"left\" balign=\"left\"&gt;\n {% for m_name, m_args, m_abstract in methods %}\n {%- if m_abstract -%}\n &lt;i&gt;{{m_name}}{{m_args}}&lt;/i&gt;\n {%- else -%}\n {{m_name}}{{m_args}}\n {%- endif -%}\n &lt;br/&gt;\n {% endfor %}\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;/table&gt;\n&gt;\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;\n &lt;table border=\"1\" cellborder=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"left\"&gt;\n &lt;tr&gt;\n &lt;td align=\"center\"&gt;\n &lt;b&gt;&lt;i&gt;NodeBase&lt;/i&gt;&lt;/b&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;tr&gt;\n &lt;td align=\"left\" balign=\"left\"&gt;\n &lt;i&gt;abstract_property&lt;/i&gt;&lt;br/&gt;\n property&lt;br/&gt;\n slota&lt;br/&gt;\n slotb&lt;br/&gt;\n\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;tr&gt;\n &lt;td align=\"left\" balign=\"left\"&gt;\n &lt;i&gt;abstract_method(self, bar, baz=True)&lt;/i&gt;&lt;br/&gt;\n implemented_method(self, bar, baz=True)&lt;br/&gt;\n\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;hr/&gt;\n\n &lt;/table&gt;\n&gt;\n</code></pre>\n\n<p>The template has been written in a simple, \"dumb\" fashion so there is some repetition, for example in the <code>td</code> definitions and the conditional italics. There are ways to reduce this that I will leave as an exercise to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T22:49:34.037", "Id": "471832", "Score": "1", "body": "As I said - \"Graphviz uses a syntax that looks like html (but isn't).\" - maybe it works for this - can you give an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T04:31:47.150", "Id": "471848", "Score": "0", "body": "Sure; edited. The suggested code is not a perfect one-to-one mapping of the output of your code (e.g. trailing break tags, whitespace, etc.)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:48:48.957", "Id": "472306", "Score": "0", "body": "p.s. in the process of creating the suggested code I uncovered a small handful of other issues. In particular, `name` not being defined at the right time surprised me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:00:27.347", "Id": "472308", "Score": "0", "body": "Since the code is supposed to be in a working state, should I fix it from my working copy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:02:14.707", "Id": "472309", "Score": "0", "body": "Based on https://codereview.meta.stackexchange.com/questions/9078/ the answer appears to be no - _If the question has been answered, you must not edit it in a way that would invalidate the answers; that is not permitted on Code Review._" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T21:11:16.337", "Id": "240526", "ParentId": "233604", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T19:59:36.300", "Id": "233604", "Score": "13", "Tags": [ "python", "object-oriented" ], "Title": "Draw a UML-style class hierarchy of Python's Abstract Base Classes with Python, python-graphviz, and graphviz" }
233604
<p>I have built an open-source project based on FluentAssertions in order to solve some recurring tasks I was doing while testing the .Net Core APIs I'm developing.</p> <p>I find the capability of doing in memory end-to-end tests of the APIs I build a great addition in terms of productivity and validity.</p> <p>With this project I want to solve two problems: to have a Assert API oriented for <strong>HttpResponseMessage</strong>, the type of response we get when we do an HTTP request with <em>HttpClient</em> and to get immediate feedback about what went wrong when the test fails, by providing the necessary details in the Test Explorer window from Visual Studio, so I can spend less time in debugging.</p> <p>I choose FluentAssertions because it treats extensibility as a feature, so they have a great API for doing so. Also, they provide a mechanism to build your own failure messages and link them to a specific type, which is exactly what I needed.</p> <p>The project is located <a href="https://github.com/adrianiftode/FluentAssertions.Web/" rel="noreferrer">here</a>.</p> <p>I have prepared a <a href="https://github.com/adrianiftode/FluentAssertions.Web/tree/code-review" rel="noreferrer">branch</a> for codereview.stackexchange.com to comply with the rule of not changing the code while you are reviewing it. Hopefully, this is OK, otherwise please let me know how I should proceed.</p> <p>The nuget package built from this version is</p> <pre><code>Install-Package FluentAssertions.Web -Version 1.0.113 </code></pre> <p>Next is an example of how it can be used</p> <pre><code>using FluentAssertions; using Microsoft.AspNetCore.Mvc.Testing; using Sample.Api.Net30.Controllers; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; namespace Sample.Api.Net30.Tests { public class CommentsControllerTests : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt; { private readonly WebApplicationFactory&lt;Startup&gt; _factory; public CommentsControllerTests(WebApplicationFactory&lt;Startup&gt; factory) { _factory = factory; } [Fact] public async Task Get_Returns_Ok_With_CommentsList() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments"); // Assert response.Should().Be200Ok().And.BeAs(new[] { new { Author = "Adrian", Content = "Hey" }, new { Author = "Johnny", Content = "Hey!" } }); } [Fact] public async Task Get_WithCommentId_Returns_Ok_With_The_Expected_Comment() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments/1"); // Assert response.Should().Be200Ok().And.BeAs(new { Author = "Adrian", Content = "Hey" }); } [Fact] public async Task Get_Returns_Ok_With_CommentsList_With_TwoUniqueComments() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments"); // Assert response.Should().Satisfy&lt;IReadOnlyCollection&lt;Comment&gt;&gt;( model =&gt; { model.Should().HaveCount(2); model.Should().OnlyHaveUniqueItems(c =&gt; c.CommentId); } ); } [Fact] public async Task Get_WithCommentId_Returns_A_NonSpam_Comment() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments/1"); // Assert response.Should().Satisfy(givenModelStructure: new { Author = default(string), Content = default(string) }, assertion: model =&gt; { model.Author.Should().NotBe("I DO SPAM!"); model.Content.Should().NotContain("BUY MORE"); }); } [Fact] public async Task Get_WithCommentId_Returns_Response_That_Satisfies_Several_Assertions() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments/1"); // Assert response.Should().Satisfy( r =&gt; { r.Content.Headers.ContentRange.Should().BeNull(); r.Content.Headers.Allow.Should().NotBeNull(); } ); } [Fact] public async Task Post_ReturnsOk() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent(@"{ ""author"": ""John"", ""content"": ""Hey, you..."" }", Encoding.UTF8, "application/json")); // Assert response.Should().Be200Ok(); } [Fact] public async Task Post_ReturnsOkAndWithContent() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent(@"{ ""author"": ""John"", ""content"": ""Hey, you..."" }", Encoding.UTF8, "application/json")); // Assert response.Should().Be200Ok().And.BeAs(new { Author = "John", Content = "Hey, you..." }); } [Fact] public async Task Post_WithNoContent_ReturnsBadRequest() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent("", Encoding.UTF8, "application/json")); // Assert response.Should().Be400BadRequest() .And.HaveErrorMessage("*The input does not contain any JSON tokens*"); } [Fact] public async Task Post_WithNoAuthorAndNoContent_ReturnsBadRequest() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent(@"{ ""author"": """", ""content"": """" }", Encoding.UTF8, "application/json")); // Assert response.Should().Be400BadRequest() .And.HaveError("Author", "The Author field is required.") .And.HaveError("Content", "The Content field is required."); } [Fact] public async Task Post_WithNoAuthor_ReturnsBadRequestWithUsefulMessage() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent(@"{ ""content"": ""Hey, you..."" }", Encoding.UTF8, "application/json")); // Assert response.Should().Be400BadRequest() .And.HaveError("Author", "The Author field is required.") .And.NotHaveError("content"); } [Fact] public async Task Post_WithNoAuthorButWithContent_ReturnsBadRequestWithAnErrorMessageRelatedToAuthorOnly() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync("/api/comments", new StringContent(@"{ ""content"": ""Hey, you..."" }", Encoding.UTF8, "application/json")); // Assert response.Should().Be400BadRequest() .And.OnlyHaveError("Author", "The Author field is required."); } } } </code></pre> <p>And the controller that handles the HTTP requests and the corresponding model looks like:</p> <pre><code>using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Sample.Api.Net30.Controllers { [Route("api/[controller]")] [ApiController] public class CommentsController : ControllerBase { [HttpGet] public IEnumerable&lt;Comment&gt; Get() =&gt; new[] { new Comment { Author = "Adrian", Content = "Hey", CommentId = 1}, new Comment { Author = "Johnny", Content = "Hey!", CommentId = 2 } }; [HttpGet("{id}")] public Comment Get(int id) =&gt; new Comment { Author = "Adrian", Content = "Hey", CommentId = id }; [HttpPost] public Comment Post([FromBody] Comment value) =&gt; value; } public class Comment { [Required] public string Author { get; set; } [Required, StringLength(maximumLength: 500)] public string Content { get; set; } public int CommentId { get; set; } } } </code></pre> <p>The assertion API aims to move the burden of remembering/typing the HTTP status codes as you have the option of recalling either the name or the number. Another common task is to deserialize the response to a certain model type and then to assert on.</p> <p>The other feature is to show as much information as possible from the request-response pair, when a test fails. So in this example, for the following test, I will get the subsequent messages.</p> <pre><code>[Fact] public async Task Get_Returns_Ok_With_CommentsList() { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync("/api/comments"); // Assert response.Should().Be200Ok().And.BeAs(new[] { new { Author = "Adrian", Content = "Hey" }, new { Author = "Johnny", Content = "Hey!" }, new { Author = "John", Content = "Hey!" } }); } </code></pre> <p>this test fails so the message is </p> <pre><code>Sample.Api.Net30.Tests.CommentsControllerTests.Get_Returns_Ok_With_CommentsList Source: CommentsControllerTests.cs line 22 Duration: 128 ms Message: Expected response to have a content equivalent to a model, but is has differences: - expected subjectModel to be a collection with 3 item(s), but {{ Author = Adrian, Content = Hey }, { Author = Johnny, Content = Hey! }}" "contains 1 item(s) less than" "{{ Author = Adrian, Content = Hey }, { Author = Johnny, Content = Hey! }, { Author = John, Content = Hey! }}. . The HTTP response was: HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Content-Length: 102 [ { "author": "Adrian", "content": "Hey", "commentId": 1 }, { "author": "Johnny", "content": "Hey!", "commentId": 2 } ] The originated HTTP request was: GET http://localhost/api/comments HTTP 1.1 Cookie: Content-Length: 0 Stack Trace: XUnit2TestFramework.Throw(String message) TestFrameworkProvider.Throw(String message) DefaultAssertionStrategy.HandleFailure(String message) AssertionScope.FailWith(Func`1 failReasonFunc) AssertionScope.FailWith(Func`1 failReasonFunc) AssertionScope.FailWith(String message, Object[] args) HttpResponseMessageAssertions.BeAs[TModel](TModel expectedModel, String because, Object[] becauseArgs) line 52 CommentsControllerTests.Get_Returns_Ok_With_CommentsList() line 31 --- End of stack trace from previous location where exception was thrown --- </code></pre> <p>This particular test uses <code>Be200Ok</code> and <code>BeAs&lt;&gt;</code> assertions. I will provide next the <code>BeAs</code> assertions to make a picture of how these are implemented</p> <pre><code>using FluentAssertions.Execution; using FluentAssertions.Web.Internal; using System; using System.Net.Http; namespace FluentAssertions.Web { /// &lt;summary&gt; /// Contains a number of methods to assert that an &lt;see cref="HttpResponseMessage"/&gt; is in the expected state related to the HTTP content. /// &lt;/summary&gt; public partial class HttpResponseMessageAssertions { /// &lt;summary&gt; /// Asserts that HTTP response content can be an equivalent representation of the expected model. /// &lt;/summary&gt; /// &lt;param name="expectedModel"&gt; /// The expected model. /// &lt;/param&gt; /// &lt;param name="because"&gt; /// A formatted phrase as is supported by &lt;see cref="string.Format(string,object[])" /&gt; explaining why the assertion /// is needed. If the phrase does not start with the word &lt;i&gt;because&lt;/i&gt;, it is prepended automatically. /// &lt;/param&gt; /// &lt;param name="becauseArgs"&gt; /// Zero or more objects to format using the placeholders in &lt;see paramref="because" /&gt;. /// &lt;/param&gt; public AndConstraint&lt;HttpResponseMessageAssertions&gt; BeAs&lt;TModel&gt;(TModel expectedModel, string because = "", params object[] becauseArgs) { ExecuteSubjectNotNull(because, becauseArgs); if (expectedModel == null) { throw new ArgumentNullException(nameof(expectedModel), "Cannot verify having a content equivalent to a model against a &lt;null&gt; model."); } var success = TryGetSubjectModel&lt;TModel&gt;(out var subjectModel); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(success) .FailWith("Expected {context:response} to have a content equivalent to a model, but the JSON representation could not be parsed{reason}. {0}", Subject); string[] failures; using (var scope = new AssertionScope()) { subjectModel.Should().BeEquivalentTo(expectedModel); failures = scope.Discard(); } Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(failures.Length == 0) .FailWith("Expected {context:response} to have a content equivalent to a model, but is has differences:{0}{reason}. {1}", new AssertionsFailures(failures), Subject); return new AndConstraint&lt;HttpResponseMessageAssertions&gt;(this); } /// &lt;summary&gt; /// Asserts that HTTP response has content that matches a wildcard pattern. /// &lt;/summary&gt; /// &lt;param name="expectedWildcardText"&gt; /// The wildcard pattern with which the subject is matched, where * and ? have special meanings. /// &lt;/param&gt; /// &lt;param name="because"&gt; /// A formatted phrase as is supported by &lt;see cref="string.Format(string,object[])" /&gt; explaining why the assertion /// is needed. If the phrase does not start with the word &lt;i&gt;because&lt;/i&gt;, it is prepended automatically. /// &lt;/param&gt; /// &lt;param name="becauseArgs"&gt; /// Zero or more objects to format using the placeholders in &lt;see paramref="because" /&gt;. /// &lt;/param&gt; public AndConstraint&lt;HttpResponseMessageAssertions&gt; MatchInContent(string expectedWildcardText, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expectedWildcardText, nameof(expectedWildcardText), "Cannot verify a HTTP response content match a &lt;null&gt; wildcard pattern."); ExecuteSubjectNotNull(because, becauseArgs); var content = GetContent(); if (string.IsNullOrEmpty(content)) { Execute.Assertion .BecauseOf(because, becauseArgs) .FailWith("Expected {context:response} to match the wildcard pattern {0} in its content, but content was &lt;null&gt;{reason}. {1}", expectedWildcardText, Subject); } string[] failures; using (var scope = new AssertionScope()) { content.Should().Match(expectedWildcardText); failures = scope.Discard(); } Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(failures.Length == 0) .FailWith("Expected {context:response} to match a wildcard pattern in its content, but does not since:{0}{reason}. {1}", new AssertionsFailures(failures), Subject); return new AndConstraint&lt;HttpResponseMessageAssertions&gt;(this); } } } </code></pre> <p>In order to tell FluentAssertions how to display failure messages, you can implement the <code>IValueFormatter</code> so I have one for <code>HttpResponseMessage</code></p> <pre><code>using FluentAssertions.Formatting; using FluentAssertions.Web.Internal; using FluentAssertions.Web.Internal.ContentProcessors; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace FluentAssertions.Web { internal class HttpResponseMessageFormatter : IValueFormatter { public bool CanHandle(object value) =&gt; value is HttpResponseMessage; /// &lt;inheritdoc /&gt; public string Format(object value, FormattingContext context, FormatChild formatChild) { var response = (HttpResponseMessage)value; var messageBuilder = new StringBuilder(); messageBuilder.AppendLine(); messageBuilder.AppendLine(); messageBuilder.AppendLine("The HTTP response was:"); Func&lt;Task&gt; contentResolver = async () =&gt; await AppendHttpResponseMessage(messageBuilder, response); contentResolver.ExecuteInDefaultSynchronizationContext().GetAwaiter().GetResult(); return messageBuilder.ToString(); } private static async Task AppendHttpResponseMessage(StringBuilder messageBuilder, HttpResponseMessage response) { await AppendResponse(messageBuilder, response); await AppendRequest(messageBuilder, response); } private static async Task AppendResponse(StringBuilder messageBuilder, HttpResponseMessage response) { AppendProtocolAndStatusCode(messageBuilder, response); Appender.AppendHeaders(messageBuilder, response.GetHeaders()); AppendContentLength(messageBuilder, response); await AppendResponseContent(messageBuilder, response); } private static async Task AppendRequest(StringBuilder messageBuilder, HttpResponseMessage response) { var request = response.RequestMessage; messageBuilder.AppendLine(); if (request == null) { messageBuilder.AppendLine("The originated HTTP request was &lt;null&gt;."); return; } messageBuilder.AppendLine("The originated HTTP request was:"); messageBuilder.AppendLine(); messageBuilder.AppendLine($"{request.Method.ToString().ToUpper()} {request.RequestUri} HTTP {request.Version}"); Appender.AppendHeaders(messageBuilder, request.GetHeaders()); AppendContentLength(messageBuilder, request); messageBuilder.AppendLine(); await AppendRequestContent(messageBuilder, request.Content); } private static async Task AppendResponseContent(StringBuilder messageBuilder, HttpResponseMessage response) { var content = response.Content; if (content == null) { return; } var processors = new List&lt;IContentProcessor&gt;(); processors.Add(new InternalServerErrorProcessor(response, content)); processors.AddRange(ProcessorsRunner.CommonProcessors(content)); var contentBuilder = await ProcessorsRunner.RunProcessors(processors); messageBuilder.AppendLine(); messageBuilder.Append(contentBuilder); } private static async Task AppendRequestContent(StringBuilder messageBuilder, HttpContent content) { await Appender.AppendContent(messageBuilder, content); } private static void AppendProtocolAndStatusCode(StringBuilder messageBuilder, HttpResponseMessage response) { messageBuilder.AppendLine(); messageBuilder.AppendLine($@"HTTP/{response.Version} {(int)response.StatusCode} {response.StatusCode}"); } private static void AppendContentLength(StringBuilder messageBuilder, HttpResponseMessage response) { if (!response.GetHeaders().Any(c =&gt; string.Equals(c.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))) { messageBuilder.AppendLine($"Content-Length: {response.Content?.Headers.ContentLength ?? 0}"); } } private static void AppendContentLength(StringBuilder messageBuilder, HttpRequestMessage request) { if (!request.GetHeaders() .Any(c =&gt; string.Equals(c.Key, "Content-Length", StringComparison.OrdinalIgnoreCase)) ) { request.Content.TryGetContentLength(out long contentLength); messageBuilder.AppendLine($"Content-Length: {contentLength}"); } } } } </code></pre> <p>This class and its collaborators have increased complexity and unfortunately, fewer unit tests. Thus this is also a source of pain points lately, so I will have at some moment to invest more in this regard. The collaborators are some classes that have the knowledge of building failure messages based on certain predicates, like the <code>HttpContent</code> type and/or other aspects of the subjected <code>HttpResponse</code>. So for example for a JSON it will print it and beautify it, for a binary type like data, just an informative error message and for the an internal server error it will try to parse the stack trace embedded in the developer page. Next is the <code>JsonProcessor</code>.</p> <pre><code>using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace FluentAssertions.Web.Internal.ContentProcessors { internal class JsonProcessor : ProcessorBase { private readonly HttpContent _httpContent; public JsonProcessor(HttpContent httpContent) { _httpContent = httpContent; } protected override async Task Handle(StringBuilder contentBuilder) { var content = await _httpContent.SafeReadAsStringAsync(); var beautified = content?.BeautifyJson(); if (!string.IsNullOrEmpty(beautified)) { contentBuilder.Append(beautified); } } protected override bool CanHandle() { if (_httpContent == null) { return false; } _httpContent.TryGetContentLength(out long length); var mediaType = _httpContent.Headers.ContentType?.MediaType; return length &lt;= ContentFormatterOptions.MaximumReadableBytes &amp;&amp; (mediaType.EqualsCaseInsensitive("application/json") || mediaType.EqualsCaseInsensitive("application/problem+json")); } } } </code></pre> <p>I feel at this moment that I'm close to a first production release, but I didn't get yet through a code review, to see what others think about this tool, so I kindly ask you to help me out.</p> <p>So there would be some of my questions:</p> <ul> <li>How complete do you find the assertion API, does the current one fit the day-to-day work? Do you have more suggestions?</li> <li>I focused on writing quality code and went also with some of the C# 8.0 features. I most likely missed some aspects, please point them </li> <li>Do the samples fulfill their purpose?</li> <li>Is the documentation relevant? Are the unit tests complete, beyond code coverage?</li> <li>Any other aspects like CI/CD, automated builds, nuget releases?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:13:34.000", "Id": "462013", "Score": "0", "body": "The fact that nobody has written an answer yet seems to be a big compliment :D" } ]
[ { "body": "<p>I created a very similar extension to <code>FluentAssertions</code> a while ago, which i have now abandoned. Here are my thoughts:</p>\n<p><code>Be400BadRequest</code></p>\n<p>There is no question what is asserted here, but on the other hand it might get tedious and repetitive to include both the status code and status name in the method. It is just a handful of status codes that are commonly used, so ommitting the number should be OK. An alternative could be <code>HaveStatusCode(HttpStatusCode.BadRequest)</code> which is also more correct (a response <strong>has</strong> a status but <strong>is not</strong> a status).</p>\n<p>Moreover, you can add additional convenience assertions such as</p>\n<pre><code> response.Should().HaveServerErrorStatusCode();\n response.Should().HaveRedirectionStatusCode();\n response.Should().HaveClientErrorStatusCode();\n response.Should().HaveSuccessStatusCode();\n</code></pre>\n<p><code>BeAs</code></p>\n<p>I think <code>HaveContent</code> makes more sense, because again, a response might <strong>have</strong> a content/body but <strong>is not</strong> a content/body.\nYou can also do more around content assertions, like the ability to selectively assert it. For example:</p>\n<pre><code>\n response.Should().HaveContentWithProperty&lt;CustomerModel&gt;(x =&gt; x.Name, &quot;expectedname&quot;);\n</code></pre>\n<p>A general tip, about chaining. Since users can chain the assertions in any way, it is important to really think about as many common chaining use cases as possible, and verify that those make sense.</p>\n<p>About using language features of c#, Visual Studio (plus plugins) can provide code suggestions in a much more effective way than i can do here manually.</p>\n<p>Here is my project, for reference:</p>\n<p><a href=\"https://github.com/balanikas/FluentAssertions.Http\" rel=\"nofollow noreferrer\">https://github.com/balanikas/FluentAssertions.Http</a>\n<a href=\"https://www.nuget.org/packages/FluentAssertions.Http/1.0.0-beta1\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/FluentAssertions.Http/1.0.0-beta1</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T11:46:19.917", "Id": "500823", "Score": "0", "body": "Thank you, I know about your project, I learned about it when I researched what already exists. The reason I went with BeXXX is just that when people talk about HTTP requests they usually say \"this request is a bad request because of this content\". There is also a HaveHttpStatus and NotHaveHttpStatus btw, among other Have extensions (HaveHeader, HaveError when there is a bad request etc)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T20:57:23.213", "Id": "253939", "ParentId": "233608", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T21:47:09.807", "Id": "233608", "Score": "16", "Tags": [ "c#", ".net", "unit-testing", "library", "fluent-assertions" ], "Title": "Open source project to ease the Assert part from the functional tests of .Net Core Web APIs" }
233608
<p><strong>EDIT1:</strong> Suspicion that mariadb++ is affecting my performance results compared to the raw "mariadb/mysql Connector-C"?? </p> <p><strong>EDIT2</strong>: I did a barebones C-Only implementation and it comes in at 222ms vs the 262ms using mariadb++. 40ms is significant, given the fixed DB overhead. </p> <p><strong>EDIT3:</strong> Changed <code>mysql_store_result</code> to <code>mysql_use_result</code>, which means "unbuffered query" in MySQL lingo (php was already using that)... => 130ms. Half (!) of where we were, and about 3x <code>php</code> speed now. mariadb++ seems to always use mysql_store_result. I have <a href="https://github.com/viaduck/mariadbpp/issues/33" rel="nofollow noreferrer">filed an issue</a> on mariadb++. --- If someone could still have a look at my c++ string and map processing that would be great...</p> <hr> <p>Possible answer with a c++ wrapper around the mysql_* functions <a href="https://codereview.stackexchange.com/a/233622/212940">in this answer below</a>.</p> <hr> <p><strong>Original Question..</strong></p> <p>Somewhat simplified task is to efficiently extract about a 250,000 user records from a mariadb and do some string munging and then find the "TopN" (eg most common firstnames, etc) for 3 fields. </p> <p>Focus is on performance (real life case is bigger). Focus is firstly on algorithm: I think the unordered_map hashtable followed by partial_sort_copy is pretty efficient, but happy to be proved wrong. Second focus is on the string munging mechanics. Am I extracting/munging and mapping efficiently? With as few <code>std::string</code> copies as possible? (I realise the std::tolower() is not properly utf8 compatible). I decided on a <code>std::move</code> in one place. See comments.</p> <p>The benchmark is similar code in ("cough") <code>php</code> which is actually NOT HALF BAD! <code>php</code> was only about 50% slower than this c++ code compiled with <code>clang-8 -O3</code>. Database is localhost and data is in memory. If I repeat code in loop, I get 50% of one CPU core on this process and 50% of another CPU core on the mysqld process. I realise the database is a big part of the problem here. Trying to minimise the rest. </p> <p>Not particularly "generic" and not trying to be, just clear fast code. </p> <p>Code review / advice please? Timing results at bottom (my own mini timer class, not relevant). Connection details left off. </p> <p>BTW: I thought of the "do it in the DB" way. I can do one (not 3!) fields in the DB in 300ms (more than the c++ takes for all 3 fields). The DB query can't do all 3 fields at the same time. I used: <code>SELECT field, count(*) as cnt group by field order by cnt desc limit 10;</code>. Even the <code>php</code> code is faster than that. </p> <pre><code> #include "mariadb++/account.hpp" #include "mariadb++/concurrency.hpp" #include "mariadb++/connection.hpp" #include "mariadb++/statement.hpp" #include "mariadb++/types.hpp" #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; void ltrim(std::string&amp; s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } void rtrim(std::string&amp; s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } void trim(std::string&amp; s) { ltrim(s); rtrim(s); } void strtolower(std::string&amp; s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); } ); } std::vector&lt;std::pair&lt;std::string, int&gt;&gt; top_n(const std::unordered_map&lt;std::string, int&gt;&amp; map, int n) { std::vector&lt;std::pair&lt;std::string, int&gt;&gt; top_n(n, {"", 0}); std::partial_sort_copy(map.begin(), map.end(), top_n.begin(), top_n.end(), [](auto&amp; a, auto&amp; b) { return a.second &gt; b.second; }); return top_n; } void print (const std::vector&lt;std::pair&lt;std::string, int&gt;&gt;&amp; top_n) { std::for_each(top_n.begin(), top_n.end(), [](auto&amp; e) { std::cout &lt;&lt; e.first &lt;&lt; ": " &lt;&lt; e.second &lt;&lt; "\n"; }); } int main() { std::shared_ptr&lt;mariadb::connection&gt; m_con = con(); mariadb::statement_ref qry = m_con-&gt;create_statement("select email,firstname,lastname from member"); std::unordered_map&lt;std::string, int&gt; domains, firstnames, lastnames; { Timer t1("fetch"); mariadb::result_set_ref res = qry-&gt;query(); while (res-&gt;next()) { // mariadb++ creates a copy, but it needs to. The result row will die shortly. std::string domain = res-&gt;get_string(0); trim(domain); // in place if (size_t pos = domain.find('@'); pos != std::string::npos) { strtolower(domain); // in place // this temporary will get moved domains[domain.substr(pos + 1)]++; } std::string firstname = res-&gt;get_string(1); trim(firstname); strtolower(firstname); // godbolt testing seems to show std::move prevents a copy here firstnames[std::move(firstname)]++; std::string lastname = res-&gt;get_string(2); trim(lastname); strtolower(lastname); lastnames[std::move(lastname)]++; } } { const int n = 10; Timer t1("freqs"); std::cout &lt;&lt; "\ndomains\n"; print(top_n(domains, n)); std::cout &lt;&lt; "\nfirstnames\n"; print(top_n(firstnames, n)); std::cout &lt;&lt; "\nlastnames\n"; print(top_n(lastnames, n)); } } </code></pre> <p>Basic profiling results (and output so it's more obvious what the code does). </p> <pre class="lang-none prettyprint-override"><code>fetch=262.02ms domains t...sanitised: 53687 g...: 41827 h...: 17583 ... firstnames david: 4042 john: 3348 james: 2774 ... lastnames smith: 2142 jones: 1652 williams: 1187 ... freqs=2.87693ms </code></pre> <p>Just for comparison here is the <code>php</code> code:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php $con = new PDO('...sanitised...'); $con-&gt;setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $domains = []; $firstnames = []; $lastnames = []; $start = microtime(true); foreach ($con-&gt;query("select email,firstname,lastname from member;", PDO::FETCH_NUM) as $row) { $domain = trim($row[0]); $domain = substr($domain, strpos($domain, '@') + 1); if (!isset($domains[$domain])) $domains[$domain] = 0; $domains[$domain]++; $firstname = strtolower(trim($row[1])); if (!isset($firstnames[$firstname])) $firstnames[$firstname] = 0; $firstnames[$firstname]++; $lastname = strtolower(trim($row[2])); if (!isset($lastnames[$lastname])) $lastnames[$lastname] = 0; $lastnames[$lastname]++; } echo "fetch=" . round((microtime(true) - $start) * 1000, 2) . "\n"; $start = microtime(true); echo "\ndomains\n"; arsort($domains); foreach (array_slice($domains, 0, 10) as $domain =&gt; $freq) { echo $domain . ': ' . $freq. "\n"; } echo "\nfirstnames\n"; arsort($firstnames); foreach (array_slice($firstnames, 0, 10) as $firstname =&gt; $freq) { echo $firstname . ': ' . $freq. "\n"; } echo "\nlastnames\n"; arsort($lastnames); foreach (array_slice($lastnames, 0, 10) as $lastname =&gt; $freq) { echo $lastname . ': ' . $freq. "\n"; } echo "freqs=" . round((microtime(true) - $start) * 1000, 2) . "\n"; </code></pre> <p>And the slightly depressing (from a <code>c++</code> POV) performance results. 370ms vs 262ms (lowest on 10 trials for both). (<strong>UPDATE</strong>: at top. After bypassing mariadb++ and using C-lib directly with mysql_use_result the c++ dropped to 128ms or almost 3x faster than php with lots of mysqld overhead -- better). C++ was faster by 3x on the "freqs" section, but it's apples and oranges, because php is doing a sort of the whole array and c++ is doing a partial_sort_copy of the top10. </p> <pre class="lang-none prettyprint-override"><code>fetch=370.93ms domains ... firstnames ... lastnames ... freqs=11.1ms </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T23:32:04.447", "Id": "456700", "Score": "0", "body": "Did you try using any stored procedures? It might improve the performance for both the c++ and php. Sorting in the database should be faster if you have indexes set up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T23:36:10.263", "Id": "456701", "Score": "0", "body": "I didn't. Because a) This is a sort of proof of concept of how easy and performant it is do this sort of thing in c++ vs php. and b) you can write the SQL easily for one field, but to do 3 fields you have to run 3 group by queries. One query in the DB is already slower than 3 field in php or c++ (see above). A stored procedure (in Mariadb or Mysql at least) won;t change that. stored procedures only help when you are running many queries, saves the round trip formatting of data... this is not the case here. Happy to be corrected, but in MySQL i think that's right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T23:42:17.307", "Id": "456702", "Score": "0", "body": "I, just now, tried adding an index to the firstname field and reran the query. It's 250ms now vs 300ms before. It's a complete table scan that's why, the index only marginally helps with the group by. new SQL: `select SQL_NO_CACHE lower(trim(firstname)) as fname, count(*) as cnt from member group by fname order by cnt desc limit 10`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T23:43:21.883", "Id": "456703", "Score": "0", "body": "here is mysql's \"explain\": `SIMPLE member index NULL firstname 98 NULL 228383 Using index; Using temporary; Using filesort` After 20yrs with MySQL, i have always found that for some jobs, it's best to pull the data back and do the \"processing and summarising\" in the application. This is one of those cases. That's why we are considering doing it in c++ hoping that's quicker. Not much it seems..." } ]
[ { "body": "<p>Providing a possible answer to my own question. Leaving original in tact for the record. </p>\n\n<p>In order to address the performance issues with mariadb++ I wrote a <strong>very</strong> slimline, and zero cost, c++ abstraction around mysql-Connector-C. Uses c++17 features like <code>if () initialiser</code> and <code>std::optional</code>.</p>\n\n<p>Please comment on that abstraction as well as the string munge and mapping stuff which is still here, basically unchanged. Performance is identical to using the plain C mysql.h functions: 128ms or ~3x speed of the php code with mysqld maxed out at 100% CPU, ie it's now the bottleneck. </p>\n\n<p>What does the c++ wrapper add? </p>\n\n<ul>\n<li>simpler, cleaner signatures</li>\n<li>no pointers</li>\n<li>RAII to free resources</li>\n<li>std::optional for \"now more rows\" and \"field value is NULL\"</li>\n</ul>\n\n<pre><code>#include \"mysql.h\"\n#include &lt;string&gt;\n#include &lt;unordered_map&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\n// Very slimline wrapper around mysql connector-C. Limited features. Zero cost abstraction\nnamespace mysqlpp {\nclass row {\npublic:\n explicit row(MYSQL_ROW row_) : _row{row_} {}\n\n // This helps with NULL columns, but does NOT make a copy. That's up to caller.\n std::optional&lt;const char*&gt; getField(size_t pos) {\n if (!_row[pos]) return std::nullopt;\n return std::optional&lt;const char*&gt;(_row[pos]);\n }\n\nprivate:\n MYSQL_ROW _row;\n};\n\nclass result {\npublic:\n result(MYSQL_RES* result_) : _result{result_} {}\n ~result() { mysql_free_result(_result); } // RAII\n\n std::optional&lt;row&gt; next() {\n auto r = mysql_fetch_row(_result);\n if (!r) return std::nullopt;\n return std::optional&lt;row&gt;(row(r));\n }\n\nprivate:\n MYSQL_RES* _result;\n};\n\nclass conn {\npublic:\n conn(const char* host, const char* user, const char* passwd, const char* db, unsigned int port,\n const char* unix_socket, unsigned long clientflag) {\n\n mysql = mysql_init(NULL);\n if (!mysql_real_connect(mysql, host, user, passwd, db, port, unix_socket, clientflag))\n show_error();\n }\n\n ~conn() { mysql_close(mysql); } // RAII\n\n result query(std::string sql) {\n if (mysql_real_query(mysql, sql.c_str(), sql.length())) show_error();\n MYSQL_RES* res = mysql_use_result(mysql);\n if (res == NULL) show_error();\n return result(res);\n }\n\nprivate:\n void show_error() {\n std::cerr &lt;&lt; \"Error(\" &lt;&lt; mysql_errno(mysql) &lt;&lt; \") \"\n &lt;&lt; \"[\" &lt;&lt; mysql_sqlstate(mysql) &lt;&lt; \"] \"\n &lt;&lt; \"\\\"\" &lt;&lt; mysql_error(mysql) &lt;&lt; \"\\\"\";\n mysql_close(mysql);\n exit(EXIT_FAILURE);\n }\n\n MYSQL* mysql;\n};\n\n} // end namespace mysqlpp\n\ntypedef std::unordered_map&lt;std::string, int&gt; TopNMap;\ntypedef std::vector&lt;std::pair&lt;std::string, int&gt;&gt; TopNResult;\n\nTopNResult top_n(const TopNMap&amp; map, int n) {\n TopNResult top_n(n, {\"\", 0});\n std::partial_sort_copy(map.begin(), map.end(), top_n.begin(), top_n.end(),\n [](auto&amp; a, auto&amp; b) { return a.second &gt; b.second; });\n return top_n;\n}\n\nvoid report(const TopNMap&amp; map, int n, std::string label) {\n std::cout &lt;&lt; \"\\n\" &lt;&lt; std::to_string(map.size()) &lt;&lt; \" unique \" &lt;&lt; label &lt;&lt; \"\\n\";\n TopNResult result = top_n(map, n);\n std::for_each(result.begin(), result.end(),\n [](auto&amp; e) { std::cout &lt;&lt; e.first &lt;&lt; \": \" &lt;&lt; e.second &lt;&lt; \"\\n\"; });\n}\n\nint main() {\n mysqlpp::conn mysql(\"localhost\", \"...\", \"...\", \"...\", 0,\n \"/var/run/mysqld/mysqld.sock\", 0);\n\n TopNMap domains;\n TopNMap firstnames;\n TopNMap lastnames;\n auto result = mysql.query(\"select email,firstname,lastname from member\");\n while (auto row = result.next()) {\n if (auto maybe_domain = row-&gt;getField(0)) {\n std::string domain = maybe_domain.value(); // make that copy!\n trim(domain);\n if (size_t pos = domain.find('@'); pos != std::string::npos) {\n strtolower(domain);\n domains[domain.substr(pos + 1)]++;\n }\n }\n\n if (auto maybe_firstname = row-&gt;getField(1)) {\n std::string firstname = maybe_firstname.value();\n trim(firstname);\n strtolower(firstname);\n firstnames[std::move(firstname)]++;\n }\n\n if (auto maybe_lastname = row-&gt;getField(2)) {\n std::string lastname = maybe_lastname.value();\n trim(lastname);\n strtolower(lastname);\n lastnames[std::move(lastname)]++;\n }\n }\n\n const int n = 10;\n report(domains, n, \"domains\");\n report(firstnames, n, \"firstnames\");\n report(lastnames, n, \"lastnames\");\n return EXIT_SUCCESS;\n}\n\n<span class=\"math-container\">```</span> \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T11:52:56.697", "Id": "233622", "ParentId": "233609", "Score": "0" } }, { "body": "<p><strong>String Operations</strong></p>\n\n<p>You're copying a string and then starting to make various transformations to it. As <code>std::isspace</code> and <code>std::tolower</code> end up being called and can have quite complex logic, avoiding them (and using plain for/if) can bring a significant improvement to this part, especially if you are only interested in ASCII.</p>\n\n<p><strong>Server-side VS client-side processing</strong></p>\n\n<p>Have you tried writing the code so that it runs inside the database server? Passing all this data around is costly. </p>\n\n<p>Have you tried other database technologies that might offer good enough performance using simple queries?</p>\n\n<p><strong>Use case</strong></p>\n\n<p>As we're talking about milliseconds, isn't it enough to just run the query in the database? Will the statistics be computed often (e.g. every time a page is openned)? If so, computing them differently (say an update when a change occurs) might make more sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:33:42.763", "Id": "456740", "Score": "0", "body": "The string ops point, is a good one, I will experiment. Yes I have spent much time trying to do it server side (as mentioned above), but a DB server is a \"general query machine\", which is not optimal for all operations. Sometimes, not often but regularly, it is faster so share the load server/client side. On use case: yes, the real life case is bigger and slower and it is running interactive reports of such variety that caching or pre-computing doesn't necessarily make sense (it does in some cases though, so your point is well made)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:35:49.017", "Id": "456741", "Score": "0", "body": "On the whole I find people treat DB servers like a holy grail, They are not that, but are just convenient for common operations. As soon as it gets more specialised, a combination with client side code can easily be faster... even in relatively slow client side technologies like `php` as above example shows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:42:50.183", "Id": "456742", "Score": "0", "body": "Some databases allow you to write code in C/C++ and execute it inside the server process, e.g. https://www.postgresql.org/docs/current/xfunc-c.html MySQL/MariaDB might offer something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:51:06.747", "Id": "456743", "Score": "0", "body": "Nice! I hadn't seen that. That looks more flexible than what Mysql/mariadb offers for UDFs written in C. I am sure that would be fast as it avoids the \"data pumping\" like you say. You would have to be very very sure that you are not going to take the whole server down, or lock it up on some way, etc.... ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T12:53:55.563", "Id": "233624", "ParentId": "233609", "Score": "3" } }, { "body": "<p><strong>Another \"comparative self answer\" of sorts</strong></p>\n\n<hr>\n\n<p><strong>EDIT</strong>: Against my better judgement I tried <code>buffered=True</code> on the python connection. And it's faster: 790ms => only 2x slower than <code>php</code></p>\n\n<hr>\n\n<p>Just for laughs I tried <code>python3</code> (caveat I am not a python programmer, so this may not be the most efficient way). Code below. <strong>Result 1200ms</strong>! ~3x slower than php and ~9x slower than c++. So for python running 3 x <code>group by</code> queries on DB server makes more sense. </p>\n\n<p>To be honest this is the sort of difference (ie 10x) I expected between php and c++. However i think php7 got a lot quicker on arrays, and php and mysql are a \"highly optimized matched pair\". </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import mysql.connector\n\ncnx = mysql.connector.connect(user='...', database='...', password='...')\ncursor = cnx.cursor()\n\nquery = (\"select email,firstname,lastname from member\")\n\ndomains = dict()\nfirstnames = dict()\nlastnames = dict()\n\ncursor.execute(query)\n\nfor (email, firstname, lastname) in cursor:\n pieces = email.strip().split(\"@\")\n if len(pieces) == 2:\n domain = pieces[1].lower()\n if domain not in domains:\n domains[domain] = 0\n domains[domain] = domains[domain] + 1\n\n fname = firstname.strip().lower()\n if fname not in firstnames:\n firstnames[fname] = 0\n firstnames[fname] = firstnames[fname] + 1\n\n lname = lastname.strip().lower()\n if lname not in lastnames:\n lastnames[lname] = 0\n lastnames[lname] = lastnames[lname] + 1\n\nprint(\"\\domains\")\n# tried this as well, no time difference\n# top_domains = heapq.nlargest(10, domains.items(), key=lambda kv: kv[1])\ntop_domains = sorted(domains.items(), key=lambda kv: kv[1], reverse=True)\nfor domain in top_domains[0:10]:\n print(domain[1], domain[0])\n\nprint(\"\\nfirstnames\")\ntop_firstnames = sorted(firstnames.items(), key=lambda kv: kv[1], reverse=True)\nfor firstname in top_firstnames[0:10]:\n print(firstname[1], firstname[0])\n\nprint(\"\\nlastnames\")\ntop_lastnames = sorted(lastnames.items(), key=lambda kv: kv[1], reverse=True)\nfor lastname in top_lastnames[0:10]:\n print(lastname[1], lastname[0])\n\n\ncursor.close()\ncnx.close()\n\n</code></pre>\n\n<p>But the python code is definitely the prettiest and was really quick to write, given I don't know python. ;-)</p>\n\n<p>Before someone shoots me, note that I used the following options on the connection:</p>\n\n<ul>\n<li>buffered = false (same as php and c++, should be faster) <strong>this is wrong</strong> refer top</li>\n<li>use_pure = false (use the C-extension, the pure python one is MUCH slower)</li>\n<li>raw = false (ie DO convert to python types. I am not good enough at python to understand how you do anything with the raw strings <code>.split()</code> <code>.lower()</code> and friends certainly don't work). I could well imagine that this forced type conversion from the mysql C-connector, where everything will be a null terminated c-style string ( a <code>const char*</code> in c++ lingo) , and python <code>String</code> Objects could be a major bottle neck. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:39:39.547", "Id": "233639", "ParentId": "233609", "Score": "1" } } ]
{ "AcceptedAnswerId": "233622", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T22:03:06.197", "Id": "233609", "Score": "2", "Tags": [ "c++", "performance", "php", "mysql", "comparative-review" ], "Title": "MySQL/MariaDB Data extraction / String manipulation / \"TopN\" processing => Performance of C++ vs php vs python" }
233609
<p>I have written a function to calculate all strong components in a graph. </p> <p>How do I make this cleaner and nicer?</p> <pre><code> import java.util.* import kotlin.math.min private fun readLn() = readLine()!! // string line private fun readInt() = readLn().toInt() // single int private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints typealias Graph&lt;T&gt; = Map&lt;T, List&lt;T&gt;&gt; fun getScc(graph: Graph&lt;String&gt;, allNodes: Set&lt;String&gt;): MutableList&lt;List&lt;String&gt;&gt; { val discoveryTime = mutableMapOf&lt;String, Int&gt;() val lowest = mutableMapOf&lt;String, Int&gt;() val stack = ArrayDeque&lt;String&gt;() var index = 0 val strongComponents = mutableListOf&lt;List&lt;String&gt;&gt;() val resolved = mutableSetOf&lt;String&gt;() fun dfs(node: String) { index += 1 discoveryTime[node] = index lowest[node] = index stack.addLast(node) for (neb in graph[node] ?: mutableListOf()) { if (neb in resolved) { continue } if (neb in discoveryTime) { //ancestor lowest[node] = min(discoveryTime[neb]!!, lowest[node]!!) } else { dfs(neb) lowest[node] = min(lowest[neb]!!, lowest[node]!!) } } if (lowest[node] == discoveryTime[node]) { val sc = mutableListOf&lt;String&gt;() val neb = stack.pollLast()!! resolved.add(neb) sc.add(neb) if (neb == node) { strongComponents.add(sc) return } while (stack.size &gt; 0 &amp;&amp; stack.peekLast()!! != node) { val neb = stack.pollLast()!! resolved.add(neb) sc.add(neb) } if (stack.size &gt; 0 &amp;&amp; stack.peekLast()!! == node) { val neb = stack.pollLast() resolved.add(neb) sc.add(neb) } strongComponents.add(sc) } } for (node in allNodes) { if (node !in resolved) { dfs(node) } } return strongComponents } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:44:43.183", "Id": "465682", "Score": "0", "body": "It would be good, if you could extract the `dfs` function to outside of `getScc` function and give some context (either as text, comment and/or tests) to what the code should fulfill. I will be able to give a more detailed review then." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T02:00:43.717", "Id": "233615", "Score": "1", "Tags": [ "kotlin" ], "Title": "Strong components in kotlin" }
233615
<p>I recently solved <a href="https://adventofcode.com/2019/day/6" rel="nofollow noreferrer">Advent of Code 2019 Day 6</a> in C#.</p> <p><strong>Part 1:</strong></p> <blockquote> <p>You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the local orbits (your puzzle input).</p> <p>Except for the universal Center of Mass (COM), every object in space is in orbit around exactly one other object. An orbit looks roughly like this:</p> </blockquote> <pre><code> \ \ | | AAA--&gt; o o &lt;--BBB | | / / </code></pre> <blockquote> <p>In this diagram, the object BBB is in orbit around AAA. The path that BBB takes around AAA (drawn with lines) is only partly shown. In the map data, this orbital relationship is written AAA)BBB, which means "BBB is in orbit around AAA".</p> <p>Before you use your map data to plot a course, you need to make sure it wasn't corrupted during the download. To verify maps, the Universal Orbit Map facility uses orbit count checksums - the total number of direct orbits (like the one shown above) and indirect orbits.</p> <p>Whenever A orbits B and B orbits C, then A indirectly orbits C. This chain can be any number of objects long: if A orbits B, B orbits C, and C orbits D, then A indirectly orbits D.</p> <p>For example, suppose you have the following map:</p> </blockquote> <pre><code>COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L </code></pre> <blockquote> <p>Visually, the above map of orbits looks like this:</p> </blockquote> <pre><code> G - H J - K - L / / COM - B - C - D - E - F \ I </code></pre> <blockquote> <p>In this visual representation, when two objects are connected by a line, the one on the right directly orbits the one on the left.</p> <p>Here, we can count the total number of orbits as follows:</p> <p>D directly orbits C and indirectly orbits B and COM, a total of 3 orbits. L directly orbits K and indirectly orbits J, E, D, C, B, and COM, a total of 7 orbits. COM orbits nothing. The total number of direct and indirect orbits in this example is 42.</p> <p>What is the total number of direct and indirect orbits in your map data?</p> </blockquote> <p><strong>Part 2:</strong></p> <blockquote> <p>Now, you just need to figure out how many orbital transfers you (YOU) need to take to get to Santa (SAN).</p> <p>You start at the object YOU are orbiting; your destination is the object SAN is orbiting. An orbital transfer lets you move from any object to an object orbiting or orbited by that object.</p> <p>For example, suppose you have the following map:</p> </blockquote> <pre><code>COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN </code></pre> <blockquote> <p>Visually, the above map of orbits looks like this:</p> </blockquote> <pre><code> YOU / G - H J - K - L / / COM - B - C - D - E - F \ I - SAN </code></pre> <blockquote> <p>In this example, YOU are in orbit around K, and SAN is in orbit around I. To move from K to I, a minimum of 4 orbital transfers are required:</p> </blockquote> <pre><code>K to J J to E E to D D to I </code></pre> <blockquote> <p>Afterward, the map of orbits looks like this:</p> </blockquote> <pre><code> G - H J - K - L / / COM - B - C - D - E - F \ I - SAN \ YOU </code></pre> <blockquote> <p>What is the minimum number of orbital transfers required to move from the object YOU are orbiting to the object SAN is orbiting? (Between the objects they are orbiting - not between YOU and SAN.)</p> </blockquote> <hr> <p>I am fairly new to C# and coming from a C++ background and would like to learn how to improve writing more idiomatic and readable code. My approach to the problem is as follows:</p> <p>First I have been pasting the input to a text file each day and reading the input from <code>File</code>. In this case, I tokenize the inputs into a <code>List&lt;Tuple&lt;string, string&gt;&gt;</code> which I can then pass to my <code>OrbitalMapCalculator</code>. My <code>OrbitalMapCalculator</code> then creates a list of every single body that already has a count of how many direct and indirect orbits it has. Because each body keeps its own count of orbits, an orbiting body can simply increment the number of orbits of the body it orbits.</p> <p>For part one I then simply add the total orbits of all bodies.</p> <p>For part two I find the distance from "YOU" to center and from "SAN" to center. I then find the first common orbit. From there I find the two distances and add them together.</p> <p><strong>Here is the tokenizer:</strong></p> <pre><code>using System; using System.IO; using System.Collections.Generic; namespace AdventofCode2019 { class ProcessInput { internal List&lt;Tuple&lt;string, string&gt;&gt; GenerateOrbitalPairs(string textFile) { List&lt;Tuple&lt;string, string&gt;&gt; orbitalTokens = new List&lt;Tuple&lt;string, string&gt;&gt;(); if (File.Exists(textFile)) { string[] tokenPairs = File.ReadAllLines(textFile); foreach (string pair in tokenPairs) { string[] splitPair = pair.Split(')'); orbitalTokens.Add(new Tuple&lt;string, string&gt;(splitPair[0], splitPair[1])); } } return orbitalTokens; } } } </code></pre> <p><strong>The bulk of the work is done in the <code>OrbitalMapCalculator</code>:</strong></p> <pre><code>using System; using System.Collections.Generic; namespace AdventofCode2019 { internal class OrbitalMapCalculator { private class Node { public Node orbitingNode; public int numberOfOrbits; public string ID; public Node(string id) { orbitingNode = null; numberOfOrbits = 0; ID = id; } public Node(Node orbiting, string id) { orbitingNode = orbiting; numberOfOrbits = orbiting.numberOfOrbits + 1; ID = id; } } private List&lt;Node&gt; orbitalMap = new List&lt;Node&gt;(); public void ReadTokens(List&lt;Tuple&lt;string, string&gt;&gt; orbitalPairs) { string centerOfMass = "COM"; Node centerNode = new Node(centerOfMass); orbitalMap.Add(centerNode); Queue&lt;string&gt; centerNames = new Queue&lt;string&gt;(); centerNames.Enqueue(centerOfMass); while (centerNames.Count &gt; 0) { centerOfMass = centerNames.Dequeue(); foreach (Node node in orbitalMap) { if (node.ID == centerOfMass) { centerNode = node; break; } } foreach (Tuple&lt;string, string&gt; pair in orbitalPairs) { if (centerOfMass == pair.Item1) { orbitalMap.Add(new Node(centerNode, pair.Item2)); centerNames.Enqueue(pair.Item2); } } } } public int CountOrbits() { int orbits = 0; foreach (Node node in orbitalMap) { orbits += node.numberOfOrbits; } return orbits; } public int DistanceToSanta() { string yourID = "YOU"; string santasID = "SAN"; Node you = null; Node santa = null; foreach (Node node in orbitalMap) { if (node.ID == yourID) { you = node; } if (node.ID == santasID) { santa = node; } } List&lt;Node&gt; youToCenter = new List&lt;Node&gt;(); List&lt;Node&gt; santaToCenter = new List&lt;Node&gt;(); AddNodesTilCenter(you, youToCenter); AddNodesTilCenter(santa, santaToCenter); Node pivotNode = FindPivotNode(youToCenter, santaToCenter); int youToPivot = you.numberOfOrbits - pivotNode.numberOfOrbits - 1; int santaToPivot = santa.numberOfOrbits - pivotNode.numberOfOrbits - 1; return youToPivot + santaToPivot; } private void AddNodesTilCenter(Node sentinal, List&lt;Node&gt; nodes) { while (sentinal.orbitingNode != null) { nodes.Add(sentinal); sentinal = sentinal.orbitingNode; } } private Node FindPivotNode(List&lt;Node&gt; lhs, List&lt;Node&gt; rhs) { foreach (Node leftNode in lhs) { foreach (Node rightNode in rhs) { if (leftNode.ID == rightNode.ID) { return leftNode; } } } return null; } } } </code></pre> <p><strong>And finally the <code>Program.cs</code>:</strong></p> <pre><code>using System; using System.Collections.Generic; namespace AdventofCode2019 { class Program { static void Main(string[] args) { string inputFile = @"C:\AdventOfCode\AdventofCode2019\AdventofCode2019\Day6Input.txt"; ProcessInput processor = new ProcessInput(); OrbitalMapCalculator calculator = new OrbitalMapCalculator(); List&lt;Tuple&lt;string, string&gt;&gt; orbitalPairs = processor.GenerateOrbitalPairs(inputFile); calculator.ReadTokens(orbitalPairs); // Part One only int answer = calculator.CountOrbits(); // Part Two Only int answer = calculator.DistanceToSanta(); Console.WriteLine(answer); Console.ReadKey(); } } } </code></pre>
[]
[ { "body": "<p>Thank you for well-formed question :)</p>\n\n<p>I will write my review only regarding <code>ProcessInput</code> class for now, as overall review needs more time then I have at the moment ... </p>\n\n<ol>\n<li><p>Personally I don't like the method name <code>GenerateOrbitalPairs</code> as you do not generate anything, but rather read or parse. So i think <code>ReadOrbitalpairs</code> or <code>ParseOrbitalPairs</code> would be better.</p></li>\n<li><p>I think that you should not return empty <code>List</code> if file was not found. Empty list is expected result for empty file ! But for missed file I would say that <code>Exception</code> is expected. <code>System.IO.FileNotFoundException</code> which is raised by <code>File.ReadAllLines</code> in this case is fine.</p></li>\n<li><p><code>Tuple</code> is not the best option for public method to return, because it's not clear what it contains for another person (in this case for me) ... When I first saw this method I needed go inside it, read all inner code in order to understand what it does return. Method signature should be clear, so I would create a separate class like <code>OrbitPair \n{ \n public string OrbitFrom;\n public string OrbitTo;\n}</code></p>\n\n<p>Or at least used named <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/tuples\" rel=\"noreferrer\">Tuples</a></p></li>\n<li><p>Use LINQ instead of <code>for each</code> loop.\nUsually it makes code clearer and shorter. \nThat is what your code could look like</p>\n\n<pre><code>internal List&lt;(string OrbitFrom, string OrbitTo)&gt; GenerateOrbitalPairs(string textFile)\n{\n return File.ReadAllLines(textFile).Select(s =&gt; (OrbitFrom: s.Split(')')[0], OrbitTo: s.Split(')')[1])).ToList();\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T12:08:09.557", "Id": "233682", "ParentId": "233616", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T04:27:25.987", "Id": "233616", "Score": "6", "Tags": [ "c#", "programming-challenge" ], "Title": "Counting Direct and Indirect Orbits and Counting Distance of Orbits - Advent of Code Day 6" }
233616
<p>Basic idea is to use a Class, with static methods to add and remove references in a static vector, that keeps track of these references, and check that vector upon exit.</p> <p>The class is detecting intentional leaks that I create, but maybe you can find a case where it does not detect the leak, that I am not seeing</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdexcept&gt; #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; // for REM_LEAKt #include &lt;algorithm&gt; // for std::remove void checkLeakStack(); class LeakDbg { private: LeakDbg() { /// Constructor will only be called once, /// since it's a singlton class std::atexit( checkLeakStack ); } public: struct Pair { std::string name; void* ref; bool operator==( const Pair &amp;other ) const { return ref == other.ref; } }; static bool locked; static std::vector&lt;Pair&gt; stack; static LeakDbg&amp; instance() { static LeakDbg INSTANCE; return INSTANCE; } static void addRef(const std::string&amp; nm, void* ptr) { stack.push_back(Pair{ nm, ptr }); } static void remRef(void* ptr) { /// If it's not enabled, it means /// it's OK to remove a ref if( !LeakDbg::locked ){ Pair search = Pair{"",ptr}; std::vector&lt;Pair&gt; vect; // std::remove(vect.begin(), vect.end(), search); stack.erase(std::remove(stack.begin(), stack.end(), search), stack.end()); } } }; bool LeakDbg::locked = false; std::vector&lt;LeakDbg::Pair&gt; LeakDbg::stack = std::vector&lt;LeakDbg::Pair&gt;(); void checkLeakStack() { /// Here the stack should be emoty /// you can print or assert if the stack is not empty std::cout &lt;&lt; "There are " &lt;&lt; LeakDbg::stack.size() &lt;&lt; " leaks ..." "\n"; for ( LeakDbg::Pair pair : LeakDbg::stack) { const std::string msg = pair.name + " is leaked"; std::cout &lt;&lt; msg &lt;&lt; std::endl; } } </code></pre> <p>Add defines</p> <pre><code>#define ADD_LEAK(msg, ptr) LeakDbg::addRef(msg, ptr); #define REM_LEAK(ptr) LeakDbg::remRef(ptr); #define CREATE_LEAK_DET() LeakDbg::instance(); #define LCK_LEAK_DET(st) LeakDbg::locked = st; // ADD_LEAK -&gt; Add it in a class constructor // REM_LEAK -&gt; Add it in a class destructor // CREATE_LEAK_DET -&gt; Call it once to make sure "std::atexit" is called // LCK_LEAK_DET -&gt; If set to "true", all objects destructed after, // -&gt; will be considered a leak </code></pre> <p>Test</p> <pre><code>struct Test { Test() { ADD_LEAK( "Cls", this ) } ~Test() { REM_LEAK( this ) } }; int main() { CREATE_LEAK_DET() Test *obj1 = new Test(); Test *obj2 = new Test(); Test *obj3 = new Test(); delete obj2; LCK_LEAK_DET( true ) } </code></pre> <p><strong>Update 12/12/2019</strong> If anybody is interested, I refactored the code to be reusable and less intrusive. <a href="https://github.com/Berrima/LeakDetector" rel="nofollow noreferrer">Github</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:26:10.353", "Id": "456734", "Score": "2", "body": "The code is working, I just forgot the headers, fixed now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:27:05.433", "Id": "456738", "Score": "3", "body": "Better! I think it's ready for review now. Thank you." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Use the required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> which means that it should <code>#include &lt;string&gt;</code>. It might compile on your machine because some other header includes that file, but you can't count on that, and it could change with the next compiler update.</p>\n\n<h2>Use only necessary <code>#include</code>s</h2>\n\n<p>The <code>#include &lt;stdexcept&gt;</code> and <code>#include &lt;memory&gt;</code> lines are not necessary and can be safely removed because nothing from those headers appears to be used here.</p>\n\n<h2>Avoid C-style macros</h2>\n\n<p>I'd advise not using C-style macros like the ones in this code, preferring either inline functions or even lambdas. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-macros2\" rel=\"noreferrer\">ES.31</a> for details.</p>\n\n<h2>Consider thread safety</h2>\n\n<p>If multiple threads are using this code, there is likely to be a problem because the single shared instance of the <code>std::vector</code> is not protected by a mutex. I would also recommend renaming the existing <code>locked</code> variable to something like <code>complete</code> or <code>finished</code> to better distinguish what it's doing.</p>\n\n<h2>Avoid singletons</h2>\n\n<p>A singleton is basically just another way to create global variables, and we don't like global variables much because they make code linkages much harder to see and understand. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-singleton\" rel=\"noreferrer\">I.3</a> for more on that. In this case, since you already have two global variables, much of the complexity can easily be avoided by simply using a namespace instead of a class. Here's one way to do that which eliminates the need for <code>instance</code> and <code>CREATE_LEAK_DET</code>:</p>\n\n<pre><code>namespace LeakDbg\n{\n struct Pair\n {\n std::string name;\n void* ref;\n bool operator==( const Pair &amp;other ) const { return ref == other.ref; }\n\n };\n static bool locked = false;\n static std::vector&lt;Pair&gt; stack;\n\n static void addRef(const std::string&amp; nm, void* ptr)\n {\n stack.emplace_back(Pair{ nm, ptr });\n }\n static void remRef(void* ptr)\n {\n if( !LeakDbg::locked ){\n stack.erase(std::remove(stack.begin(), stack.end(), Pair{\"\",ptr}), stack.end());\n }\n }\n void checkLeakStack()\n {\n std::cout &lt;&lt; \"There are \" &lt;&lt; LeakDbg::stack.size() &lt;&lt; \" leaks ...\" \"\\n\";\n for ( LeakDbg::Pair pair : LeakDbg::stack) {\n std::cout &lt;&lt; pair.name &lt;&lt; \" is leaked\\n\";\n }\n }\n static const bool registered{std::atexit( checkLeakStack ) == 0};\n}\n</code></pre>\n\n<h2>Consider the user</h2>\n\n<p>The current code requires that the user explicitly instruments the code, which seems a bit intrusive. Here's an alternative approach the modifies things just slightly, using the <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"noreferrer\">Curiously Recurring Template Pattern</a>, or CRTP for short. First we isolate the leak detector bits into a templated class.</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct LeakDetector {\n LeakDetector() {\n LeakDbg::addRef(typeid(T).name(), this);\n }\n ~LeakDetector() {\n LeakDbg::remRef(this);\n }\n};\n</code></pre>\n\n<p>Now to use it is much simpler than before. No ugly macros are required and we only need to add one simple thing to the declaration of the class to be monitored:</p>\n\n<pre><code>struct Test : public LeakDetector&lt;Test&gt; \n{\n Test() {\n }\n ~Test() {\n }\n};\n</code></pre>\n\n<p>An even less intrusive approach might be to override <code>new</code> and <code>delete</code> as outlined in <a href=\"https://stackoverflow.com/questions/438515/how-to-track-memory-allocations-in-c-especially-new-delete\">this question</a>.</p>\n\n<h2>Consider alternatives</h2>\n\n<p>Leak detection is a worthwhile thing to do, since many C++ bugs stem from that kind of error. However, there are already a number of existing approaches to this, some of which may already be installed on your computer. There is, for example the useful <a href=\"https://valgrind.org/\" rel=\"noreferrer\"><code>valgrind</code></a> tool. If you're using <code>clang</code> or <code>gcc</code> and have the <a href=\"https://github.com/google/sanitizers/wiki/AddressSanitizer\" rel=\"noreferrer\"><code>libasan</code></a> library installed, you can get a very nice runtime printout. Just compile the code with</p>\n\n<pre><code>g++ -g -fsanitize=address myprogram.cpp -o myprogram\n</code></pre>\n\n<p>Then at runtime, a memory leak report might look like this:</p>\n\n<pre>There are 2 leaks ...\nCls is leaked\nCls is leaked\n\n=================================================================\n<b>==71254==ERROR: LeakSanitizer: detected memory leaks</b>\n\n<b>Direct leak of 1 byte(s) in 1 object(s) allocated from:</b>\n #0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)\n #1 0x4057a6 in main /home/edward/test/memleak/src/main.cpp:97\n #2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)\n\n<b>Direct leak of 1 byte(s) in 1 object(s) allocated from:</b>\n #0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)\n #1 0x405774 in main /home/edward/test/memleak/src/main.cpp:95\n #2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)\n\nSUMMARY: AddressSanitizer: 2 byte(s) leaked in 2 allocation(s).\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:36:05.360", "Id": "456759", "Score": "0", "body": "Thanks for the input, I am developing a GUI, and valgrind makes the interaction really slow, time to change my PC I guess. And the reason I used macros, is to be able to separate debug from release. I guess I will go with inheritance since it's less intrusive" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:39:06.650", "Id": "456760", "Score": "1", "body": "While valgrind does indeed slow things down, the address sanitizer has a lot less runtime impact in my experience. You might try that if you're using a compiler that supports it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:17:31.847", "Id": "456764", "Score": "0", "body": "I will give google/sanitizers a try" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T23:00:14.570", "Id": "456788", "Score": "2", "body": "Although they can be expensive to record, don't underestimate the value of those callstacks: knowing not just that two \"operator new(unsigned long)\" leaked somewhere in the entire execution but precisely which objects they are is often the difference between an exhaustive slog through the code and swooping directly onto the root cause." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:01:55.277", "Id": "456832", "Score": "0", "body": "`inline` is no use for functions nowadays. Just write normal functions and let compiler do optimizations. Also, templates are somewhat close to macros too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:04:57.003", "Id": "456833", "Score": "0", "body": "Also, wouldn't your constructor/destructor idea fail if object is copied or moved?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:50:57.993", "Id": "457428", "Score": "0", "body": "I updated the question with a link to a GitHub with a better and refactored code" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:02:32.743", "Id": "233637", "ParentId": "233625", "Score": "10" } }, { "body": "<p>Seems to be broken:</p>\n\n<pre><code>int main()\n{\n CREATE_LEAK_DET()\n Test obj4;\n Test obj5(obj4);\n LCK_LEAK_DET( true )\n}\n</code></pre>\n\n<p>Now compile and run:</p>\n\n<pre><code>&gt; g++ -std=c++14 ty.cpp\n&gt; ./a.out\nThere are 1 leaks ...\nCls is leaked\n&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:17:17.087", "Id": "456763", "Score": "0", "body": "Yep, you can't forget copy constructors. If I also push the ref to the copy constructor it solves it. But are there other cases the code misses." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:40:48.743", "Id": "233640", "ParentId": "233625", "Score": "2" } } ]
{ "AcceptedAnswerId": "233637", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:04:24.443", "Id": "233625", "Score": "8", "Tags": [ "c++", "memory-management" ], "Title": "Leak detection simple class" }
233625
<p>I have a sample list which contains nodes and their neighbors, if they have any. The task is to find the node which have the highest number of neighbors.</p> <pre><code>neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']] </code></pre> <p>The input is undirected. Meaning that <code>['A', 'B']</code> are neighbors. While <code>['A']</code> doesn't have any neighbors since it has no other value within its own list. If a sublist has 2 elements, then they are neighbors. Otherwise they are not neighbors.</p> <p>My solution is below, it has a lot of if-else statements. Is there a more elegant way to solve this?</p> <pre><code>def find_neighbors(neigh): d = {} for i in neigh: if i: if len(i)==2: if i[0] in d.keys(): d[i[0]] +=1.0 else: d[i[0]] = 1.0 if i[1] in d.keys(): d[i[1]] +=1.0 else: d[i[1]] = 1.0 max = 0 for i,j in d.items(): if j &gt; max: max = j return [i for i, j in d.items() if j == max] find_neighbors(neigh) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T04:52:51.857", "Id": "456728", "Score": "1", "body": "I am a little confused with your example where `A` doesn't have any neighbors, yet `['A', 'B']` are neighbors to each other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T06:20:04.203", "Id": "456729", "Score": "1", "body": "I agree with the other @Alexander that this is still quite unclear, I have flagged the post as such. Why are you using floats to count the number of neighbours? Are you expecting some nodes to have 0.5 neighbours?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T20:11:27.897", "Id": "456767", "Score": "0", "body": "I agree with both Alexander's comment, the definition of `neigh` is ambiguous, does `neigh = [['A'], ['A','B']]` mean that `B` has a neighbor and `A` has not? You might post a better defined _code review request_ to code review (and delete this one)." } ]
[ { "body": "<p>This checks if there is a neighbor of an element and if so, adds it to the count. </p>\n\n<pre><code>import operator \ndef find_max_letter_in_array(neighborhood):\n all_neighbors_with_count = {}\n for neighbor_set in [pair_of_neighbors for pair_of_neighbors in neighborhood if len(pair_of_neighbors) &gt; 1]:\n for neighbor in neighbor_set:\n all_neighbors_with_count.update({neighbor[0]: 1 if neighbor[0] not in all_neighbors_with_count else all_neighbors_with_count[neighbor[0]]+ 1})\n\n #return all_neighbors_with_count\n return max(all_neighbors_with_count.items(), key=operator.itemgetter(1))[0]\n\n\nneigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]\nprint(find_max_letter_in_array(neigh))\n\noutput: \n#{'A': 3, 'B': 2, 'C': 2, 'D': 1}\nA\n</code></pre>\n\n<ol>\n<li>You can loop over lists with conditions in them so that you only iterate over items you actually need </li>\n</ol>\n\n<pre><code>for each_element in [element for element in list if len(element) &gt; 1]:\n</code></pre>\n\n<ol start=\"2\">\n<li>Another important part is, you can use dict.update to do both insert and update. </li>\n<li>You can use the if statement while doing the assignment of a value as well</li>\n</ol>\n\n<pre><code>x = y if something_is_true else \n</code></pre>\n\n<ol start=\"4\">\n<li>At the end, using the operator.max, you can simply your code to get the max element key from dictionary based on all keys' values.</li>\n</ol>\n\n<p>Hope it helps in how you can compress your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:26:45.483", "Id": "456735", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:29:23.887", "Id": "456758", "Score": "0", "body": "Adding details to the suggestion of a compressed code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T05:08:21.073", "Id": "233628", "ParentId": "233626", "Score": "1" } }, { "body": "<p>For good programming we need to create and manipulate reusable code, so that every time when we are using list, tuple or dictionary, we can realize, Is it possible to use this for solving my another problem? And this is the good programming habit. \nFor example we are using a list of list for neighbors item, the list containing neighbors against a neighbor, so that we can simply split them and we can use it for count maximum neighbors also whenever time we need the compared list or neighbors list we can use it, so this program will be most shorter and in efficient way also re usable. \nAnother thing is that, it is the good example of one line looping and one line conditions. </p>\n\n<p>Try the following code to print all of the matched items:</p>\n\n<pre><code>neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]\nfirst_list = [str(item[0]) for item in neigh]\nsecond_list = [(len(item) - 1) for item in neigh]\n\nfor i in range(len(second_list)):\n if second_list[i] == max(second_list):\n neigh_max = first_list[i]\n print(neigh_max)\n</code></pre>\n\n<p>If you want to print just one time one item, you can use this:</p>\n\n<pre><code>neigh_max = first_list[second_list.index(max(second_list))]\n</code></pre>\n\n<p>Instead of using:</p>\n\n<pre><code>for i in range(len(second_list)):\n if second_list[i] == max(second_list):\n neigh_max = first_list[i]\n print(neigh_max)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T13:26:56.680", "Id": "456737", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T05:25:43.523", "Id": "233630", "ParentId": "233626", "Score": "0" } }, { "body": "<ol>\n<li>Use better variable names, <code>d</code>, <code>i</code> and <code>j</code> are quite poor.<br>\nDon't overwrite bultins, <code>max</code> is already defined.</li>\n<li><p>You can use <code>max</code> rather than have your own loop.</p>\n\n<pre><code>max_neighbours = max(d.values())\n</code></pre></li>\n<li><p>You don't need to use <code>in d.keys()</code>, <code>in d</code> works just fine.</p></li>\n<li><p>You can use <code>collections.defaultdict</code> rather than a <code>dict</code> for <code>d</code> so that you don't need the <code>if i[0] in d.keys()</code>.</p>\n\n<pre><code>d = collections.defaultdict(int)\nfor i in neigh:\n if len(i) == 2:\n d[i[0]] += 1\n d[i[1]] += 1\n</code></pre></li>\n<li><p>You can use <code>itertools.chain.from_iterable</code> along with a small comprehension to remove the need to specify <code>d[i[...]] += 1</code> twice.</p>\n\n<pre><code>neighbours = (\n nodes\n for nodes in neigh\n if len(nodes) == 2\n)\nfor node in itertools.chain.from_iterable(neighbours):\n d[node] += 1\n</code></pre></li>\n<li><p>You can use <code>collections.Counter</code> to count the neighbours for you.</p>\n\n<pre><code>d = collections.Counter(itertools.chain.from_iterable(neighbours))\n</code></pre></li>\n</ol>\n\n<p>All together this can get:</p>\n\n<pre><code>import collections\nimport itertools\n\n\ndef find_neighbors(neigh):\n neighbours = collections.Counter(itertools.chain.from_iterable(\n nodes\n for nodes in neigh\n if len(nodes) == 2\n ))\n max_neighbours = max(neighbours.values())\n return [\n node\n for node, count in neighbours.items()\n if count == max_neighbours\n ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:54:04.533", "Id": "233635", "ParentId": "233626", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T04:31:21.257", "Id": "233626", "Score": "3", "Tags": [ "python" ], "Title": "Finding the elements with the most neighbors" }
233626
<p>My VBA code currently loops for 5,000 iterations and takes about 25 minutes to collect the output data in the Output excel sheet. Is there a way to reduce the time taken for instance by improving the copying and pasting of values, collecting the output data in some kind of array etc.? Given that I will be looping it for up to 10,000 iterations when I obtain more data</p> <p>Note: The calculations are excel formulas within the Calcs excel sheet, as this is a cash flow schedule with irregular cash flows and discount rates, hence I am unable to automate the cash flow calculations via VBA.</p> <pre><code>Sub x() Dim r As Long Dim lastrow As Long Application.ScreenUpdating = False Application.CutCopyMode = False With Worksheets("MCInput") lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row MsgBox lastrow - 1 &amp; " Trials" End With With Worksheets("Calcs") For r = 0 To (lastrow - 2) .Range("CASHINPUT").Value = Worksheets("MCInput").Range("TCASHRTN").Offset(r).Value .Range("EQINPUT").Value = Worksheets("MCInput").Range("TEQRTN").Offset(r).Value .Range("FIINPUT").Value = Worksheets("MCInput").Range("TFIRTN").Offset(r).Value .Range("Results").Calculate .Range("Results").Copy Worksheets("Output").Range("A1").Offset(1 + r, 1).PasteSpecial xlPasteValues Next r End With Application.ScreenUpdating = True Application.CutCopyMode = True End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:31:00.830", "Id": "456746", "Score": "1", "body": "You mention this is a cash flow schedule, can you add a little more detail about that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:14:37.873", "Id": "456762", "Score": "1", "body": "You've an `End Sub` but no `(Public | Private) Sub FooBar()` to start it. I'm assuming it goes above your variable declarations, but that could be incorrect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T00:04:29.053", "Id": "456790", "Score": "0", "body": "What's the `Results` range calculating and why does it need to be calculated by Excel, as opposed to being computed by VBA code? If that calculation doesn't need to happen on the worksheet, then you can collect the inputs, perform all calculations, and dump all results at once, with 1 single worksheet read and 1 single worksheet write." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T01:20:46.043", "Id": "456798", "Score": "0", "body": "Thanks @IvenBach, I have edited the code to include 'Sub x()'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T01:26:05.840", "Id": "456800", "Score": "0", "body": "@pacmaninbw it is a cash flow schedule with irregular inflows and outflows over a period of 30 years and irregular discount rates for each year. At the end of each year, I will need to calculate the IRR for cashflows of all preceding years. Thereafter, I will check against an arbitrary target return and if the IRR falls below target, a loan is required to top-up the cash flow, and the cumulative loan also has its own set of payback period. So it is rather challenging for me to do the calculations in VBA, especially for a new VBA user like myself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T04:36:41.670", "Id": "456803", "Score": "2", "body": "Is it really called `x` though? You see naming is one of the hardest things in programming: giving a meaningful name to a procedure that does too many things can even be impossible! Typically, procedure names start with a verb, and describe the purpose or side effects of the procedure... anyway it would be nice to have the formula for the `Results` range, and enough context to be able to determine whether a formula whose result is copied and then pasted, is the most efficient way to go about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T08:51:53.990", "Id": "456820", "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." } ]
[ { "body": "<p>Use descriptive variable names. <code>r</code> as a variable name tells you nothing and makes your code harder to read. <code>rowOffset</code> tells you what it's used for. This goes a long way to make your code readable.</p>\n\n<p>Declare your variables just before you use them. You only have 2 currently but its easy for variables to increase. Instead of having a wall of declarations at the top of a Function/Sub, like below:</p>\n\n<pre><code>dim r as long\nDim i as long\ndim p as range\ndim sv as range\n\n</code></pre>\n\n<p>Have them declared just before they get used.</p>\n\n<pre><code>dim lastRow as long\nlastRow = Worksheets(\"MCInput\").Cells(Rows.Count,\"B\").End(xlUp).Row\n\ndim rowOffset as long\nFor rowOffset = 0 to (lastRow - 2)\n `Code that does what you want\nNext\n</code></pre>\n\n<p>This ultimately aids you in refactoring (restructuring) your code when you need to. It also becomes easier to tell when a variable is no longer needed. No code using the variable just after it's declared? Delete it. With a wall of declarations you have to laboriously check for usage. There are tools like <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a>, which I'm a contributor to, than can tell you if a variable is used.</p>\n\n<hr>\n\n<p>You're using a string literal populated with a worksheets name to access the worksheet through the hidden Global object's Worksheets property IE <code>Global.Worksheets(\"Calcs\")</code>. This returns an <code>Object</code> variable which is late-bound and doesn't give you intellisense when you use <code>.</code> (period) after the collection. It's preferred to use the Worksheet.CodeName. You can see this in the Project Explorer window. The CodeName of the worksheet is <code>Sheet1</code> while the Name (What is shown in the tab) is <code>Calcs</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/KkkrZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KkkrZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Sheet1 isn't a helpful name, this ties into using descriptive names above, so we'll change it by double clicking on it in the Project Explorer to display the code behind for the worksheet, then pressing F4 to display the Properties Window (also found under the menu at the top View>Properties. At the top where it says (Name) change it to something more descriptive.</p>\n\n<p><a href=\"https://i.stack.imgur.com/YJY46.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YJY46.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now instead of using <code>Worksheets(\"Calcs\")</code> use <code>CalculationSheet</code> to access the worksheet object. The same thing can be done to. Two added benefits:</p>\n\n<ul>\n<li>You're no longer dependent on the literal string \"Calcs\" which stops working if the worksheet is renamed.</li>\n<li>You get intellisense. Type <code>CalculationSheet.</code> (note the period) to show a list of accessible members.</li>\n</ul>\n\n<hr>\n\n<p>There's more that can and probably should be done with your code. Things like worksheet properties would help to clean up and shorten the code which then leads to the realization you'd benefit from <a href=\"https://rubberduckvba.wordpress.com/2017/12/08/there-is-no-worksheet/\" rel=\"nofollow noreferrer\">creating a proxy</a> for accessing your data. I was nerd-sniped by this already and that can be for another review.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T06:11:01.350", "Id": "233661", "ParentId": "233633", "Score": "3" } }, { "body": "<p>Thanks, guys. I got the answer on another forum. I made it store the calculated data outputs in an array before performing a one-time dump into another excel sheet. This halved my time taken to run the loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T14:59:28.253", "Id": "235232", "ParentId": "233633", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:17:50.137", "Id": "233633", "Score": "1", "Tags": [ "performance", "vba", "excel", "iteration" ], "Title": "Reduce time taken for VBA loop when copying multiple sets of input values, performing Excel formula calculations and recording results" }
233633
<p>I am an old python newbie here, migrating from fortran77 ;) Still unsure of the python terminology at the moment :(</p> <p>The python3 script below fetches a large list of matching files in a folder tree, in the format:</p> <pre><code>[ fully_qualified_folder_name, [list of matching files in this folder] ] </code></pre> <p>Being only a python newbie, there HAS to be a better way ?</p> <p>I hope to use the code to generate a nightly json file underpinning a chromecasting web server on a Raspberry Pi 4, based on Google's example chrome (web page) "sender". The web page will eventually use javascript on the client-side for the user to choose a file from a list and "cast" it from the Pi4's apache2 web server over to the chromecast device. So, I thought, why not give try Python a try ?</p> <p>Suggestions would be appreciated.</p> <pre><code>import os import fnmatch def yield_files_with_extensions(folder_path, file_match): for root, dirs, files in os.walk(folder_path): for file in files: if fnmatch.fnmatch(file.lower(),file_match.lower()): #yield os.path.join(root, file) yield file break # without this line it traverses the subfolders too def yield_files_in_subfolders(folder_path, file_match): for root, dirs, files in os.walk(folder_path): for d in dirs: subfolder = os.path.join(root, d) mp4_files = [subfolder, [f for f in yield_files_with_extensions(subfolder, file_match)]] yield mp4_files # the_path = r'/mnt/mp4library/mp4library' # retieve the topmost folder's files mp4_files1 = [[ the_path, [f for f in yield_files_with_extensions(the_path, "*.mp4")] ]] mp4_files2 = [f for f in yield_files_in_subfolders(the_path, "*.mp4")] mp4_files2 = mp4_files1 + mp4_files2 crecords=0 cfiles=0 for a in mp4_files2: crecords=crecords+1 print ("-----record "+str(crecords)+"---" + a[0] + " ... files=" + str(len(a[1]))) #print (a[0]) #print (a[1]) c=0 for b in a[1]: c=c+1 print ("mp4 File "+str(c)+"---" + b) cfiles=cfiles+c print ('Count of files: ' + str(cfiles)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T15:42:35.603", "Id": "456751", "Score": "3", "body": "Please can you explain what this code does. Currently your description just says \"doesn't work\" multiple times over - which makes this question off-topic as the code doesn't work the way you intend it to. If it's true that it doesn't work, then we can't help you until you get it working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T16:00:04.377", "Id": "456752", "Score": "0", "body": "OK. Sorry. Perhaps in the other thread, however here the code does work. \n\nIt walks a nominated folder root and fetches a large list of matching filenames in the folder/subfolder tree, in the format:\n`[ fully_qualified_folder_name, [list of matching files in this folder] ]`\n\nTo clarify: \nIs there a better way to achioeve it ? \nIs there a way for os.walk to return stuff in alphabetical order ? \nGiven these are .mp4 files, is there any way to determine the file size,duration,resolution of each file so I can add it to the list ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T16:06:38.853", "Id": "456753", "Score": "2", "body": "Given that you've asked in the question, and the comments, ways to change your code to perform actions it currently doesn't seem to do I'm voting to close this as off-topic. We aren't a code writing service, you need to figure out how to sort and extract MP4 data by yourself or through a different service." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T16:10:23.397", "Id": "456754", "Score": "2", "body": "OK. I did ask if there was a better way though (a review question)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T16:13:12.357", "Id": "456755", "Score": "2", "body": "Yes, and you've asked off-topic things too. Maybe you can edit your post to make it only ask on-topic things?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T22:29:49.003", "Id": "456782", "Score": "0", "body": "OK. Removed 2 questions: I noticed that the folders are returned unsorted, is there a way to fix that without sorting myself ?\nGiven these are .mp4 files, is there any way to determine the file size,duration,resolution of each file ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T22:53:31.093", "Id": "456785", "Score": "0", "body": "I would also suggest updating the title to be more precise and succinct (e.g. removing \"a better way?\", as that is a question that everyone here asks implicitly when requesting a code review). Maybe something like \"Find all files that match a filename pattern in a folder tree.\"" } ]
[ { "body": "<p>As you tagged this Python 3.x, I'd suggest using <a href=\"https://docs.python.org/3.7/library/pathlib.html?highlight=rglob#pathlib.Path.rglob\" rel=\"nofollow noreferrer\"><code>pathlib.Path.rglob()</code></a> and <a href=\"https://docs.python.org/3.7/library/collections.html?highlight=defaultdict#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>. Also, check out <a href=\"https://docs.python.org/3.7/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a>.</p>\n\n<pre><code>import collections\nimport pathlib\n\nmp4s = collections.defaultdict(list)\n\nroot = pathlib.Path(r'/mnt/mp4library/mp4library')\n\nfile_count = 0\n\nfor filepath in root.rglob('*.mp4'):\n #filepath is relative to root. Uncomment the next line for absolute paths\n #filepath = filepath.resolve()\n\n mp4s[filepath.parent].append(filepath.name)\n\n file_count += 1\n\nfor record_number, (folder, filenames) in enumerate(sorted(mp4s.items())):\n\n print(f\"-----record {record_number}---{folder} ... files={len(filenames)}\")\n\n for c,filename in enumerate(filenames):\n print(f\"mp4 File {c}---filename\")\n\nprint('Count of files: {filecount}')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T03:36:59.193", "Id": "456801", "Score": "0", "body": "Thanks ! I'll look into these." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:43:55.690", "Id": "456861", "Score": "0", "body": "This answer doesn't really review the code but just presents an alternative solution. Please, see: [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/q/8403/154946) and [What IS a Code Review?](https://codereview.meta.stackexchange.com/q/5407/154946)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T02:28:57.697", "Id": "456970", "Score": "1", "body": "thank you, i reviewed it and discovered case sensitivity was an issue for me, so had to use '*.[mM][pP]4'" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T03:12:03.917", "Id": "233654", "ParentId": "233634", "Score": "6" } }, { "body": "<ul>\n<li><p>A dictionary is the more appropriate data structure to use here, since your code is essentially building a mapping from directory paths to lists of matched filenames. That is, instead of building a <code>List[List[Union[str, List[str]]]]</code>, build a <code>Dict[str, List[str]]</code>.</p></li>\n<li><p>A single call to <code>os.walk</code> is sufficient to perform the job that <code>yield_files_in_subfolders</code> and <code>yield_files_with_extensions</code> are currently doing together. For each 3-tuple <code>(root, dirs, files)</code>, <code>root</code> is the containing directory and <code>files</code> is a list of non-directory files that reside directly under <code>root</code>.</p></li>\n<li><p>Do note that if we want each <code>root</code> directory (as mentioned above) to be an absolute path, we need to pass in an absolute path to <code>os.walk</code>. Calling <code>os.path.abspath</code> on the input directory path ensures this.</p></li>\n<li><p>To make the script easier to use and test, I'd recommend reading in the target (top-level) directory and the filename extension as command-line arguments. We can do this with <code>argparse</code> or <code>sys.argv</code>.</p></li>\n</ul>\n\n<p>Here is the script with the above suggestions implemented:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport os\nimport fnmatch\nimport argparse\nfrom collections import defaultdict\n\ndef find_matching_files(directory, file_pattern):\n # directory could be a relative path, so transform it into an absolute path\n directory = os.path.abspath(directory)\n directory_to_matched_files = defaultdict(list)\n\n for root, _, files in os.walk(directory):\n for file in files:\n if fnmatch.fnmatch(file.lower(), file_pattern):\n directory_to_matched_files[root].append(file)\n\n return directory_to_matched_files\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('target_directory')\n parser.add_argument('-x', '--filename-extension', default='mp4')\n args = parser.parse_args()\n\n files = find_matching_files(args.target_directory,\n f'*.{args.filename_extension.lower()}')\n\n # print report of directories &amp; files\n # [...]\n</code></pre>\n\n<p>Sample invocation:</p>\n\n<pre><code>$ ./script.py /mnt/mp4library/mp4library -x mp4\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:47:28.527", "Id": "456830", "Score": "1", "body": "Thank you ! A nice example, as an os.walk alternative implementation to rglob. I see argparse would also be useful in my use case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:49:30.930", "Id": "456839", "Score": "0", "body": "@RolandIllig You're right, just fixed it. Thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T04:55:07.603", "Id": "233658", "ParentId": "233634", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T14:53:02.043", "Id": "233634", "Score": "4", "Tags": [ "python", "python-3.x", "file-system" ], "Title": "Find all files that match a filename pattern in a folder tree" }
233634
<p>Just for fun, I created a script called TinyBF which can compress <a href="https://esolangs.org/wiki/Brainfuck" rel="noreferrer">Brainfuck</a> programs into a format half their size. For example, take a famous <a href="https://codegolf.stackexchange.com/a/68494/">hello world</a> program clocking in at 78 bytes:</p> <pre><code>--&lt;-&lt;&lt;+[+[&lt;+&gt;---&gt;-&gt;-&gt;-&lt;&lt;&lt;]&gt;]&lt;&lt;--.&lt;++++++.&lt;&lt;-..&lt;&lt;.&lt;+.&gt;&gt;.&gt;&gt;.&lt;&lt;&lt;.+++.&gt;&gt;.&gt;&gt;-.&lt;&lt;&lt;+. </code></pre> <p>When put into TinyBF format, it is only 39 bytes:</p> <pre><code>7#!00"7!'!7?,,,?#B!?.&gt;!$,.&gt;?!. </code></pre> <p>The steps for encoding are:</p> <ol> <li><p>Translate all characters in the input using the following dictionary: <code>{'&gt;': '2', '&lt;': '3', '+': '4', '-': '5', '.': '6', ',': '7', '[': '8', ']': '9'}</code>.</p></li> <li><p>Split the string into chunks of two characters each - pad the last item with a trailing zero if it is only one digit long.</p></li> <li><p>Make a string using the resultant charcodes of the previous list.</p></li> </ol> <p>Without further ado, here's the compress and decompress methods (<code>tinybf.py</code>):</p> <pre><code>def compress(code): """compress(code): Compress a string of Brainfuck code into TinyBF format.""" translated = code.translate({62: 50, 60: 51, 43: 52, 45: 53, 46: 54, 44: 55, 91: 56, 93: 57}) return "".join(chr(int(translated[pos:pos + 2].ljust(2, "0"))) for pos in range(0, len(translated), 2)) def decompress(code): """decompress(code): Decompress a string of TinyBF code into Brainfuck format.""" translated = "".join(str(ord(c)) for c in code).translate({50: 62, 51: 60, 52: 43, 53: 45, 54: 46, 55: 44, 56: 91, 57: 93}) return translated.rstrip("0") </code></pre> <p>And here's the script/output I used to test it:</p> <pre><code>import tinybf original_code = "--&lt;-&lt;&lt;+[+[&lt;+&gt;---&gt;-&gt;-&gt;-&lt;&lt;&lt;]&gt;]&lt;&lt;--.&lt;++++++.&lt;&lt;-..&lt;&lt;.&lt;+.&gt;&gt;.&gt;&gt;.&lt;&lt;&lt;.+++.&gt;&gt;.&gt;&gt;-.&lt;&lt;&lt;+." compressed_code = tinybf.compress(original_code) print(compressed_code) # 7#!00"7!'!7?,,,?#B!?.&gt;!$,.&gt;?!. print(len(original_code), len(compressed_code)) # 78 39 new_code = tinybf.decompress(compressed_code) print(new_code == original_code) # True </code></pre> <p>Any advice on the code or improvements I could make? I'm also looking for name advice if possible - I settld on TinyBF for this question, but I also considered Braincrunch and Tinyfuck, so if you have thoughts on those, that'd be great.</p>
[]
[ { "body": "<p>Since you seem to want code golf over readable code this may not be the answer you want. All the suggestions I make are things I would prefer, but I don't think it's that uncommon for others to disagree. The outcome either way is still pretty ugly.</p>\n\n<ul>\n<li>Your code isn't PEP 8 compliant, and is generally pretty hard to read.</li>\n<li><p>Your one-line docstrings are quite poor, docstring wise. Contrast with:</p>\n\n<blockquote>\n<pre><code>\"\"\"Compress Brainfuck code to TinyBF\"\"\"\n</code></pre>\n</blockquote></li>\n<li><p>Use <code>str.maketrans</code> rather than manually make the translation table.</p>\n\n<pre><code>COMPRESS_TABLE = str.maketrans({'&gt;': '2', '&lt;': '3', '+': '4', '-': '5', '.': '6', ',': '7', '[': '8', ']': '9'})\n</code></pre>\n\n<p>Alturnately you can define both from a common string.</p>\n\n<pre><code>_COMPRESS_STR = '&gt;2 &lt;3 +4 -5 .6 ,7 [8 ]9'\nCOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR.split()))\nDECOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR[::-1].split()))\n</code></pre></li>\n<li>I would prefer <code>itertools.zip_longest</code> over manually zipping and justifying.</li>\n<li>You can split <code>decompress</code> over multiple lines to make the code more readable.</li>\n</ul>\n\n<pre><code>import itertools\n\n_COMPRESS_STR = '&gt;2 &lt;3 +4 -5 .6 ,7 [8 ]9'\nCOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR.split()))\nDECOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR[::-1].split()))\n\n\ndef compress(code: str) -&gt; str:\n \"\"\"Compress Brainfuck code into TinyBF\"\"\"\n return \"\".join(\n chr(int(a + b))\n for a, b in itertools.zip_longest(\n *2*[iter(code.translate(COMPRESS_TABLE))],\n fillvalue=\"0\",\n )\n )\n\n\ndef decompress(code: str) -&gt; str:\n \"\"\"Decompress TinyBF into Brainfuck\"\"\"\n return (\n \"\".join(str(ord(c)) for c in code)\n .translate(DECOMPRESS_TABLE)\n .rstrip(\"0\")\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:22:50.860", "Id": "233641", "ParentId": "233638", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T17:22:38.683", "Id": "233638", "Score": "8", "Tags": [ "python", "compression", "brainfuck" ], "Title": "Brainfuck compressor in Python" }
233638
<p>I am in the process of setting up WordPress with WooCommerce, one of the requirements is a bit of integration that takes a person from another website directly to a specific product. I have set the external product references in tags on the products.</p> <p>An example incoming query would be:</p> <p><a href="http://localhost/TestSite/search?q=9404" rel="nofollow noreferrer">http://localhost/TestSite/search?q=9404</a></p> <p>I have written a short plugin that does this.</p> <p>I am an average programmer, but very new to PHP, WordPress and WooCommerce. Can you see any potential errors, inefficencies or, security issues?</p> <p>Any insight would be gladly recieved. <pre><code> //Tag on Test Product: 98614 //example URL: //http://localhost/TestSite/search?q=98614 function TagLinker(){ if (isset($_GET['q'])) { $TagNumber = $_GET['q']; $params=array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'product_tag', 'field' =&gt; 'slug', 'terms' =&gt; $TagNumber ) )); $wc_query = new WP_Query($params); if ($wc_query -&gt; have_posts() ) { $wc_query -&gt; the_post(); $product_id = get_the_ID($wc_query-&gt;ID); $url = get_permalink( $product_id ); wp_reset_postdata(); if ( wp_redirect( $url ) ) {exit;} }; } } add_action( 'init', 'TagLinker' ); ?&gt; </code></pre>
[]
[ { "body": "<p>It's a good idea with frameworks to follow the method calls to see what you're actually doing, Wordpress is one of the most exploited frameworks out there and thus has fairly good security improvements. Here is the Wordpress WP_Query class you're invoking (assuming you have the latest code pulled). </p>\n\n<p>It looks like the __construct calls $this->query on your $params, which calls wp_parse_args(). (If you already have the code pulled, Grep can help finding where in the code the class lives).\n<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php</a></p>\n\n<p>As far as security is concerned, your primary concern would be with the user supplied data $_GET['q']. If you do not feel that the WP_Query class is doing enough to sanitize the user data you can sanitize it yourself.</p>\n\n<p>In your case, it looks like you only want the user to supply a integer? If that is the case you can filter. Adjust as necessary:</p>\n\n<pre><code>if (filter_var($_GET['q'], FILTER_VALIDATE_INT)) {\n // is int\n}\n</code></pre>\n\n<p>Additional tips:\nThere is no reason to set $_GET['q'] to $TagNumber in your example, since you're not sanitizing it. Doing so only increases memory usage and complicates code review.</p>\n\n<p>Be consistent about whether or not to clear between an if and \"{\". Most of the reason for clearing has to do with refactoring and applies mostly to class definitions.</p>\n\n<p>There is no need to ?> close the script, it can add unintended white space.</p>\n\n<p>Don't indent functions unless they are inside classes (looks to be intended for no reason).</p>\n\n<p>Pick a style for naming variables, e.g. snake_case; not $TagName and $params, but $tag_name and $params</p>\n\n<p>I hope this is helpful :-) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:44:24.010", "Id": "456829", "Score": "0", "body": "That is very helpful! Thank you for your comments :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T23:40:02.487", "Id": "233649", "ParentId": "233643", "Score": "1" } } ]
{ "AcceptedAnswerId": "233649", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T19:05:59.877", "Id": "233643", "Score": "4", "Tags": [ "php", "plugin", "wordpress" ], "Title": "Simple Bespoke WordPress Integration Plugin" }
233643
<p>I have a fair few years experience with programming, and am currently working in a software development role, writing internal web applications in C#.</p> <p>This is the first C++ code I have ever written, so I therefore don't know the conventions, code smells, do's/don't's of the language.</p> <p>I decided to write an extremely basic Rock, Paper, Scissors implementation using the command line.</p> <p>Please let me know if I can improve anything?</p> <p><strong><em>main.cpp</em></strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; using namespace std; enum Outcome { user, bot, draw }; string outcomeMap[3] = {"You win!", "Bot wins!", "It was a draw!"}; enum Choice { rock, paper, scissors }; string choiceMap[3] = {"rock", "paper", "scissors"}; Choice getUserChoice() { cout &lt;&lt; "Rock, paper or scissors? " &lt;&lt; endl; string input; getline(cin, input); if(input == "rock" || input == "ROCK" || input == "1" || input == "r" || input == "R") { return rock; } else if(input == "paper" || input == "PAPER" || input == "2" || input == "p" || input == "P") { return paper; } else if(input == "scissors" || input == "SCISSORS" || input == "3" || input == "s" || input == "S") { return scissors; } else { throw invalid_argument("You must choose rock, paper or scissors."); } } Choice getBotChoice() { auto randomNumber = rand() % 3 + 1; switch(randomNumber) { case 1: return rock; case 2: return paper; case 3: return scissors; default: throw invalid_argument("Random number was generated outside of the given range."); } } Outcome decideOutcomeOfGame(Choice userChoice, Choice botChoice) { if (userChoice == botChoice) { return draw; } else if (userChoice == rock &amp;&amp; botChoice == paper) { return bot; } else if (userChoice == rock &amp;&amp; botChoice == scissors) { return user; } else if (userChoice == paper &amp;&amp; botChoice == rock){ return user; } else if (userChoice == paper &amp;&amp; botChoice == scissors){ return bot; } else if (userChoice == scissors &amp;&amp; botChoice == rock){ return bot; } else if (userChoice == scissors &amp;&amp; botChoice == paper) { return user; } } bool shouldGameExit() { cout &lt;&lt; "Quit?" &lt;&lt; "\r\n"; string input; getline(cin, input); if(input == "no" || input == "NO" || input == "n" || input == "N" || input == "0") { return false; } else { return true; } } void gameLoop() { auto quit = false; while(!quit) { auto userChoice = getUserChoice(); auto botChoice = getBotChoice(); cout &lt;&lt; "You chose " &lt;&lt; choiceMap[userChoice] &lt;&lt; "\r\n"; cout &lt;&lt; "The bot chose " &lt;&lt; choiceMap[botChoice] &lt;&lt; "\r\n"; cout &lt;&lt; outcomeMap[decideOutcomeOfGame(userChoice, botChoice)] &lt;&lt; "\r\n"; quit = shouldGameExit(); } } int main() { gameLoop(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T21:08:44.970", "Id": "456771", "Score": "1", "body": "related: https://codereview.stackexchange.com/questions/213842/rock-paper-scissors-engine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:39:09.790", "Id": "457160", "Score": "1", "body": "Try to use arrays and loops instead of \"if this or this or this or this\", since you have a lot. Use either nested switches or conditionals for your decideOutcome logic, or maybe try a matrix (2D array) approach, e.g. 0 is rock, 1 paper, 2 scissors, then have a 2D lookup array with the index of the corresponding outcome as the values/elements in the array. Also yeah, use a do while loop and get rid of the useless quit variable." } ]
[ { "body": "<p>It's a good start! Here are some 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. Know when to use it and when not to (as when writing include headers). In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences. </p>\n\n<h2>Use <code>&lt;cstdlib&gt;</code> instead of <code>&lt;stdlib.h&gt;</code></h2>\n\n<p>The difference between the two forms is that the former defines things within the <code>std::</code> namespace versus into the global namespace. Language lawyers have lots of fun with this, but for daily use I'd recommend using <code>&lt;cstdlib&gt;</code>. See <a href=\"http://stackoverflow.com/questions/8734230/math-interface-vs-cmath-in-c/8734292#8734292\">this SO question</a> for details.</p>\n\n<h2>Use <code>for</code> loops rather than <code>while</code> loops where practical</h2>\n\n<p>Your <code>gameloop</code> routine can be simplified a bit by using a <code>for</code> loop rather than a <code>while</code> loop. here is the current code:</p>\n\n<pre><code>void gameLoop() {\n auto quit = false;\n while(!quit) {\n // other stuff\n quit = shouldGameExit();\n }\n}\n</code></pre>\n\n<p>I'd recommend writing it as a <code>for</code> loop to do several things. First, it changes the scope of the <code>quit</code> variable to solely within the loop. Second, it makes it clear how the exit condition is set:</p>\n\n<pre><code>void gameLoop() {\n for (auto quit = false; !quit; quit = shouldGameExit()) {\n // other stuff\n }\n}\n</code></pre>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Check return values and handle errors</h2>\n\n<p>The code calls <code>getline</code> but never checks for error return values. If <code>getline</code> encounters a problem, it sets the <code>failbit</code>. It's easy to check for this in C++, because of operator overloading. That is, one could do this:</p>\n\n<pre><code>getline(cin, input)\nif (cin) { // if getline was OK\n ///\n}\n</code></pre>\n\n<h2>Think of the user</h2>\n\n<p>Generally speaking, it's not unusual for users to type in faulty input. For that reason, I think I would not <code>throw</code> an exception from with <code>getUserChoice</code>. Instead of abruptly aborting the user out of the program, a friendlier way to do it would be to give the user a chance to correct the input. Here's one way to rewrite that function:</p>\n\n<pre><code>Choice getUserChoice() {\n Choice userchoice;\n for (auto valid{false}; !valid; ) {\n cout &lt;&lt; \"Rock, paper or scissors? \\n\";\n string input;\n getline(cin, input);\n if (cin) {\n if(input == \"rock\" || input == \"ROCK\" || input == \"1\" || input == \"r\" || input == \"R\") {\n valid = true;\n userchoice = rock;\n\n } else if(input == \"paper\" || input == \"PAPER\" || input == \"2\" || input == \"p\" || input == \"P\") {\n valid = true;\n userchoice = paper;\n } else if(input == \"scissors\" || input == \"SCISSORS\" || input == \"3\" || input == \"s\" || input == \"S\") {\n valid = true;\n userchoice = scissors;\n } else {\n cout &lt;&lt; \"Sorry, I didn't understand \\\"\" &lt;&lt; input &lt;&lt; \"\\\"\\n\";\n }\n }\n }\n return userchoice;\n}\n</code></pre>\n\n<p>Note that one could code a <code>return</code> instead of using the <code>userchoice</code> and <code>valid</code> variables, but I prefer having an easier-to-read program flow without having to hunt for <code>return</code> statements. You can decide for yourself which flavor you prefer.</p>\n\n<h2>Make sure all paths return a value</h2>\n\n<p>The <code>decideOutcomeOfGame</code> routine returns the outcome of the game. It's <em>probable</em> that all combinations are enumerated, but I'd prefer to make sure the function returns something every time. Here's how I'd write it.</p>\n\n<pre><code>Outcome decideOutcomeOfGame(Choice userChoice, Choice botChoice) {\n if (userChoice == botChoice) {\n return draw;\n } else if ((userChoice == rock &amp;&amp; botChoice == paper)\n || (userChoice == paper &amp;&amp; botChoice == scissors)\n || (userChoice == scissors &amp;&amp; botChoice == rock)) {\n return bot;\n }\n return user;\n}\n</code></pre>\n\n<h2>Consider using a better random number generator</h2>\n\n<p>You are currently using </p>\n\n<pre><code>auto randomNumber = rand() % 3 + 1;\n</code></pre>\n\n<p>Normally I recommend the use of the <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\">C++11 <code>std::uniform_int_distribution</code></a> to replace the old-style <code>rand()</code> but since you're using C++17, you could use <a href=\"https://en.cppreference.com/w/cpp/algorithm/sample\" rel=\"noreferrer\"><code>std::sample</code></a>. This reduces the <code>getBotChoice()</code> function to this:</p>\n\n<pre><code>Choice getBotChoice() {\n constexpr static std::array&lt;Choice,3&gt; choices{ rock, paper, scissors };\n static auto rnd{std::mt19937{std::random_device{}()}};\n std::vector&lt;Choice&gt; botChoice;\n std::sample(std::begin(choices), std::end(choices), std::back_inserter(botChoice), 1, rnd);\n return botChoice.front();\n}\n</code></pre>\n\n<p>There is now no need for the <code>throw</code> because the code will never generate an invalid return value.</p>\n\n<h2>Use <code>std::string_view</code> where practical</h2>\n\n<p>Rather than mutable strings, the global variables <code>outcomeMap</code> and <code>choiceMap</code> would be better expressed as a <code>std::array</code> of <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"noreferrer\"><code>std::string_view</code></a>. In other words, instead of this:</p>\n\n<pre><code>string outcomeMap[3] = {\"You win!\", \"Bot wins!\", \"It was a draw!\"};\n</code></pre>\n\n<p>Write this:</p>\n\n<pre><code>constexpr array&lt;string_view, 3&gt; outcomeMap{\"You win!\", \"Bot wins!\", \"It was a draw!\"};\n</code></pre>\n\n<h2>Consider encapsulating into a namespace</h2>\n\n<p>It doesn't seem as though these functions are going to be useful without each other. Because they're so closely related (and related as well to the data), I'd recommend consolidating everything into a <code>namespace</code>.</p>\n\n<h2>Understand <code>return 0</code> in main</h2>\n\n<p>When a C or C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so there is no need to put <code>return 0;</code> explicitly at the end of <code>main</code>. I advocate omitting it to reduce the clutter and let the compiler generate code; others prefer to write it explicitly. It's up to you to choose which style you prefer, but either way you should know about this compiler behavior.</p>\n\n<h2>Simplify your code</h2>\n\n<p>The code currently contains this construct:</p>\n\n<pre><code>if(input == \"no\" || input == \"NO\" || input == \"n\" || input == \"N\" || input == \"0\") {\n return false;\n } else {\n return true;\n }\n</code></pre>\n\n<p>As @Deduplicator correctly notes in a comment, better would be to simply return the value of the expression which is already <code>bool</code>:</p>\n\n<pre><code>return !(input == \"no\" || input == \"NO\" || input == \"n\" || input == \"N\" || input == \"0\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T21:32:53.933", "Id": "456776", "Score": "0", "body": "Thanks! Lots of C++ specific recommendations in this answer, which is *exactly* what I was looking for! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T22:05:52.507", "Id": "456779", "Score": "0", "body": "You might also want to peruse https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T01:20:25.553", "Id": "456797", "Score": "2", "body": "The input validation in various places can be simplified by half by normalizing the strings to either upper or lower case: `input = /*convert to lower case*/; if(input == \"rock\" || input == \"r\" || input == \"1\") { /*...*/ }` and `return input == \"no\" || input == \"n\" || input == \"0\";`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T01:24:16.713", "Id": "456799", "Score": "0", "body": "@Casey good point. Another way to do it is to use a `std::unordered_map` to easily translate from input to token." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T08:43:59.590", "Id": "456815", "Score": "0", "body": "Actually, your last refactoring inverts the condition. I'd advocate for extracting the whole condition into a function `isNo(const string_view& input)` and then `return !isNo(input)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T08:48:25.763", "Id": "456818", "Score": "0", "body": "Instead of \"hunt[ing] for [visible] return statements\", you end up hunting for visible assignments and invisible control flow paths. For instance, it's not immediately obvious whether any assignment you make to `userChoice` will make it to the `return` statement unchanged. That's why I'd advocate the exact opposite, for readability. JMHO" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:51:06.690", "Id": "456831", "Score": "0", "body": "I don't really like `shouldGameExit()` in the header of a for loop. A function call that entails I/O and interactivity shouldn't be hidden away at the end of a loop header IMO. To me this is a good enough reason to just use a while." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:21:34.850", "Id": "456835", "Score": "0", "body": "@LaurentLARIZZA I’ve fixed the inverted condition. Thanks. For the `return` issue, it’s a fair point; one could reasonably advocate either position. The problem with the original was that it wasn’t obvious that it always returned a value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T12:34:46.307", "Id": "456850", "Score": "0", "body": "I think `!(input == \"no\" || input == \"NO\" || input == \"n\" || input == \"N\" || input == \"0\")` == `input != \"no\" && input != \"NO\" && input != \"n\" && input != \"N\" && input != \"0\"`. I also **completely** disagree with the `for` loop and believe that should be a `do...while` loop, but that seems to be a matter of opinion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:19:15.433", "Id": "456888", "Score": "0", "body": "I think having an explicit `return 0` in `main` is better; it shows that your code executed correctly, and it's likely to be optimized out anyway if the compiler does insert code to do it. I think the main reason it was standardized was because people were causing undefined behavior by omitting the `return 0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:14:15.543", "Id": "457003", "Score": "0", "body": "The structuring for `decideOutcomeOfGame()` looks a bit mixed. I mean, the `else` in the second `if` block is unnecessary, as the first `if` block would `return`. Though if that `else` is included for stylistic reasons, then presumably the final catch-all case should also be wrapped in an `else`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:22:49.573", "Id": "457044", "Score": "2", "body": "Actually for the game loop, I'd not use for, but do while, which would completely get rid of the variable `quit`." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T20:39:33.043", "Id": "233646", "ParentId": "233644", "Score": "34" } }, { "body": "<p>In addition to Edward's answer.</p>\n<h2>Use <code>enum class</code> instead of <code>enum</code></h2>\n<pre><code>enum class Outcome { user, bot, draw };\nenum class Choice { rock, paper, scissors };\n</code></pre>\n<p>This does two things:</p>\n<ul>\n<li>Inject the names into the <code>enum class</code>, rather than into the surrounding namespace. (You then have to write <code>Outcome::user</code> instead of <code>user</code>, until C++20's <code>using enum</code> is available)</li>\n<li>Remove any implicit conversion to/from the underlying type.</li>\n</ul>\n<h3>A better random generation alternative</h3>\n<p>You want equiprobable numbers between 0 and 2 inclusive, to be able to get one of <code>Choice</code>s values. Improving on Edward's answer, this would be:</p>\n<pre><code>Choice getBotChoice() {\n constexpr static std::array&lt;Choice,3&gt; choices{ rock, paper, scissors };\n static auto rnd{std::mt19937{std::random_device{}()}};\n std::uniform_int_distribution&lt;int&gt; distribution(0,choices.size() - 1);\n return choices[distribution(rnd)];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:35:28.840", "Id": "456838", "Score": "0", "body": "While I also often suggest using `enum class`, in this case it seems to me that it’s better as a plain `enum` for brevity and clarity. Otherwise one would have to use a `static_cast` to use it as an array index." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:54:20.863", "Id": "456840", "Score": "0", "body": "@Edward : you've got an example here : your `choices` array is properly tucked away in the `getBotChoice` function. The `static_cast` (or C style cast) would be present only once, not scattered at every call. `enum`s or `enum class`es all the same will have drawbacks until C++ gets proper compile-time reflection on them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:02:02.273", "Id": "456843", "Score": "0", "body": "I meant the part where a `Choice` is turned into text for output. I’m starting to think that perhaps a non-enum class might be a nicer option. What do you think?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:09:48.320", "Id": "456845", "Score": "0", "body": "@Edward : This is one of the yucky points of `enum`s (scoped or unscoped). You can't (yet) introspect the number of declared enumerators, nor generate a dumb string from the enumerator name. There is a common technique of declaring an extra enumerator `NB_ENUMS` at the end (your `enum`had better be scoped, or you'll get name clashes), and you don't use it in user code, only to declare appropriately-sized arrays and such. This limits the power of `enum`s. There is no satisfactory solution yet, until we get proper compile-time reflection in C++. The C preprocessor might help there :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:18:24.623", "Id": "456846", "Score": "0", "body": "To sum up, I think the solution with enums is fine, but you have to make concessions, until `enum`s have full power : `using enum` for C++20, compile-time reflection for : the number of enumerators, the list of enumerators, the `string_view`s on the enumerator names, and the automatic generation of `to_string`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:12:28.063", "Id": "233668", "ParentId": "233644", "Score": "10" } }, { "body": "<p>In addition to the other answers. You say you have several years of experience. In this time you should have learnt to let your IDE format the code for you, to get consistent spacing between the <code>if</code> and the parenthesis. You sometimes wrote <code>if(</code> and sometimes <code>if (</code>.</p>\n\n<p>What you did really well though is naming the things. That's usually much harder to get right than the amount of whitespace in the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:22:50.587", "Id": "233675", "ParentId": "233644", "Score": "4" } }, { "body": "<p>One more suggestion to add on top of these already great answers.</p>\n\n<p>In the vein of \"being nicer to your users,\" instead of</p>\n\n<pre><code>if(input == \"rock\" || input == \"ROCK\" || input == \"1\" || input == \"r\" || input == \"R\") {\n</code></pre>\n\n<p>Consider:</p>\n\n<pre><code>std::transform(input.begin(), input.end(), input.begin(),\n [](unsigned char c){ return std::tolower(c); });\nif(input == \"rock\" || input == \"r\" || input == \"1\") {\n</code></pre>\n\n<p>You never use <code>input</code> for anything but those conditional checks and there's no real reason to disallow your users from entering Title Case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:35:42.733", "Id": "233731", "ParentId": "233644", "Score": "9" } } ]
{ "AcceptedAnswerId": "233646", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T19:19:36.567", "Id": "233644", "Score": "21", "Tags": [ "c++", "game", "console", "c++17", "rock-paper-scissors" ], "Title": "Rock, Paper, Scissors in C++" }
233644
<p>I am creating a small library for controlling bars of leds and have some doubts about my design.</p> <p>I have 2 basic entities in the design so far:</p> <p>BarService (and implementation)</p> <pre><code>template&lt;class T&gt; class BarService{ public: virtual void turnOnLeds(T* bar, int end) = 0; </code></pre> <pre><code>class PinBarService : public BarService&lt;PinBar&gt;{ public: virtual void turnOnLeds(PinBar* bar, int end); void initPins(PinBar* bar); }; </code></pre> <pre><code>class OpampService : public BarService&lt;OpampBar&gt;{ public: virtual void turnOnLeds(OpampBar* bar, int end); void initPins(OpampBar* bar); }; </code></pre> <p>Bar models:</p> <pre><code>class Bar{ private: int ledCount; public: Bar(int ledCount); int getLedCount(); }; </code></pre> <pre><code>class BasicBar : public Bar{ private: int* pins; public: BasicBar(int ledCount, int pins[]); int getPin(int index); }; </code></pre> <pre><code>class OpampBar : public Bar{ private: int input; public: OpampBar(int ledCount, int input); }; </code></pre> <p>My reasoning for separating these is that I feel the Bar models should only contain information about themselves, thus allowing me to create more classes later on which use that information rather than having the bar itself perform actions (like writing to hardware).</p> <p>The reason I'm having doubts is that by using templates every implementation of the service needs to accept a different model.</p> <p>My question comes down to: Am I going overboard with separating the model from its actions? and are templates a good solution here? and overall, what could be improved about this design? </p>
[]
[ { "body": "<p>Generally \"template vs polymorphism\" is a complex topic. A simple rule of thumb: if it is high level (e.g., service you instantiate a few times) go virtual, if it is low level (you need to create a array of million these objects) then go template.</p>\n\n<p>In your case... honestly your interface makes little sense to me - it is difficult to make any advices.</p>\n\n<p>Say, is there any point in <code>Bar</code> class? It simply holds an <code>int</code> and serves no other purpose. Just having a common function and variable doesn't imply that you need to have a shared basic class. If it had virtual destructor then I could understand to a certain degree.</p>\n\n<p>Why <code>OpampBar</code> is a class? It just holds two integers. Why not make it a struct with public members? Why make it unnecessarily complicated?</p>\n\n<p>What is this <code>BasicBar</code> and what is this <code>pins</code> raw pointer? Is it a pointer to an array? A pointer to data that doesn't belong to it? Why not use <code>std::vector&lt;int&gt;</code>? There are lots of well made classes and functions in STL, why not utilize them?</p>\n\n<p>What is the point of <code>BarService</code>? It is an interface class. I know of two purposes of interface classes: (1) To allow your program to switch between different derived classes easily. (2) Hide implementation. Is this the case? (Well, it can also serve as poor man's <code>concept</code> substitude... but I doubt that you use any SFINAE).</p>\n\n<p>You need to watch and read tutorials on C++. There are plenty for free - just google it. There are lots of CppCon videos on YouTube where they explain additions to C++ (you gotta learn what was added in C++11/14 as well as what STL already had for 20 years).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T07:30:44.143", "Id": "456809", "Score": "0", "body": "In an embedded system it Is often prefered or even the only viable way to avoid dynamic memory allocation. Maybe thats why array Is used instead of std::vector..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T07:58:14.233", "Id": "456811", "Score": "0", "body": "@slepic if you want to limit dynamic allocation then one can use `std::unique_ptr<int[]>` and utilize move operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T06:55:53.577", "Id": "457188", "Score": "0", "body": "But wouldn't that still do dynamic memory allocation? unique_ptr just handles the deallocation for you once the unique_ptr is destroyed. Isnt't it true, that it can't help if you wanted to avoid dynamic memory allocation entirely, not just limit it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T12:14:42.137", "Id": "457239", "Score": "0", "body": "@slepic it would be in a more controlled fashion - so you can pass buffers around. Or you want a system where there is no dynamic allocation at all? I mean, in this case I doubt you can use anything beyond C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T21:18:03.470", "Id": "457304", "Score": "0", "body": "Not true. You can still use classes, parameter overloading, all the fancy stuff. Dynamic does not mean OOP. Dynamic just means you decide (the amount/type of objects to create - the amount of memory to allocate) at runtime. But you can still put all that stuff on the stack as long as you know the number and types of objects you create at compile time. And OP never stated anything that implies he need to allocate variable amount of objects, nor create any objects of polymorphic type which he could not determine at compile time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T21:54:55.877", "Id": "457306", "Score": "0", "body": "@slepic you throw away almost everything there is in STL library - except for a few classes. I doubt that anyone would bother making a C++ implementation for such a limited system. In the worst case make a custom allocator that takes lots of space on the stack and simply use classes via this allocator. But if this is possible why can't `new` work in the first place?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T05:53:26.817", "Id": "457329", "Score": "0", "body": "Also not true. Many things in STL dont rely on dynamic memory. C++ has many implementations for such limited systems. It Is commonly used in such systems. And most importantly just because a feature exist doesnt mean you have to use it. dynamic memory allocation Is only reasonable in cases i already mentioned. And for example `array<>` is STL container without dynamic allocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:11:35.497", "Id": "457330", "Score": "0", "body": "Anyway, it doesnt have to be the case that dynamic memory is not avalable. There is just no reason to use it in OPs case. And why would I implement a custom allocator if allocation on stack as local variable is perfectly fine for given use case? Embedded systems usualy dont need that dynamic memory. They operate over a fixed set of components, chips have a fixed amount of pins, and so on. It's not like new LEDs are suddenly going to spawn in the system. Nor the chip is going to offspring a new pin..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:15:32.107", "Id": "457332", "Score": "0", "body": "I think you have blown your head with all the new stuff in the language And Are So keen on using it that you forgot to reason about when it Is appropriate. Hammer Is not Always the right Tool for a job... Although i knew a Guy WHO used pickaxe for everything And He seemd fine with that but thats another Story :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:19:54.830", "Id": "457334", "Score": "0", "body": "@slipic you aren't too bright, are you? Find me the poor fellow who needs to implement the whole C++ standart for system that have no dynamic allocation - no threads, no nothing. And all for what? It's easier to write in assembly those led controllers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:22:33.343", "Id": "457335", "Score": "0", "body": "Nevertheless the Real world shows us that C++ has Been implemented for such platforms And it Is commonly used on such platforms. And no, it Is not easier in assembler. Assembler Is So low level that it makes it hard to understand the code ať first glance. Use assembler if you want the best performance And remove every single unneeded instruction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:36:58.963", "Id": "457336", "Score": "0", "body": "Hmm so now I need threads to controll LEDs? Interesting. Nobody ever said everything from STL has to be implemented on those platforms. Do you always use every single feature of a library you pull in to your project? I doubt so. Embedded systems usualy dont have capabilities to have threads. And so the threads component doesnt have to be implemented on such platform. C++ has a lot to offer apart from STL and so it is still worth it. Now lets even assume that dynamic memory is available. Give me one good reason to use dynamic memory in OPs case and I will shut up..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:41:11.987", "Id": "457337", "Score": "0", "body": "@slepic C++ is used for embedded but it is only in your imagination that dynamic allocation cannot be called." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:44:08.293", "Id": "457338", "Score": "0", "body": "I didnt say cannot. I say it is not necesary until you need dynamic amount of objects or objects of type not known at compile time. They usualy have a limited amount of memory and so it is wise to only use it when no other option is available. Im still wating for your explanation why using the implicit stack is not an option here." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T04:45:47.963", "Id": "233657", "ParentId": "233645", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T19:32:13.493", "Id": "233645", "Score": "1", "Tags": [ "c++", "object-oriented", "inheritance" ], "Title": "Shift register library design" }
233645
<p>My code here loops through my folder and my files inside the folder and use <code>.find</code> and copy the strings into a new Excel sheet and then with all the data in the new sheet, I will use <code>.Find(What:=)</code> to find the strings inside the new worksheet and then either split or use Right, Left, Mid functions, sometimes using replace, however 68 files requires 1 minute 30 seconds run time using this code and I need help making it more efficient.</p> <pre><code>Option Explicit Sub GenerateData() Application.ScreenUpdating = False Dim wks As Worksheet Dim wkb As Workbook Set wkb = ActiveWorkbook Set wks = wkb.Worksheets.Add(After:=wkb.Worksheets(wkb.Worksheets.Count), Type:=xlWorksheet) ' Add headers data With wks .Range("A1:K1") = Array("Test", "Temp", "Type", "Start", "FileName", "No", "End", _ "Month", "Smart", "Errors", "ErrorCellAddress") End With ' Early Binding - Add "Microsoft Scripting Runtime" Reference Dim FSO As New Scripting.FileSystemObject ' Set FolderPath Dim FolderPath As String FolderPath = "c:\Users\Desktop\Tryout\" ' Set Folder FSO Dim Folder As Scripting.Folder Set Folder = FSO.GetFolder(FolderPath) ' Loop thru each file Dim File As Scripting.File Dim a As Range, b As Range, c As Range, d As Range, e As Range, f As Range, g As Range, h As Range, l As Range For Each File In Folder.Files Dim wkbData As Workbook Set wkbData = Workbooks.Open(File.Path) Dim wksData As Worksheet ActiveSheet.Name = "Control" Set wksData = wkbData.Worksheets("Control") ' -&gt; Assume this file has only 1 worksheet 'Format of the data Dim BlankRow As Long BlankRow = wks.Range("A" &amp; wks.Rows.Count).End(xlUp).Row + 1 ' Write filename in col E,F,G wks.Cells(BlankRow, 5).Value = File.Name wks.Cells(BlankRow, 6).Value = File.Name wks.Cells(BlankRow, 7).Value = File.Name 'Find Testtest Set a = wksData.Columns("A:A").Find(" testtest : ", LookIn:=xlValues) If Not a Is Nothing Then wks.Cells(BlankRow, 1).Value = a.Value End If 'Find Temp Set b = wksData.Columns("A:A").Find(" testflyy : ", LookIn:=xlValues) If Not b Is Nothing Then wks.Cells(BlankRow, 2).Value = b.Value End If 'Find Type Set d = wksData.Columns("A:A").Find(" testflyy : ", LookIn:=xlValues) If Not d Is Nothing Then wks.Cells(BlankRow, 3).Value = d.Value End If 'Find start Set l = wksData.Columns("A:A").Find(" Started at: ", LookIn:=xlValues) If Not l Is Nothing Then wks.Cells(BlankRow, 4).Value = l.Value End If 'Find Smart Set c = wksData.Columns("A:A").Find("SmartABC ", LookIn:=xlValues) If Not c Is Nothing Then wks.Cells(BlankRow, 9).Value = c.Value Else Set f = wksData.Columns("A:A").Find("SmarABCD Version ", LookIn:=xlValues) If Not f Is Nothing Then wks.Cells(BlankRow, 9).Value = f.Value Else Set g = wksData.Columns("A:A").Find("smarabcd_efg revision", LookIn:=xlValues) If Not g Is Nothing Then wks.Cells(BlankRow, 9).Value = g.Value End If End If End If 'Find Errors Set e = wksData.Columns("A:A").Find("ERROR: ABC", LookIn:=xlValues) If Not e Is Nothing Then wks.Cells(BlankRow, 10).Value = e.Value wks.Cells(BlankRow, 11).Value = e.Address Else Set h = wksData.Columns("A:A").Find("ERROR: EFG", LookIn:=xlValues) If Not h Is Nothing Then wks.Cells(BlankRow, 10).Value = h.Value End If End If ' Trim and tidy up Data 'Trim Testtest RowA(1) wks.Cells(BlankRow, 1).Replace What:="testtest : ", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False 'Trim StartTime RowD(4) wks.Cells(BlankRow, 4).Replace What:=" Started at: ", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False 'Trim Temp RowB(2) Dim strSearchB As String, strSearchC As String Dim bCell As Range, cCell As Range Dim s2 As String, s3 As String strSearchB = " testflow : B" strSearchC = " testflow : M" Set bCell = wks.Cells(BlankRow, 2).Find(What:=strSearchB, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not bCell Is Nothing Then s2 = Split(bCell.Value, ":")(1) s2 = Mid(s2, 1, 3) bCell.Value = s2 Else Set cCell = wks.Cells(BlankRow, 2).Find(What:=strSearchC, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not cCell Is Nothing Then s3 = Split(cCell.Value, ":")(1) s3 = Mid(s3, 10, 2) cCell.Value = s3 End If End If 'Trim Type RowC(3) Dim strSearchD As String, strSearchE As String Dim dCell As Range, eCell As Range Dim s4 As String, s5 As String strSearchD = " testflow : B" strSearchE = " testflow : M1947" Set dCell = wks.Cells(BlankRow, 3).Find(What:=strSearchD, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not dCell Is Nothing Then s4 = Split(dCell.Value, "_", 3)(2) s4 = Mid(s4, 1, 3) dCell.Value = s4 Else Set eCell = wks.Cells(BlankRow, 3).Find(What:=strSearchE, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not eCell Is Nothing Then eCell.Value = "123" End If End If 'Trim No RowF(6) Dim strSearchF As String Dim fCell As Range Dim s6 As String strSearchF = "homebeestrash_archivetreser" Set fCell = wks.Cells(BlankRow, 6).Find(What:=strSearchF, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not fCell Is Nothing Then s6 = Split(fCell.Value, "treser")(1) s6 = Mid(s6, 1, 2) fCell.Value = s6 End If 'Trim EndDate RowG(7) Dim strSearchG As String Dim gCell As Range Dim s7 As String strSearchG = "homebeestrash_archivetreser" Set gCell = wks.Cells(BlankRow, 7).Find(What:=strSearchG, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not gCell Is Nothing Then s7 = Split(gCell.Value, "reports")(1) s7 = Split(s7, "Report")(0) s7 = Left(s7, 8) &amp; " " &amp; Right(s7, 6) 'Month Row H(8) wks.Cells(BlankRow, 8).Value = WorksheetFunction.Transpose(Left(s7, 4) &amp; "-" &amp; Mid(s7, 5, 2) &amp; "-" &amp; Mid(s7, 7, 2)) gCell.Value = s7 End If wks.Cells(BlankRow, 8).NumberFormat = "[$-en-US]mmmm d, yyyy;@" 'Set Date format 'Trim Smart Dim strSearchST As String Dim stCell As Range Dim s8 As String strSearchST = "This is " Set stCell = wks.Cells(BlankRow, 9).Find(What:=strSearchST, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not stCell Is Nothing Then s8 = Split(stCell.Value, "This is ")(1) s8 = Mid(s8, 1, 29) stCell.Value = s8 End If wkbData.Close False Next File 'Add AutoFilter Dim StartDate As Long, EndDate As Long With wks.Cells(BlankRow, 8) StartDate = DateSerial(Year(.Value), Month(.Value), 1) EndDate = DateSerial(Year(.Value), Month(.Value) + 1, 0) End With wks.Cells(BlankRow, 8).AutoFilter Field:=5, Criteria1:="&gt;=" &amp; StartDate, Operator:=xlAnd, Criteria2:="&lt;=" &amp; EndDate If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData End Sub <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:57:48.730", "Id": "456866", "Score": "2", "body": "You may get some performance boost from code efficiencies after a review here, but I believe the majority of your execution time may be spent in the file system and Excel opening/closing the files. There is execution overhead in the Excel application to properly open a workbook and initialize the `Workbook` object. As a test, strip out all of the `.Find` sections of your code and just open and close all the workbooks. This minimal test will give you a good idea of the best possible time to execute your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:57:58.847", "Id": "456867", "Score": "1", "body": "Your comments claim that you're going to `'Find Temp` then `'Find Type`, yet the code following those comments are both searching for `testflyy` and assigning the results to `b` and `d`. Is this a typo when copying the code here? If not, just use `b` for both because your result will be the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-13T01:54:59.493", "Id": "461074", "Score": "0", "body": "I've rolled back the last edit. Please do not alter the code or deface the post after receiving answers." } ]
[ { "body": "<blockquote>\n <p>Disclaimer: <a href=\"http://rubberduckvba.com\" rel=\"nofollow noreferrer\"><strong>Rubberduck</strong></a> is a free, open-source VBIDE add-in project I manage and cheerlead, that's proudly &amp; actively maintained by members of this community. I have zero personal interests in your clicks, but I do own the project's website, contributed and/or reviewed the content, and I've written the articles on the project's blog - covers all links you'll find in this post (well, except the docs.microsoft.com one).</p>\n</blockquote>\n\n<hr>\n\n<p>I like starting at the top:</p>\n\n\n\n<blockquote>\n<pre><code>Sub GenerateData()\n</code></pre>\n</blockquote>\n\n<p>The procedure is <a href=\"http://rubberduckvba.com/Inspections/Details/ImplicitPublicMember\" rel=\"nofollow noreferrer\">implicitly Public</a>; in most other languages including VB.NET, a member without an explicit access modifier is <code>Private</code> - regardless of what the language defaults are, using explicit access modifiers everywhere is best practice.</p>\n\n<p>Kudos for avoiding the <code>Sub A()</code> or <code>Sub Macro1()</code> trap and actually using a somewhat meaningful name for the procedure. \"Generate data\" is a bit vague, but naming a procedure that's well over 200 lines of code is never easy, because such procedures tend to do a lot of things: accurately naming smaller, more specialized procedures is much easier!</p>\n\n<blockquote>\n<pre><code>' Add headers data\nWith wks\n .Range(\"A1:K1\") = Array(\"Test\", \"Temp\", \"Type\", \"Start\", \"FileName\", \"No\", \"End\", _\n \"Month\", \"Smart\", \"Errors\", \"ErrorCellAddress\")\nEnd With\n</code></pre>\n</blockquote>\n\n<p>Whenever I encounter a comment like this (\"below code does XYZ\"), I see a missed opportunity for a procedure named <code>DoXYZ</code>. In this case, something like this:</p>\n\n<pre><code>Private Sub AddColumnHeaders(ByVal sheet As Worksheet)\n sheet.Range(\"A1:K1\") = Array( _\n \"Test\", \"Temp\", \"Type\", \"Start\", _\n \"FileName\", \"No\", \"End\", \"Month\", _\n \"Smart\", \"Errors\", \"ErrorCellAddress\")\nEnd Sub\n</code></pre>\n\n<p>And just like that we've replaced 5 lines with one, and eliminated a comment that says <em>what</em> (always let <em>the code itself</em> say that, not comments), leaving room for a better comment that says <em>why</em>, if needed:</p>\n\n<pre><code>AddColumnHeaders wks\n</code></pre>\n\n<p>But we could go one step further, and take a <code>Workbook</code> parameter instead, and <em>return</em> a new, worksheet with the column headers - and since the only code that needs a <code>Workbook</code> is the code that's creating the worksheet, we eliminate the need for a local <code>Workbook</code> variable:</p>\n\n<pre><code>Dim sheet As Worksheet\nSet sheet = CreateOutputSheet(ActiveWorkbook)\n</code></pre>\n\n<p>And the <code>CreateOutputSheet</code> function might look like this:</p>\n\n<pre><code>Private Function CreateOutputSheet(ByVal book As Workbook) As Worksheet\n Dim sheet As Worksheet\n Set sheet = book.Worksheets.Add(After:=book.Worksheets(book.Worksheets.Count))\n AddColumnHeaders sheet\n Set CreateOutputSheet = sheet\nEnd Function\n</code></pre>\n\n<p>Note that the <code>Type</code> argument is redundant when it's an <code>xlWorksheet</code> that you're adding; <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.sheets.add\" rel=\"nofollow noreferrer\">it's the default</a>.</p>\n\n<p>Also note, the crystal-clear distinction between <code>book</code> and <code>sheet</code>; compare to the single-character difference between <code>wks</code> and <code>wkb</code>. Vowels exist, and should be used: don't arbitrarily strip them from identifiers, we're not in 1985 anymore, variables <em>can</em>, and <em>should</em> have meaningful, pronounceable names.</p>\n\n<blockquote>\n<pre><code>' Early Binding - Add \"Microsoft Scripting Runtime\" Reference\n Dim FSO As New Scripting.FileSystemObject\n' Set FolderPath\n Dim FolderPath As String\n FolderPath = \"c:\\Users\\Desktop\\Tryout\\\"\n' Set Folder FSO\n Dim Folder As Scripting.Folder\n Set Folder = FSO.GetFolder(FolderPath)\n</code></pre>\n</blockquote>\n\n<p>Note that adding a reference to the <code>Scripting</code> library isn't what makes the <code>FSO</code> early bound: while useful (informs of a dependency) that comment is somewhat misleading - if you declared the <code>FSO</code> with <code>As Object</code>, member calls against it would still be late-bound, even if the library is referenced. See <a href=\"https://rubberduckvba.wordpress.com/2019/04/28/late-binding/\" rel=\"nofollow noreferrer\">late binding</a> for more info.</p>\n\n<p>Of particular note, <em>implicit</em> late binding, like you have here and in every single one of your <code>Range.Find</code> calls:</p>\n\n<blockquote>\n<pre><code>Set a = wksData.Columns(\"A:A\").Find(\" testtest : \", LookIn:=xlValues)\n</code></pre>\n</blockquote>\n\n<p><code>Range.Columns</code> returns a <code>Range</code> (early-bound), but doesn't take any parameters: the <code>(\"A:A\")</code> argument list is going to <code>Range.[_Default]</code>, which returns a <code>Variant</code> - hence, any member call chained to it, can only be resolved at run-time. This means your <code>Range.Find</code> member call isn't validated at compile-time, you wrote it blindfolded without parameter quick-info, and if you made a typo, <code>Option Explicit</code> can't save you from it. <em>That</em> implicit late binding is pretty insiduous, and should be given much more importance and attention than this early-bound declaration.</p>\n\n<p>Keep in mind that <code>Dim</code> statements aren't executable, and <code>As New</code> creates an <a href=\"http://rubberduckvba.com/Inspections/Details/SelfAssignedDeclaration\" rel=\"nofollow noreferrer\">auto-instantiated object</a> that will not behave the way you normally expect objects to behave. This <code>FSO</code> object is live and well for the entire duration of the procedure, and yet it's only used in one single instruction. Consider limiting its lifetime to a bare minimum. All variables should be as tightly scoped as possible, and no object needs to stick around if it's not needed.</p>\n\n<p>Consider:</p>\n\n<pre><code>Dim basePath As String\nbasePath = Environ$(\"USERPROFILE\") &amp; \"\\Desktop\\Tryout\\\"\n\nDim baseFolder As Scripting.Folder\nWith New Scripting.FileSystemObject\n Set baseFolder = .GetFolder(basePath)\nEnd With\n</code></pre>\n\n<p>The indentation, somewhat consistent up to that point (I find the offset assignment vs declaration quite off-putting and rather hard to apply consistently, but that could be just me), starts going south and feel pretty much random here. This is a definitive sign of indentation gone terribly wrong:</p>\n\n<blockquote>\n<pre><code> End If\n End If\n End If\n</code></pre>\n</blockquote>\n\n<p>These same-level <code>End If</code> tokens show up in multiple places, and that is a problem: if I quickly glance at the code top-to-bottom, I might miss the <code>For</code> loop buried in a bunch of declarations that really belong elsewhere, and I'll have to work very hard to locate the corresponding <code>Next</code> token, like I just did. Proper and consistent indentation is the solution, and you can use Rubberduck's <a href=\"http://rubberduckvba.com/indentation\" rel=\"nofollow noreferrer\">Smart Indenter</a> port, or any other VBIDE add-in that features an indenter for that.</p>\n\n<p>These variables have a rather strong smell:</p>\n\n<blockquote>\n<pre><code>Dim a As Range, b As Range, c As Range, d As Range, e As Range, f As Range, g As Range, h As Range, l As Range\n</code></pre>\n</blockquote>\n\n<p>Ignoring the fact that they are meaningless single-letter identifiers (and that using lowercase-L as a variable name is outright criminal), the sequence feels like it could just as well be <code>rng1</code>, <code>rng2</code>, <code>rng3</code>, and so on - and <em>that</em> is what's wrong with them: these variables are saying \"we're all doing the same thing\", and indeed, looking at how they're used, they're <em>literally</em> all the same.</p>\n\n<p>Every single one of these blocks:</p>\n\n<blockquote>\n<pre><code> 'Find Testtest\n Set a = wksData.Columns(\"A:A\").Find(\" testtest : \", LookIn:=xlValues)\n If Not a Is Nothing Then\n wks.Cells(BlankRow, 1).Value = a.Value\n End If\n</code></pre>\n</blockquote>\n\n<p>Is identical, save what's being searched, and what column it's being written to: this block should be its own parameterized procedure. Whenever you find yourself selecting a block of code and hitting <kbd>Ctrl</kbd>+<kbd>C</kbd>, stop and think of how you can avoid duplicating code by introducing a small, specialized procedure.</p>\n\n<p>This comment makes no sense:</p>\n\n<blockquote>\n<pre><code> 'Format of the data\n Dim BlankRow As Long\n BlankRow = wks.Range(\"A\" &amp; wks.Rows.Count).End(xlUp).Row + 1\n</code></pre>\n</blockquote>\n\n<p>Working out the row to write in wouldn't be needed if your <code>Range</code> happened to be a <code>ListObject</code> (aka table). With the <code>ListObject</code> API, you would be getting the table to dump the data into:</p>\n\n<pre><code>Dim table As ListObject\nSet table = wks.ListObjects(\"TableName\")\n\nDim newRow As ListRow\nSet newRow = table.ListRows.Add\n</code></pre>\n\n<p>And done. Now all you need to do is populate the <code>Range</code> of this <code>newRow</code>.</p>\n\n<pre><code>Private Function PopulateIfFound(ByVal source As Range, ByVal value As String, ByVal row As ListRow, ByVal writeToColumn As Long, Optional ByVal writeAddressToNextColumn As Boolean = False) As Boolean\n Dim result As Range\n Set result = source.Find(value, LookIn:=xlValues)\n If Not result Is Nothing Then\n Dim cell As Range\n Set cell = row.Range.Cells(ColumnIndex:=writeToColumn)\n cell.Value = result.Value\n If writeAddressToNextColumn Then\n cell.Offset(ColumnOffset:=1).Value = result.Address\n End If\n PopulateIfFound = True\n End If\nEnd Function\n</code></pre>\n\n<p>And now the repetitive searches would look like this:</p>\n\n<pre><code> Dim source As Range\n Set source = wksData.Range(\"A:A\")\n\n PopulateIfFound source, \" testtest : \", newRow, 1\n PopulateIfFound source, \" testflyy : \", newRow, 2\n PopulateIfFound source, \" testflyy : \", newRow, 3\n PopulateIfFound source, \" Started at: \", newRow, 4\n If Not PopulateIfFound(source, \"SmartABC \", newRow, 9) Then\n PopulateIfFound source, \"smarabcd_efg revision\", newRow, 9\n End If\n If Not PopulateIfFound(source, \"ERROR: ABC\", newRow, 10, True) Then\n PopulateIfFound source, \"ERROR: EFG\", newRow, 10\n End If\n</code></pre>\n\n<p>I note that your searches include a dangerous amount of seemingly-arbitrary whitespace; this makes the code extremely frail, because a single missing or additional space is all it takes to make any of these searches fail.</p>\n\n<p>This is interesting:</p>\n\n<blockquote>\n<pre><code> ' Write filename in col E,F,G\n wks.Cells(BlankRow, 5).Value = File.Name\n wks.Cells(BlankRow, 6).Value = File.Name\n wks.Cells(BlankRow, 7).Value = File.Name\n</code></pre>\n</blockquote>\n\n<p>I can see that it's writing the file name in 3 consecutive columns (<em>what</em>). What I'd like this comment to tell me, is <em>why</em> the file name needs to be in 3 places right next to each others. Strikes me as redundant/superfluous otherwise.</p>\n\n<p>This shouldn't need to happen:</p>\n\n<blockquote>\n<pre><code> ' Trim and tidy up Data\n\n 'Trim Testtest RowA(1)\n wks.Cells(BlankRow, 1).Replace What:=\"testtest : \", Replacement:=\"\", LookAt:=xlPart, _\n SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _\n ReplaceFormat:=False\n\n 'Trim StartTime RowD(4)\n wks.Cells(BlankRow, 4).Replace What:=\" Started at: \", Replacement:=\"\", LookAt:=xlPart, _\n SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _\n ReplaceFormat:=False\n</code></pre>\n</blockquote>\n\n<p>You're the one writing to <code>wks.Cells(BlankRow, n)</code>: you shouldn't need to make another pass to clean up anything after the data was written - just clean it up <em>as you write it</em>. Everything that's happening from here on, up to <code>wkbData.Close False</code>, is reprocessing data that was already written. If your destination were a <code>ListObject</code>, you wouldn't need to worry about number formats, since the formatting would be identical for every row, and automatically carried onto any <code>newRow</code> you add to it, along with the formula for any calculated column.</p>\n\n<p>This is a potential issue:</p>\n\n<blockquote>\n<pre><code>Dim StartDate As Long, EndDate As Long\n\nWith wks.Cells(BlankRow, 8)\n StartDate = DateSerial(Year(.value), Month(.value), 1)\n EndDate = DateSerial(Year(.value), Month(.value) + 1, 0)\nEnd With\n</code></pre>\n</blockquote>\n\n<p>Treat dates as <code>Date</code>. They're not strings, and they're not <code>Long</code> integers either. If you <em>really</em> want to use a numeric type for them, then use a <code>Double</code>. But <code>StartDate As AnythingButDate</code> is just wrong: since this is for filtering, a numeric value is more sane than a string, so kudos for that - I'd go with <code>Dim fromDateValue As Double</code> and <code>Dim toDateValue As Double</code>.</p>\n\n<blockquote>\n<pre><code>If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData\n</code></pre>\n</blockquote>\n\n<p>Because <code>ActiveSheet</code> is <code>Object</code>, these member calls are implicitly late-bound. This is bad, first because up to that point we didn't care at all what the <code>ActiveSheet</code> was (except for that part where we assume the opened workbook doesn't already have a <code>\"Control\"</code> sheet as its one and only worksheet... this may be a bad assumption; such assumptions are typically made explicit with <code>Debug.Assert</code> calls, e.g. <code>Debug.Assert wkbData.Worksheets.Count = 1</code>, and execution stops if the assertion isn't true).</p>\n\n<p>I'd have an explicit reference to a proper <code>Worksheet</code> variable here: the code does not need to care what sheet is active, and shouldn't either.</p>\n\n<p>Don't worry about performance. Worry about redundant and repetitive code. Once your code is all cleaned up, see how it runs. Identify what double-processing is being done, remove it.</p>\n\n<p>As others have mentioned, the single largest bottleneck here, is I/O overhead: opening and closing workbooks is very expensive, and if that's what your code needs to do, then that's the overhead it needs to cope with. Consider implementing a <a href=\"https://rubberduckvba.wordpress.com/2018/01/12/progress-indicator/\" rel=\"nofollow noreferrer\">progress indicator</a> to make the long-running operation more bearable.</p>\n\n<p><em>Maybe</em> replacing the <code>Range.Find</code> calls with some <code>WorksheetFunction.Index</code>/<code>WorksheetFunction.Match</code> combo might be faster, but that depends on what your data really looks like. Besides, the first thing to do is to constraint the search range to the actually meaningful cells in column A, rather than searching across the million-or-so cells in that column.</p>\n\n<p>Toggling <code>Application.Calculation</code> to <code>xlCalculationManual</code> would stop Excel from recalculating dependents whenever you write a cell value; if you don't need to recalculate anything until you're completely done with a file, then that's a good idea - toggling calculation back to <code>xlCalculationAutomatic</code> will trigger a recalc, so no need to explicitly calculate anything.</p>\n\n<p>Toggling <code>Application.EnableEvents</code> to <code>False</code> would stop Excel from raising <code>Workbook</code> and <code>Worksheet</code> events every time you write to a cell; if you have event handlers for worksheet <code>Change</code> events, this is a must. Otherwise, toggling it off can still make Excel work more on executing your VBA code and less on trying to keep the workbook in a consistent state.</p>\n\n<p>Toggling <code>Application.ScreenUpdating</code> to <code>False</code> like you did helps a tiny little bit too, but since you're not constantly activating and selecting things, the effect is marginal.</p>\n\n<p>Note that whenever you toggle this global <code>Application</code> state, you absolutely want to handle any &amp; all run-time errors that might happen while your procedure is running, such as to guarantee that whatever happens, whether it blows up or not, the global <code>Application</code> state is exactly what it was before you ran the procedure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T01:59:56.860", "Id": "456965", "Score": "0", "body": "Seriously! i am loss for words, thanks so much for the effort that you put in, it is my first time using private sub and functions, i have read up and researched about them, but still have no idea how to make use of them. Could you please enlighten me about it? If possible the combination of the codes provided by you so i can have a better idea how i can use/call functions and how to run private subs and regarding to why i repeatedly find and write the same strings in different columns is because sometimes just one string consists of information for column 2 or 3 thus the 3lines of `File.Name`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T02:08:44.903", "Id": "456967", "Score": "0", "body": "Code is a series of executable instructions that have such or such side effect on the document(s) it's working with. Right? Now what if code were the expression of ideas, descriptions of what's going on, and the deeper you dive into it, the finer the details get. When you write code you get to craft a language with verbs (procedures), nouns (objects, properties), even adverbs (arguments)! The key is *abstraction*. Higher abstraction at the top, gory details at the bottom; small, specialized procedures that do one thing, and that do it well, are more reliable and easier to maintain & debug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T02:12:52.033", "Id": "456968", "Score": "0", "body": "Start with pseudo-code: what are the steps? Name them; each one is its own named procedure. Only one needs to be `Public`: the one that's meant to be visible from the calling code's point of view. If that's in Module1 and I'm in another module, then when I type `Module1.` the autocompletion list only includes the public members. The private ones are *implementation details*, at a lower abstraction level than the caller needs to care for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:05:48.533", "Id": "457196", "Score": "0", "body": "sorry to bother you again but when i was trying out the code i kept getting an error like \"Object required\" or \"Object Variable or With Block variable not set\" from the line `Dim table As ListObject\nSet table = wks.ListObjects(\"TableName\")\n\nDim newRow As ListRow\nSet newRow = table.ListRows.Add` i have tried many other ways like creating a function for it and adding object to it but all of it can't work...could you mind helping me out abit? Thanks once again :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:38:17.330", "Id": "457244", "Score": "0", "body": "Is `wks` defined? It needs to be a `Worksheet` object. This error message can also indicate that `Option Explicit` is missing from the module, so the code happily compiles and runs with undefined variables. If `wks` is undefined, then at run-time it's a `Variant/Empty` and that's why making a member call against it raises an \"object required\" error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:54:37.127", "Id": "457249", "Score": "0", "body": "Yes it has been defined as `Dim wks As WorkSheet` with `Set wks = Worksheets(1)` however an error `Subscript out of range` will pop up" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:08:40.343", "Id": "457251", "Score": "0", "body": "i feel the error is with this line right here... `Set table = wks.ListObjects(\"TableName\")` but i'm not sure why" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:10:42.493", "Id": "457252", "Score": "0", "body": "Did you name your table \"TableName\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:12:12.957", "Id": "457253", "Score": "0", "body": "You mean in this line? `Set table = wks.ListObjects(\"TableName\")` , if its okay with you, can we start a conversation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:07:55.323", "Id": "457260", "Score": "0", "body": "@lalalisa sure! [VBA Rubberducking](https://chat.stackexchange.com/rooms/14929/vba-rubberducking) awaits =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T01:48:00.260", "Id": "457319", "Score": "0", "body": "@Matheiu Guindon is it ok if you join this room here? https://chat.stackexchange.com/rooms/102099/room-for-lalalisa-and-mathieu-guindon" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:43:07.627", "Id": "233719", "ParentId": "233653", "Score": "6" } } ]
{ "AcceptedAnswerId": "233719", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T02:21:07.540", "Id": "233653", "Score": "6", "Tags": [ "vba", "excel" ], "Title": "Copying strings from files into a new Excel sheet" }
233653
<p>I've written this decorator to avoid too many requests to a backend. Did I get it right? Do I need some locks or can I assume some things are atomic / thread safe because this is asyncio?</p> <pre><code>def batch_calls(f): """Batches single call into one request. Turns `f`, a function that gets a `tuple` of independent requests, into a function that gets a single request. """ queue = {} async def make_call(): if not queue: return await asyncio.sleep(0.1) if not queue: return queue_copy = dict(queue) queue.clear() try: for async_result, result in zip( queue_copy.values(), await f(tuple(queue_copy)) ): async_result.set_result(result) except Exception as exception: for async_result in queue_copy.values(): async_result.set_exception(exception) async def wrapped(hashable_input): if hashable_input in queue: return await queue[hashable_input] async_result = asyncio.Future() # Check again because of context switch due to the creation of `asyncio.Future`. # TODO(uri): Make sure this is needed. if hashable_input in queue: return await queue[hashable_input] queue[hashable_input] = async_result if len(queue) == 1: asyncio.create_task(make_call()) return await async_result return wrapped </code></pre> <p>The user might use it like so:</p> <pre><code>@batch_calls async def call_server(texts: Tuple[Text, ...]): return tuple( ( await httpx.post( url=SERVICE_URL, json={"texts": texts}, ) ).json() ) </code></pre> <p>This code is causing a deadlock on some situations - not easily reproducible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T05:57:03.370", "Id": "456807", "Score": "0", "body": "Can you also post a more extended context: 1) a sample function `f` definition to which your decorator is applied; 2) sample `hashable_input` value ???" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:03:32.860", "Id": "456844", "Score": "0", "body": "gave a run example. you can think of hashable_input as a string. ptal" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T04:27:52.213", "Id": "233656", "Score": "3", "Tags": [ "python", "asynchronous" ], "Title": "Batching calls to server in python with asyncio" }
233656
<p>I'm working on one easy question (<a href="https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/submissions/" rel="nofollow noreferrer">Leetcode 1275. Find Winner on a Tic Tac Toe Game</a>) and am wondering how I can make the code even cleaner.</p> <pre><code>class Solution: def tictactoe(self, moves: List[List[int]]) -&gt; str: from collections import Counter def is_win(pos: List[List[int]]) -&gt; bool: pos = set(tuple(i) for i in pos) d1, d2 = set([(0, 0), (1, 1), (2, 2)]), set([(0, 2), (1, 1), (2, 0)]) x = Counter(i for i, _ in pos) y = Counter(i for _, i in pos) d1 -= set(pos) d2 -= set(pos) return (3 in x.values()) or (3 in y.values()) or not d1 or not d2 a, b = moves[::2], moves[1::2] A, B = is_win(a), is_win(b) if A: return 'A' elif B: return 'B' elif not A and not B and (len(moves) == 9): return 'Draw' return 'Pending' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:43:54.440", "Id": "456828", "Score": "1", "body": "Can you add a context of calling your function `tictactoe` with sample value for `moves` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:19:59.510", "Id": "456834", "Score": "1", "body": "Yep, using `List[int]` instead of the more obvious `Tuple[int, int]` for `(row, col)` is definitely confusing. Leetcode should have defined better types here." } ]
[ { "body": "<p>The second half of your code is inefficient, as it computers <code>is_win(b)</code> unnecessarily. It can be written as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if is_win(moves[::2]):\n return 'A'\n elif is_win(moves[1::2]):\n return 'B'\n elif len(moves) == 9:\n return 'Draw'\n else:\n return 'Pending'\n</code></pre>\n\n<p>This removes the redundant <code>not a and not b</code>, the redundant parentheses and the redundant computation of <code>is_win</code> in case A has won already.</p>\n\n<p>When I saw <code>is_win</code> for the first time, I didn't understand it.</p>\n\n<ul>\n<li>Maybe my chances had been better if you renamed <code>d1</code> to <code>diag1</code>.</li>\n<li>You could also write <code>diag1</code> and <code>diag2</code> on separate lines, to align their coordinates vertically.</li>\n<li>You could also inline the <code>diag1</code> and <code>diag2</code> so that you don't need a name for them at all.</li>\n</ul>\n\n<p>I'm thinking of:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_win(pos: List[List[int]]) -&gt; bool:\n pos = set(tuple(i) for i in pos)\n horiz = 3 in Counter(r for r, _ in pos).values()\n verti = 3 in Counter(c for _, c in pos).values()\n diag1 = not (set([(0, 0), (1, 1), (2, 2)]) - pos)\n diag2 = not (set([(0, 2), (1, 1), (2, 0)]) - pos)\n return horiz or verti or diag1 or diag2\n</code></pre>\n\n<p>To avoid unnecessary computations here as well, you can let your IDE inline the variables except for <code>pos</code>.</p>\n\n<p>Instead of <code>not (set1 - set2)</code>, the expression <code>set1.issubset(set2)</code> is clearer because it avoids the confusing <code>not</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> diag1 = {(0, 0), (1, 1), (2, 2)}.issubset(pos)\n # or:\n diag1 = {(0, 0), (1, 1), (2, 2)} &lt;= pos\n</code></pre>\n\n<p>Or you could make checking the diagonals similar to horizontal and vertical:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> diag1 = 3 in Counter(r - c for r, c in pos).values()\n diag2 = 3 in Counter(r + c for r, c in pos).values()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:32:58.153", "Id": "456908", "Score": "1", "body": "it is good idea to use multiple list comprehensive other than just use one for loop?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:53:28.013", "Id": "233672", "ParentId": "233659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T05:04:06.237", "Id": "233659", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Leetcode 1275. Find Winner on a Tic Tac Toe Game" }
233659
<p>I am new to Ctypes. I am writing a piece of code that brings an array of unknown size from C to Python using Ctypes. Unknown size here mean that Python initially doesn't know the size of the array. C code has the algorithm which creates the array. Somehow after lot of trails, I managed to write code for that:</p> <p>python code: sample.py</p> <pre><code>from ctypes import * #import needed packages import os def main(): a = 6; lib_path = os.path.join(os.path.dirname(__file__), 'Debug','{}.dll'.format("sum")) #print(lib_path) try: lib = cdll.LoadLibrary(lib_path) except Exception as e: raise RuntimeError("Could not library with this path: {}. {}".format(lib_path, e)) class truct(Structure): _fields_ = [("array", POINTER(c_double)), ("len", c_int)] va = truct() ty = (c_double * 1 ) va.array = ty() va.len = 1 lib.sample_function.argtypes= [POINTER(truct)] lib.sample_function.restype = c_int try: ret = lib.sample_function(byref(va)) except Exception as e: raise RuntimeError("Library call raises exception: {}".format(e)) </code></pre> <p>C code:</p> <pre><code>typedef struct A { double *array; int a; } A; void sample_function2(A* structure){ int array_local[] = { 0,0,1,1,0}; int iter2; for (iter2 =0;iter2&lt;5;iter2++){ if(array_local[iter2]){ structure-&gt;array[iter2] = iter2; }else{ structure-&gt;array[iter2] = 0; }} } int sample_function( A* structure) { int n = 5; int iter; sample_function2(structure); return 0; } </code></pre> <p>This code works as expected. But is it a good practice to use this method?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T05:07:38.017", "Id": "233660", "Score": "4", "Tags": [ "python", "c" ], "Title": "Transfer an array of unknown size from C to Python using Ctypes" }
233660
<p>I have a 2D array <code>matches</code> where I store the game id and another array of objects <code>games</code> where I store <code>gameId</code> with the <code>playerId</code>. </p> <p>Here is what I have done so far: </p> <p>Step 1: I get the opponent's gameId against the gameId from "matches" array.</p> <p>e.g. gameId "2" has an opponent "1"</p> <p>Step 2: check opponent_game in games and return game.</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 gameId = 2 let matches = [ [1, 2], [3, 4] ] const opponent_game = matches.filter((v, i) =&gt; { if (v.includes(gameId)) { var index = v.indexOf(gameId); if (index &gt; -1) { return v.splice(index, 1); } } }) let games = [{ gameId: 1, playerId: 222 }, { gameId: 4, playerId: 222 }] const game = games.filter((v, i) =&gt; { return v.gameId === opponent_game[0][0] }) console.log(game)</code></pre> </div> </div> </p> <p>Please suggest best practices in javascript or an optimized and clean way to write the same solution. TIA</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T08:42:57.627", "Id": "456814", "Score": "0", "body": "Does this code work? The `matches.filter` call looks wrong. The callback function should return a boolean, but you are returning an array or `undefined` ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:00:02.720", "Id": "456821", "Score": "0", "body": "yes it's working" } ]
[ { "body": "<p><code>.includes()</code> and checking <code>.indexOf()</code> against <code>-1</code> do the same thing, you only need one. </p>\n\n<p>Also the function should be returning a boolean value. It currently works because the array returned by <code>.splice()</code> is considered <code>true</code> and not returning anything (or <code>undefined</code>) is considered <code>false</code>. It would be better to explicitly return a boolean:</p>\n\n<pre><code> const opponent_game = matches.filter((v, i) =&gt; {\n var index = v.indexOf(gameId);\n if (index &gt; -1) {\n v.splice(index, 1);\n return true;\n }\n return false;\n})\n</code></pre>\n\n<p>However modifying the content of an array in a <code>filter</code> is bad practice, because it is unexpected. Since you only looking for a single value <code>.reduce()</code> would probably be the better choice:</p>\n\n<pre><code> const opponent_game = matches.reduce((acc, v) =&gt; {\n if (acc !== null) {\n return acc;\n }\n var index = v.indexOf(gameId);\n if (index &gt; -1) {\n return v[1 - index];\n }\n return null;\n}, null)\n</code></pre>\n\n<p>In this case <code>opponent_game</code> is a number and no longer an array containing an array containing a number so that simplifies the second part too. Also since you are looking for a single item <code>.find()</code> would be more appropriate:</p>\n\n<pre><code>const game = games.find(v =&gt; {\n return v.gameId === opponent_game\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:30:21.100", "Id": "456848", "Score": "0", "body": "have run this code? console.log(opponent_game) return result \"2\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T12:39:45.673", "Id": "456851", "Score": "0", "body": "@ManjeetThakur Fixed it. I shouldn't have used `splice` in the reduce version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:49:10.983", "Id": "456996", "Score": "0", "body": "I'm still not satisfied and also try another way to solve this problem" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:12:21.613", "Id": "233667", "ParentId": "233662", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T07:17:52.517", "Id": "233662", "Score": "-1", "Tags": [ "javascript" ], "Title": "Best way extract gameId from array object" }
233662
<p>I am a technical reviewer/writer and I use VBA for Word a lot to manage issues in Word documents I receive. I have frequently come across niggles when using Collections, Scripting.Dictionaries or Array lists. Then I saw some posts on creating a C# library for consumption by VBA. After much reading and research I eventually produced a C# library that wraps a C# dictionary and which can be consumed by VBA. It works very well but there are some wrinkles.</p> <ul> <li><p>I'd like to be able to view the content of the dictionary in the same way that the content of Collections and ArrayLists (but not Scripting.Dictionaries) can be viewed using the VBA IDE Locals Window.</p></li> <li><p>I'd like to understand why, when I pass the object created by the C# class, I can use class_instance.Item = value in the method which creates the class instance, but where if I pass the class instance to another method in VBA I first have to cast it to an object before I can assign a value to an element in the cast class_instance (e.g. class_instance_as_object.Item =Value).</p></li> </ul> <p>Please be aware that this is a work in progress as I keep adding methods to the class whenever I have some VBA code that I wish to simplify.</p> <p>I am not a professional programmer and the C# code below is my first foray into using this language.</p> <p>I'm also looking for useful pointers to articles, or chapters in books that I should go and read to help me improve my c# code, but all comments are welcome.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Linq; namespace VBAExtensions { /// &lt;summary&gt; /// Enum for accessing the kvp structure returned by Method Cohorts /// &lt;/summary&gt; public enum CohortType { /// &lt;summary&gt;1 = the keys in A plus keys in B that are not shared&lt;/summary&gt; KeysInAAndOnlyB = 1, /// &lt;summary&gt;2 = the Keys from B in A where B has a different value to A&lt;/summary&gt; KeysInAandBWithDifferentValues, /// &lt;summary&gt;3 = the keys that are only in A and only in B&lt;/summary&gt; KeysNotInAandB, /// &lt;summary&gt;4 = the keys that are inA and B &lt;/summary&gt; KeysInAandB, /// &lt;summary&gt;5 = the keys in A only &lt;/summary&gt; KeysInAOnly, /// &lt;summary&gt;6 = the keys in B only&lt;/summary&gt; KeysInBOnly } /// &lt;summary&gt; /// Kvp is a C# class for VBA which implements a Key/Value Dictionary /// The object is a morer flexible version of the Scripting.Dictionary /// &lt;/summary&gt; [Guid("6DC1808F-81BA-4DE0-9F7C-42EA11621B7E")] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IKvp { /// &lt;summary&gt; /// Returns/Sets the "Value" specified by "Key" (i) of a Key/Value Pair /// &lt;/summary&gt; /// &lt;param name="Key"&gt;&lt;/param&gt; /// &lt;returns&gt;Type used in Set statement (C# dynamic)&lt;/returns&gt; dynamic this[dynamic Key] { get; set; } /// &lt;summary&gt; /// Adds "Value" to the Kvp using an integer (VBA Long) Key. /// The integer key is is started at 0 /// &lt;/summary&gt; /// &lt;param name="Value"&gt;&lt;/param&gt; void AddByIndex(dynamic Value); /// &lt;summary&gt; /// Populates this Kvp using AddByIndex for each character in the string /// &lt;/summary&gt; /// &lt;param name="ipString"&gt;&lt;/param&gt; void AddByIndexAsChars(string ipString); /// &lt;summary&gt; /// Pupulates this Kvp using AddByIndex for each substring in ipString delineated by ipSeparator /// &lt;/summary&gt; /// &lt;param name="ipString"&gt;&lt;/param&gt; /// &lt;param name="ipSeparator"&gt;&lt;/param&gt; void AddByIndexAsSubStr(string ipString, string ipSeparator = ","); /// &lt;summary&gt; /// Pupulates a Kvp using AddByIndex for each array item /// &lt;/summary&gt; /// &lt;param name="this_array"&gt;&lt;/param&gt; void AddByIndexFromArray(dynamic this_array); /// &lt;summary&gt; /// Adds "Value" to the Kvp with a key pf "Key" /// &lt;/summary&gt; /// &lt;param name="Key"&gt;&lt;/param&gt; /// &lt;param name="Value"&gt;&lt;/param&gt; void AddByKey(dynamic Key, dynamic Value); /// &lt;summary&gt; /// Adds array to the Kvp with ujsing array[x,1] as the key and array[x,0..end] as the value /// &lt;/summary&gt; void AddByKeyFromArray(dynamic ipArray); /// &lt;summary&gt; /// Groups the keys of the two Kvp /// &lt;/summary&gt; /// &lt;param name="ArgKvp"&gt;&lt;/param&gt; /// &lt;returns&gt;An array of 6 Kvp /// keys in a {1,2,3,4,5,6} /// keys in b {1,2,3,6,7,8} /// 1 = the keys in A plus keys in B that are not shared {1,2,3( from A),4,5,6,7,8} /// 2 = the Keys from B in A where B has a different value to A {3( from B) if value is different} /// 3 = the keys that are only in A and only in B {4,5,7,8} /// 4 = the keys that are in A and B {1,2,3,6} /// 5 = the keys in A only {4,5} /// 6 = the keys in B only {7,8} /// &lt;/returns&gt; Kvp Cohorts(Kvp ArgKvp); /// &lt;summary&gt; /// The number of key/vaue pairs in the Kvp /// &lt;/summary&gt; /// &lt;returns&gt;Long&lt;/returns&gt; int Count(); /// &lt;summary&gt; /// Returns a shallow copy of the Kvp /// &lt;/summary&gt; /// &lt;returns&gt;New kvp as a copy of the old kvp&lt;/returns&gt; Kvp Clone(); /// &lt;summary&gt; /// Gets the "Key" for the first ocurrence of "Value" in the Kvp. /// &lt;/summary&gt; /// &lt;param name="Value"&gt;&lt;/param&gt; /// &lt;returns&gt;Key&lt;/returns&gt; dynamic GetKey(dynamic Value); /// &lt;summary&gt; /// Returns a variant array of the Keys of the Kvp /// &lt;/summary&gt; /// /// &lt;returns&gt;Variant Array&lt;/returns&gt; dynamic GetKeys(); /// &lt;summary&gt; /// Gets the 0th element of the Kvp /// &lt;/summary&gt; /// &lt;returns&gt;Value at )th position&lt;/returns&gt; dynamic GetFirst(); /// &lt;summary&gt; /// Gets the element at the upper bound of MyKvp /// This may not be the maximum integer key /// &lt;/summary&gt; /// &lt;returns&gt;Value of the element at the upper bound&lt;/returns&gt; dynamic GetLast(); /// &lt;summary&gt; /// Returns a variant array of the values of the Kvp /// &lt;/summary&gt; /// &lt;returns&gt;Variant Array&lt;/returns&gt; dynamic GetValues(); /// &lt;summary&gt; /// Concatenates the keys to a string /// Will fall over is an element is not a primitive /// &lt;/summary&gt;summary&gt; /// &lt;returns&gt;Keys seperated by seperator&lt;/returns&gt; string GetKeysAsString(string ipSeparator = ","); /// &lt;summary&gt; /// Concatenates the keys to a string /// Will fall over is an element is not a primitive /// &lt;/summary&gt;summary&gt; /// &lt;returns&gt;values seperated by seperator&lt;/returns&gt; string GetValuesAsString(string ipSeparator = ","); /// &lt;summary&gt; /// True if the "Key" exists in the keys of the Kvp /// &lt;/summary&gt; /// &lt;param name="Key"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool HoldsKey(dynamic Key); /// &lt;summary&gt; /// True if the "Value" exists in the values of the Kvp /// &lt;/summary&gt; /// &lt;param name="Value"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool HoldsValue(dynamic Value); /// &lt;summary&gt; /// True if the Kvp holds 0 key/value pairs /// &lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool IsEmpty(); /// &lt;summary&gt; /// True if the Kvp holds one or more key/value pairs /// &lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool IsNotEmpty(); /// &lt;summary&gt; /// True is the "Key" is not found in the keys of the Kvp /// &lt;/summary&gt; /// &lt;param name="Key"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool LacksKey(dynamic Key); /// &lt;summary&gt; /// True if the "Value" is not found in the values of the Kvp /// &lt;/summary&gt; /// &lt;param name="Value"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool LacksValue(dynamic Value); /// &lt;summary&gt; /// Reverses the Key/Value pairs in a Kvp /// &lt;/summary&gt; /// &lt;returns&gt;New Kvp where: /// Kvp.Value(1) = Kvp Unique values as Value/Key pairs /// Kvp.Value(2) = Kvp Non unique values as Key/Value pairs&lt;/returns&gt; Kvp Mirror(); /// &lt;summary&gt; /// Gets the value of the key then deletes the element from MyKvp /// &lt;/summary&gt; /// &lt;param name="ipKey"&gt;&lt;/param&gt; /// &lt;returns&gt;Value at key&lt;/returns&gt; dynamic Pull(dynamic ipKey); /// &lt;summary&gt; /// get the value of the key at the lower bound of array keys /// deletes the elemnt /// &lt;/summary&gt; /// &lt;returns&gt;value at key of lower bound element&lt;/returns&gt; dynamic PullFirst(); /// &lt;summary&gt; /// get the value of the key at the upper bound of array keys /// deletes the element /// &lt;/summary&gt; /// &lt;returns&gt;value at key of upper bound element&lt;/returns&gt; dynamic PullLast(); /// &lt;summary&gt; /// Removes the Key/Value pair spacified by "Key" from the Kvp /// &lt;/summary&gt; void Remove(dynamic Key); /// &lt;summary&gt; /// deletes the element at th key of the lower bound of array MyKvp.keys /// &lt;/summary&gt; void RemoveFirst(); /// &lt;summary&gt; /// deletes the element with the key at the upper bound of array MyKvp.keys /// &lt;/summary&gt; void RemoveLast(); /// &lt;summary&gt; /// Removes all Key/Value pairs from the Kvp /// &lt;/summary&gt; void RemoveAll(); /// &lt;summary&gt; /// Returns true if the Values in Kvp are unique. /// &lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool ValuesAreUnique(); /// &lt;summary&gt; /// Returns true if the Values in Kvp are not unique. /// &lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; bool ValuesAreNotUnique(); } [Guid("434C844C-9FA2-4EC6-AB75-45D3013D75BE")] [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDual)] public class Kvp : IKvp, IEnumerable { private Dictionary&lt;dynamic, dynamic&gt; MyKvp = new Dictionary&lt;dynamic, dynamic&gt;(); public dynamic this[dynamic Key] { get { return MyKvp[Key]; } set { MyKvp[Key] = (dynamic) value; } } public void AddByIndex(dynamic Value) { int my_index = GetNextKvpIndex(); MyKvp.Add(my_index, Value); } public void AddByIndexAsChars(string ipString) { int myIndex = GetNextKvpIndex(); char[] MyArray = ipString.ToCharArray(); for (int i = 0; i &lt;= MyArray.GetUpperBound(0); i++) { //Kvp uses ordinal indexes MyKvp.Add(i + myIndex, MyArray[i].ToString()); } } private int GetNextKvpIndex() { // Can probably do this better by getting the keys, sorting and taking max +1 // but only if the keys are integers if (MyKvp.Count==0) { return 0; } int my_index = MyKvp.Count + 1; while (MyKvp.ContainsKey(my_index)) { my_index++; } return my_index; } public void AddByIndexAsSubStr(string ipString, string ipSeparator = ",") { int my_index = GetNextKvpIndex(); string[] MyArray = ipString.Split(ipSeparator.ToArray()); for (int i = 0; i &lt;= MyArray.GetUpperBound(0); i++) { //Kvp uses ordinal indexes MyKvp.Add(i + my_index, MyArray[i]); } } public void AddByIndexFromArray(dynamic ipArrayrray) { int my_index = GetNextKvpIndex(); dynamic[] myArray = (dynamic)ipArrayrray; for (int i = 0; i &lt;= myArray.GetUpperBound(0); i++) { //Kvp uses ordinal indexes MyKvp.Add(i + my_index, ipArrayrray[i]); } } public void AddByKey(dynamic Key, dynamic Value) { MyKvp.Add(Key, Value); } public void AddByKeyFromArray(dynamic ipArray) { int rowLower = ipArray.GetLowerBound(0); int rowUpper = ipArray.GetUpperBound(0); int colLower = ipArray.GetLowerBound(1); int colUpper = ipArray.GetUpperBound(1); for (int i = rowLower; i &lt; rowUpper; i++) { Kvp thisRow = new Kvp(); for (int j = colLower; j &lt; colUpper; j++) { thisRow.AddByIndex(ipArray[i, j]); } MyKvp.Add(ipArray[i, 1], thisRow); } } public Kvp Cohorts(Kvp ArgKvp) { Kvp ResultKvp = new Kvp(); // VBA reports object not set error if the resuly kvp are not newed for (int i = 1; i &lt; 7; i++) { ResultKvp.AddByKey(i, new Kvp()); } foreach (KeyValuePair&lt;dynamic, dynamic&gt; MyKvpPair in MyKvp) { // A plus unique in B ResultKvp[1].AddByKey(MyKvpPair.Key, MyKvpPair.Value); if (ArgKvp.LacksKey(MyKvpPair.Key)) // problem is here { // In A only or in B only ResultKvp[3].AddByKey(MyKvpPair.Key, MyKvpPair.Value); // In A only ResultKvp[5].AddByKey(MyKvpPair.Key, MyKvpPair.Value); } else { // In A and In B ResultKvp[4].AddByKey(MyKvpPair.Key, MyKvpPair.Value); } } // ArgKvp is a Kvp. The GetEnumerator for ArgKvp returns a Value // and not a key value pair. Therefore we need to iterate over the keys // of ArgKvp foreach (dynamic MyKey in ArgKvp.GetKeys()) { // B in A with different value if (ResultKvp[1].LacksKey(MyKey)) // Result 0 will contain all of A { ResultKvp[1].AddByKey(MyKey, ArgKvp[MyKey]); ResultKvp[3].AddByKey(MyKey, ArgKvp[MyKey]); ResultKvp[6].AddByKey(MyKey, ArgKvp[MyKey]); } else { if (ResultKvp[1][MyKey] != ArgKvp[MyKey]) { ResultKvp[2].AddByKey(MyKey, ArgKvp[MyKey]); } } } return ResultKvp; } public Int32 Count() { return MyKvp.Count; } public Kvp Clone() { Kvp CloneKvp = new Kvp(); foreach (KeyValuePair&lt;dynamic, dynamic&gt; myPair in MyKvp) { CloneKvp.AddByKey(myPair.Key, myPair.Value); } return CloneKvp; } public bool IsEmpty() { return MyKvp.Count == 0; } public bool IsNotEmpty() { return !IsEmpty(); } public IEnumerator GetEnumerator() { foreach (KeyValuePair&lt;dynamic, dynamic&gt; my_pair in MyKvp) { yield return my_pair.Value; } } public dynamic GetKey(dynamic Value) { return this.Mirror()[1][Value]; } public dynamic GetKeys() { return MyKvp.Keys.ToArray(); } public string GetKeysAsString(string ipSeparator = ",") { string myReturn = string.Empty; foreach (KeyValuePair&lt;dynamic, dynamic&gt; myPair in MyKvp) { myReturn += myPair.Key.ToString() + ipSeparator; } return myReturn.TrimEnd(ipSeparator.ToCharArray()); } public dynamic GetFirst() { return MyKvp.First().Value; } public dynamic GetLast() { return MyKvp.Last().Value; } public string GetValuesAsString(string ipSeparator = ",") { string myReturn = string.Empty; foreach (KeyValuePair&lt;dynamic, dynamic&gt; myPair in MyKvp) { myReturn += myPair.Value.ToString() + ipSeparator; } return myReturn.TrimEnd(ipSeparator.ToCharArray()); } public dynamic GetValues() { return MyKvp.Values.ToArray(); } public bool HoldsKey(dynamic Key) { return MyKvp.ContainsKey(Key); } public bool HoldsValue(dynamic Value) { return MyKvp.ContainsValue(Value); } public bool LacksKey(dynamic Key) { return !HoldsKey(Key); } public bool LacksValue(dynamic Value) { return !HoldsValue(Value); } public Kvp Mirror() { Kvp MyResult = new Kvp(); MyResult.AddByKey((int)1, new Kvp()); MyResult.AddByKey((int)2, new Kvp()); foreach (KeyValuePair&lt;dynamic, dynamic&gt; my_pair in MyKvp) { if (MyResult[1].LacksKey(my_pair.Value)) { MyResult[1].AddByKey(my_pair.Value, my_pair.Key); } else { MyResult[2].AddByKey(my_pair.Key, my_pair.Value); } } return MyResult; } public dynamic Pull(dynamic ipKey) { dynamic myValue = MyKvp[ipKey]; MyKvp.Remove(ipKey); return myValue; } public dynamic PullFirst() { dynamic myValue = MyKvp[MyKvp.Keys.ToArray()[0]]; MyKvp.Remove(MyKvp.Keys.ToArray()[0]); return myValue; } public dynamic PullLast() { dynamic[] myKeys = MyKvp.Keys.ToArray(); dynamic myValue = MyKvp[myKeys[myKeys.GetUpperBound(0)]]; MyKvp.Remove(myKeys[myKeys.GetUpperBound(0)]); return myValue; } public void Remove(dynamic Key) { MyKvp.Remove(Key); } public void RemoveFirst() { MyKvp.Remove( MyKvp.Keys.ToArray()[0]); } public void RemoveLast() { dynamic[] myKeys = MyKvp.Keys.ToArray(); MyKvp.Remove(myKeys[myKeys.GetUpperBound(0) ]); } public void RemoveAll() { MyKvp.Clear(); } public bool ValuesAreUnique() { return MyKvp.Count == MyKvp.Values.Distinct().Count(); } public bool ValuesAreNotUnique() { return !ValuesAreUnique(); } } } </code></pre> <p>The VBA code below illustrates the issue when passing a Kvp from one method to another.</p> <pre class="lang-vb prettyprint-override"><code>Option Explicit Sub AssignToKvpItem() Dim myKvp: Set myKvp = New Kvp myKvp.AddByIndex 42&amp; myKvp.AddByIndex 84&amp; Debug.Print myKvp.Item(CLng(1)) Debug.Print myKvp.Item(CLng(2)) myKvp.Item(1&amp;) = 99 Debug.Print myKvp.Item(1&amp;) TestPassedKvpAssignment myKvp End Sub Sub TestPassedKvpAssignment(ByVal ipKvp As Kvp) Debug.Print ipKvp.Item(1&amp;) 'This line produces an error 424 'object required ipKvp.Item(1&amp;) = 1001 ' So 1001 is not assigned Debug.Print ipKvp.Item(1&amp;) Dim myObj As Object: Set myObj = ipKvp 'This line works fine myObj.Item(1&amp;) = 2002 Debug.Print ipKvp.Item(1&amp;) End Sub </code></pre> <p>Below are some Rubberduck unit tests from when I last updated VBA tests for the <code>Kvp</code> class (I hang my head in shame that I am somewhat behind in implementing tests for all methods in the c# code provided above).</p> <pre class="lang-vb prettyprint-override"><code>Option Explicit '@IgnoreModule '@TestModule '@Folder("VBASupport") Private Assert As Rubberduck.AssertClass 'Private Fakes As Rubberduck.FakesProvider '@ModuleInitialize Private Sub ModuleInitialize() 'this method runs once per module. Set Assert = New Rubberduck.AssertClass 'Set Fakes = New Rubberduck.FakesProvider End Sub '@ModuleCleanup Private Sub ModuleCleanup() 'this method runs once per module. Set Assert = Nothing 'Set Fakes = Nothing End Sub ''@TestInitialize 'Private Sub TestInitialize() ''this method runs before every test in the module. 'End Sub ' ' ''@TestCleanup 'Private Sub TestCleanup() ''this method runs after every test in the module. 'End Sub '@TestMethod("Kvp") Private Sub IsObject() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp 'Assert: Assert.AreEqual "Kvp", TypeName(myKvp) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub IsEmpty() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp 'Assert: Assert.AreEqual True, myKvp.IsEmpty TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub IsNotEmpty() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByIndex "Hello World" 'Assert: Assert.AreEqual True, myKvp.IsNotEmpty TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Count() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByIndex "Hello World" 'Assert: Assert.AreEqual 1&amp;, myKvp.Count TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Add_ByIndex() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByIndex "Hello World" 'Assert: Assert.AreEqual "Hello World", myKvp.Item(1&amp;) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Add_ByIndexFromArray() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp Dim MyArray(3) As Variant Dim myResult_Array() As Variant 'Act: MyArray(0) = "Hello" MyArray(1) = True MyArray(2) = 42 MyArray(3) = 3.142 Set myKvp = New Kvp myKvp.AddByIndexFromArray MyArray myResult_Array = myKvp.GetValues 'Assert: Assert.SequenceEquals MyArray, myResult_Array TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Add_ByKey() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) Assert.AreEqual "Hello World", myKvp.Item(22&amp;) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub HoldsKey() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) Assert.AreEqual True, myKvp.HoldsKey(22&amp;) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub HoldsValue() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) Assert.AreEqual True, myKvp.HoldsValue("Hello World") TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub LacksValue() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) Assert.AreEqual True, myKvp.LacksValue(22&amp;) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub LacksKey() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) Assert.AreEqual True, myKvp.LacksKey(80) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Remove() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) If myKvp.LacksKey(22&amp;) Then GoTo TestFail myKvp.Remove 22&amp; Assert.AreEqual True, myKvp.LacksKey(22&amp;) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub RemoveAll() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp.AddByKey Key:=25&amp;, Value:="Hello World 3" 'Assert: 'Debug.Print myKvp.Item(CLng(1)) myKvp.RemoveAll Assert.AreEqual True, myKvp.IsEmpty TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub MakeFromString() On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult1() As Variant Dim myResult2() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=25&amp;, Value:="Hello World 3" Set myKvp2 = New Kvp myResult1 = myKvp1.GetValues myKvp2.AddByIndexAsSubStr "Hello World 1,Hello World 2,Hello World 3" myResult2 = myKvp2.GetValues 'Assert: Assert.SequenceEquals myResult1, myResult2 TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub GetKeys() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp Dim myKvp_keys(2) As Long Dim myResult_keys As Variant 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp.AddByKey Key:=25&amp;, Value:="Hello World 3" myKvp_keys(0) = 22&amp; myKvp_keys(1) = 23&amp; myKvp_keys(2) = 25&amp; myResult_keys = myKvp.GetKeys 'Assert: Assert.SequenceEquals myKvp_keys, myResult_keys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub GetValues() On Error GoTo TestFail 'Arrange: Dim myKvp As Kvp ' Dynamicops integers rather than long Dim myitems(2) As String Dim myKvp_items() As Variant 'Act: Set myKvp = New Kvp myKvp.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp.AddByKey Key:=25&amp;, Value:="Hello World 3" myitems(0) = "Hello World 1" myitems(1) = "Hello World 2" myitems(2) = "Hello World 3" myKvp_items = myKvp.GetValues 'Assert: Assert.SequenceEquals myitems, myKvp_items TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_all_A_with_B_not_input_A() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(7) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 1&amp; myResult_keys(1) = 2&amp; myResult_keys(2) = 3&amp; myResult_keys(3) = 4&amp; myResult_keys(4) = 5&amp; myResult_keys(5) = 6&amp; myResult_keys(6) = 7&amp; myResult_keys(7) = 8&amp; 'Debug.Print myKvp1(1&amp;) 'Debug.Print myKvp1(2&amp;) ' Debug.Print myKvp1(3&amp;) ' Debug.Print myKvp1(4&amp;) ' Debug.Print myKvp1(5&amp;) ' Debug.Print myKvp1(6&amp;) Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(1&amp;).GetKeys ' myCohortKeys = myResult(1&amp;).GetKeys ' myCohortKeys = myResult(2&amp;).GetKeys ' myCohortKeys = myResult(3&amp;).GetKeys ' myCohortKeys = myResult(4&amp;).GetKeys ' myCohortKeys = myResult(5&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys Set myKvp1 = Nothing Set myKvp2 = Nothing Set myResult.Item(0) = Nothing Set myResult.Item(1) = Nothing Set myResult.Item(2) = Nothing Set myResult.Item(3) = Nothing Set myResult.Item(4) = Nothing Set myResult.Item(5) = Nothing TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_B_input_A_with_different_value() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(0) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 3&amp; Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(2&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_input_A_only_and_input_B_only() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(3) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 4&amp; myResult_keys(1) = 5&amp; myResult_keys(2) = 7&amp; myResult_keys(3) = 8&amp; Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(3&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_input_both_A_and_B() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(3) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 1&amp; myResult_keys(1) = 2&amp; myResult_keys(2) = 3&amp; myResult_keys(3) = 6&amp; Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(4&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_input_A_only() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(1) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 4&amp; myResult_keys(1) = 5&amp; Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(5&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Cohorts_input_B_only() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp Dim myResult_keys(1) As Long Dim myResult As Kvp Dim myCohortKeys() As Variant 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=3&amp;, Value:="Hello World 3a" myKvp1.AddByKey Key:=4&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=5&amp;, Value:="Hello World 5" myKvp1.AddByKey Key:=6&amp;, Value:="Hello World 6" Set myKvp2 = New Kvp myKvp2.AddByKey Key:=1&amp;, Value:="Hello World 1" myKvp2.AddByKey Key:=2&amp;, Value:="Hello World 2" myKvp2.AddByKey Key:=3&amp;, Value:="Hello World 3b" myKvp2.AddByKey Key:=6&amp;, Value:="Hello World 6" myKvp2.AddByKey Key:=7&amp;, Value:="Hello World 7" myKvp2.AddByKey Key:=8&amp;, Value:="Hello World 8" myResult_keys(0) = 7&amp; myResult_keys(1) = 8&amp; Set myResult = myKvp1.Cohorts(myKvp2) myCohortKeys = myResult.Item(6&amp;).GetKeys 'Assert: Assert.SequenceEquals myResult_keys, myCohortKeys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub Mirror() 'On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp Dim myKvp2 As Kvp 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=25&amp;, Value:="Hello World 3" myKvp1.AddByKey Key:=26&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=27&amp;, Value:="Hello World 5" Set myKvp2 = myKvp1.Mirror 'Assert: Assert.SequenceEquals myKvp1.GetKeys, myKvp2.Item(1&amp;).GetValues TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod("Kvp") Private Sub ItemsAreUnique() On Error GoTo TestFail 'Arrange: Dim myKvp1 As Kvp 'Act: Set myKvp1 = New Kvp myKvp1.AddByKey Key:=22&amp;, Value:="Hello World 1" myKvp1.AddByKey Key:=23&amp;, Value:="Hello World 2" myKvp1.AddByKey Key:=25&amp;, Value:="Hello World 3" myKvp1.AddByKey Key:=26&amp;, Value:="Hello World 4" myKvp1.AddByKey Key:=27&amp;, Value:="Hello World 5" 'Assert: Assert.AreEqual True, myKvp1.ValuesAreUnique TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T09:52:16.480", "Id": "233671", "Score": "3", "Tags": [ "c#", "beginner", "vba", "interface", "com" ], "Title": "C# Dictionary Wrapper for VBA" }
233671
<p><em>DO NOT RUN THIS EXAMPLE BLINDLY, IT REMOVES ALL FILES UNDER argv[1]</em></p> <p>Hello,</p> <p>This little programm should read all files from a given directory and do some work with them. New files are constantly written into the directory by an outside process. For the duration of the processing, the file should stay in the input directory as it will be processed line by line and not getting loaded into memory all at once. This is also the reason for the <code>process_list</code> member so files don't get processed twice. <code>num_threads</code> will be a runtime variable. For simplicity I hardcoded it now, but that would be the reason for the dynamic allocation. There are some more simplifications, like omitting error checks, checking if the path points to a directory or file, etc, but I think it illustrates all potential issues I could think of.</p> <p>I'd like feedback on the overall approach, if this is a good way to solve the task or if I could do better. Have I forgotten some potential issues (e.g. while writing this I came across iterator invalidation)? Also, any other best practices that I could apply here are also very welcome. Thanks.</p> <pre><code>#include &lt;chrono&gt; #include &lt;csignal&gt; #include &lt;cstdio&gt; #include &lt;mutex&gt; #include &lt;filesystem&gt; #include &lt;thread&gt; #include &lt;vector&gt; volatile std::sig_atomic_t keep_running = 1; static void signal_handler(int sig) { std::fprintf(stderr, "Received signal [%d]. Terminating...\n", sig); keep_running = false; } namespace fs = std::filesystem; class DirectoryView { private: fs::path dir; fs::directory_iterator it; std::mutex mtx; fs::path *process_list; static inline fs::directory_iterator end_it; int process_list_size; void reload(void) { it = fs::directory_iterator(dir); } bool is_in_processing(const fs::path&amp; ret) { for (int i = 0; i != process_list_size; ++i) { if (process_list[i] == ret) return true; } return false; } public: DirectoryView(const char *p, const int num_threads) : dir(p), it(p), process_list_size(num_threads) { process_list = new fs::path[num_threads]; } ~DirectoryView(void) { delete[] process_list; } const fs::path next(const int i) { std::scoped_lock&lt;std::mutex&gt; lock(mtx); for (; it != end_it; ++it) { const fs::path ret(it-&gt;path()); if (is_in_processing(ret)) continue; else { process_list[i] = ret; ++it; // not nice, but prepare for next call to next() so it points to a new directory entry (loop increment is not executed here) return ret; } } reload(); return fs::path(); // Possible improvement: try running next() once more, it is likely there is a new file in the directory for this thread to process } void finished_processing(int i) { process_list[i].clear(); } }; static void process_file(const fs::path&amp; file, const int id) { std::printf("Thread [%d]: Processing file [%s]\n", id, file.string().c_str()); //std::this_thread::sleep_for(std::chrono::seconds(1)); // to illustrate more complex (= longer) processing fs::remove(file); } static void worker(const int id, DirectoryView&amp; dv) { while (keep_running) { const fs::path next = dv.next(id); if (next.empty()) { // FIXME wake up when new files in directory? std::this_thread::sleep_for(std::chrono::seconds(10)); } else { process_file(next, id); dv.finished_processing(id); } } } int main(int argc, char **argv) { if (argc &lt; 2) return 1; std::signal(SIGINT, signal_handler); const int num_threads = 4; DirectoryView dv(argv[1], num_threads); std::vector&lt;std::thread&gt; workers; for (int i = 0; i &lt; num_threads; ++i) { workers.push_back(std::thread(worker, i, std::ref(dv))); } for (auto&amp; w : workers) w.join(); return 0; } </code></pre>
[]
[ { "body": "<p>In all, it's a good effort. Here are some things that may help you improve your program.</p>\n\n<h2>Choose appropriate variable types</h2>\n\n<p>The <code>keep_running</code> flag is a <code>std::sig_atomic_t</code> but since you're using C++17 anyway (for <code>std::filesystem</code>), I'd recommend making that an <code>atomic_bool</code> which more clearly reflects its usage and intent.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>is_in_processing</code> function doesn't (and shouldn't) alter the underlying <code>DirectoryView</code> object, so it should be declared as a <code>const</code> function like this:</p>\n\n<pre><code>bool is_in_processing(const fs::path&amp; ret) const;\n</code></pre>\n\n<h2>Understand differences between C and C++</h2>\n\n<p>I don't know if you come from C or just wanted to be explicit, but this function:</p>\n\n<pre><code>void reload(void) { it = fs::directory_iterator(dir); }\n</code></pre>\n\n<p>could also be declared as</p>\n\n<pre><code>void reload() { it = fs::directory_iterator(dir); }\n</code></pre>\n\n<p>Unlike C, when the argument list is empty in C++, it means the same as <code>void</code>.</p>\n\n<h2>Use the standard library</h2>\n\n<p>The code currently contains this function:</p>\n\n<pre><code>bool is_in_processing(const fs::path&amp; ret) \n{\n for (int i = 0; i != process_list_size; ++i) {\n if (process_list[i] == ret)\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Adding <code>const</code> as mentioned above, this could be very succinctly rewritten using <code>std::any_of</code></p>\n\n<pre><code>bool is_in_processing(const fs::path&amp; ret) const {\n return std::any_of(&amp;process_list[0], &amp;process_list[process_list_size], [ret](const fs::path &amp;p){ \n return p == ret; });\n}\n</code></pre>\n\n<h2>Prefer <code>lock_guard</code> to <code>scoped_lock</code> for single <code>mutex</code></h2>\n\n<p>The essential difference between <code>scoped_lock</code> and <code>lock_guard</code> is that <code>scoped_lock</code> handles the coordination of multiple mutexes. Since you've only got one, it makes sense to use the somewhat simpler <code>lock_guard</code> instead.</p>\n\n<h2>Rethink the architecture</h2>\n\n<p>The current architecture uses multiple threads to process the same directory, but the descriptions seems to imply a desire to process a single directory using multiple threads. The difference is that the current design has multiple threads all processing every file with the result that if we have four threads, we could have the same file processed four or more times. A different design could split up a single directory of files among multiple threads and have only <em>one</em> thread process each file so that each file is only processed once. One way to do that is to have a <code>DirWatcher</code> looking for changes in the directory and then dispatching <code>DirWorker</code>s (possibly in multiple threads) to do the work. Alternatively, have them communicate via a thread-safe work queue and let each <code>DirWorker</code> independently grab an item and process it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:41:58.467", "Id": "456932", "Score": "1", "body": "Thanks for your comments. I read somewhere(just checked, not the C++ core guidelines) that `scoped_lock` is always the better choice over `lock_guard`. I will check if it makes any difference. Regarding a different architecture: Isn't the `directory_iterator` sort of a work queue? Anyway, I'll sure try it out because it sounds much cleaner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:04:00.183", "Id": "456934", "Score": "0", "body": "The advice you read could have been [this SO question](https://stackoverflow.com/questions/43019598/stdlock-guard-or-stdscoped-lock), but I'm unconvinced. Here's why: try leaving out the template argument as in `scope_guard<> lock();` and the same with `lock_guard<> lock()`. Both are errors, but the `scope_guard` version compiles without complaint and creates faulty code while `lock_guard` will not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:06:11.103", "Id": "456935", "Score": "0", "body": "You might correctly note that the programmer made an error, but as one who has actually made that silly error before, I would prefer that the compiler flag it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:17:33.997", "Id": "456939", "Score": "0", "body": "To you question, the `directory_iterator` could be kind of a work queue, except all threads get the same queue. It's true that they attempt to check to see if the file is already in process but it seems a bit cleaner architecturally if they simply get different queues or each grab a single work item at a time from a single queue." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:24:16.797", "Id": "233687", "ParentId": "233679", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T11:47:28.227", "Id": "233679", "Score": "2", "Tags": [ "c++", "multithreading", "file-system", "c++17" ], "Title": "Processing all files in directory" }
233679
<p>I made a 26-bit binary Wiegand calculator for an ESP32 following this format: <a href="https://i.stack.imgur.com/63brZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/63brZ.png" alt="26-Bit Wiegand Format"></a></p> <p>This is "Arduino C" :</p> <pre><code>unsigned int * getWiegand(unsigned int dec) { unsigned int* wiegandNum = new unsigned int[26]; Serial.println(); // transform dec number into binary number and store it in binaryNum[] int n = 1; for(int i = 23; i&gt;=0; i--) { int k = dec &gt;&gt; i; if (k &amp; 1) wiegandNum[n++] = 1; else wiegandNum[n++] = 0; } // check for parity of the first 12 bits bool even = true; for(int i=1;i&lt;13;i++) { if(wiegandNum[i] == 1) { even = !even; } } // add 0 or 1 as first bit (leading parity bit - even) based on the number of ones in the first 12 bits if(even) { wiegandNum[0] = 0; } else { wiegandNum[0] = 1; } // check for parity of the last 12 bits bool odd = false; for(int i=13; i&lt;25;i++) { if(wiegandNum[i] == 1) { odd = !odd; } } // add 0 or 1 as last bit (trailing parity bit - odd) based on the number of ones in the last 12 bits if(odd) { wiegandNum[25] = 0; } else { wiegandNum[25] = 1; } return wiegandNum; } void setup() { Serial.begin(115200); unsigned int* wiegandArray = getWiegand(12679548); for(int i=0;i&lt;26;i++) { Serial.print(wiegandArray[i]); } } </code></pre> <p><code>12679548</code> will return <code>01100000101111001011111000</code> which, based on this <a href="https://pripd.com/tools/cardCalculator.php" rel="nofollow noreferrer">online tool</a> is correct.</p> <p>Execution time for this function is 255 microseconds. I don't know if the time is good or not, but I believe that the code can be improved.</p> <p>What do you think ?</p> <p>References:</p> <ul> <li><a href="https://www.arduino.cc/reference/en/language/structure/sketch/setup/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/structure/sketch/setup/</a></li> <li><a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/print/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/communication/serial/print/</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:11:51.550", "Id": "456852", "Score": "1", "body": "The structure or class Serial is used within the code but is not defined within the question. This code can't be reviewed because it is incomplete. We need to see the declaration and instantiation of the object Serial." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:59:17.610", "Id": "456868", "Score": "1", "body": "@pacmaninbw `Serial.println()` is just like `cout<<endl;`. It's from the ESP32 Core libraries. I have never defined it inside a program. https://www.arduino.cc/reference/en/language/functions/communication/serial/print/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:19:15.337", "Id": "456887", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Be careful when allocating memory with <code>new[]</code> and passing to the caller:</p>\n\n<pre><code>unsigned int * getWiegand(unsigned int dec)\n{\n unsigned int* wiegandNum = new unsigned int[26];\n // ...\n return wiegandNum;\n}\n\nvoid setup()\n{\n unsigned int* wiegandArray = getWiegand(12679548);\n // BUG: never deleted!\n}\n</code></pre>\n\n<p>This is a memory leak. Prefer to use a smart pointer or container instead.</p>\n\n<p>BTW, is it really necessary to use 26 <code>unsigned int</code> values each storing one bit, or could/should you use a more compact representation?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:11:11.380", "Id": "456871", "Score": "0", "body": "I have no idea what's good or not. That program is all my knowledge about C++. I don't know anything about smart pointers or containers. Storing one bit in one `unsigned int` is the only representation I could think off. I need access to every bit for an `if(wiegandArray[0] == 1) {// do something} else if(wiegandArray[0] == 0) {// do something else}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:22:22.987", "Id": "456872", "Score": "0", "body": "I also need the container of the binary number to be re-usable. The program will get an unspecified number of binary numbers that will have to be placed into an array to be manipulated later. Something like this: `unsigned int* wiegandArray;` and then this: `wiegandArray = getWiegand(12679548);` gets called each time a new number is being served. I couldn't put all the code of the project here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:06:30.263", "Id": "233690", "ParentId": "233683", "Score": "4" } }, { "body": "<p>Here are a number of ideas that may help you improve your program.</p>\n\n<h2>Separate calculation from I/O</h2>\n\n<p>The <code>Serial.println();</code> call from within <code>getWeigand</code> really shouldn't be there. It's better if the function does just one thing, and that is to calculate and return the number.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>The code calls <code>new</code> but there isn't any matching <code>delete</code> which means that the program leaks memory. It's better to make sure all memory is freed, but better still, see the next suggestion.</p>\n\n<h2>Avoid using <code>new</code> and <code>delete</code></h2>\n\n<p>Modern C++ doesn't use <code>new</code> and <code>delete</code> as much as it used to. In this case, much better than passing around a raw array pointer and hoping the other end knows what the size is, is to use <code>std::array</code> instead. That is an improvement over a plain array because it works with all of the standard container algorithms and has its own <code>.size()</code> operator. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i13-do-not-pass-an-array-as-a-single-pointer\" rel=\"nofollow noreferrer\">I.13</a> for more details on why passing around a single array pointer is not a good idea.</p>\n\n<h2>Prefer single bit shifting to multi-bit shifting</h2>\n\n<p>Many processors have hardware optimizations for multi-bit shifts, but not all do. That means on some machines, multi-bit shifts take longer. For that reason, and because I think it's more readable, I'd suggest changing the first <code>for</code> loop to this:</p>\n\n<pre><code>for (int i = 24; i &gt; 0; --i) {\n wiegandNum[i] = dec &amp; 1;\n dec &gt;&gt;= 1;\n}\n</code></pre>\n\n<h2>Simplify your code</h2>\n\n<p>Instead of doing things like this:</p>\n\n<pre><code>if(even) {\n wiegandNum[0] = 0;\n} else {\n wiegandNum[0] = 1;\n}\n</code></pre>\n\n<p>just use the value directly:</p>\n\n<pre><code>wiegandNum[0] = !even;\n</code></pre>\n\n<h2>Use whitespace for readability</h2>\n\n<p>Lines like this one:</p>\n\n<pre><code>for(int i=1;i&lt;13;i++) {\n</code></pre>\n\n<p>are much easier to read with a little more whitespace:</p>\n\n<pre><code>for (int i = 1; i &lt; 13; i++) {\n</code></pre>\n\n<h2>Create a test routine</h2>\n\n<p>With code like this, it's usually good to do extensive testing to make sure it does what you intend. I am not using an Arduino, but created a version that runs on Linux (or really any computer that supports C++):</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\nstd::string weiString(unsigned int dec)\n{\n std::string str{};\n auto answer = getWiegand(dec);\n for (const auto digit: answer) {\n str.push_back(digit ? '1' : '0');\n }\n return str;\n}\n\nint main()\n{\n struct {\n unsigned n;\n std::string expected;\n bool operator()() const {\n std::string calculated = weiString(n);\n bool ok{calculated == expected};\n std::cout &lt;&lt; std::hex &lt;&lt; n \n &lt;&lt; std::dec \n &lt;&lt; '\\t' &lt;&lt; expected \n &lt;&lt; '\\t' &lt;&lt; calculated \n &lt;&lt; '\\t' &lt;&lt; (ok ? \"OK\" : \"incorrect!\") \n &lt;&lt; '\\n';\n return ok;\n }\n } tests[]{\n {12679548, \"01100000101111001011111000\" },\n {0xffff, \"00000000011111111111111111\" },\n {0x1ffff, \"10000000111111111111111111\" },\n {0xffffff, \"01111111111111111111111111\" },\n {0xdecade, \"01101111011001010110111101\" },\n {0xfffffff, \"01111111111111111111111111\" }, // ignore high bits\n };\n\n for (const auto&amp; test: tests) {\n test();\n }\n}\n</code></pre>\n\n<h2>Results</h2>\n\n<p>Here's the alternate version that uses these suggestions. It also uses the exclusive-or operator <code>^</code> to simplify parity calculations:</p>\n\n<pre><code>#include &lt;array&gt;\n\nstd::array&lt;unsigned, 26&gt; getWiegand(unsigned int dec)\n{\n std::array&lt;unsigned, 26&gt; wiegandNum;\n for (int i = 24; i &gt; 0; --i) {\n wiegandNum[i] = dec &amp; 1;\n dec &gt;&gt;= 1;\n }\n // check for parity of the first 12 bits\n bool even = false;\n for (int i = 1; i &lt; 13; i++) {\n even ^= wiegandNum[i];\n }\n wiegandNum[0] = even;\n\n // check for parity of the last 12 bits\n bool odd = true;\n for (int i = 13; i &lt; 25; i++) {\n odd ^= wiegandNum[i];\n }\n wiegandNum[25] = odd;\n\n return wiegandNum;\n}\n</code></pre>\n\n<p>Even shorter is to process one of the parity bits over the entire array as it's generated and then recalculate just the other one and adjust. It might be less obvious why this works, but it does. See if you can see why.</p>\n\n<pre><code>std::array&lt;unsigned, 26&gt; getWiegand(unsigned int dec)\n{\n bool odd = true;\n std::array&lt;unsigned, 26&gt; wiegandNum;\n for (int i = 24; i &gt; 0; --i) {\n wiegandNum[i] = dec &amp; 1;\n odd ^= wiegandNum[i];\n dec &gt;&gt;= 1;\n }\n // check for parity of the first 12 bits\n bool even = false;\n for (int i = 1; i &lt; 13; i++) {\n even ^= wiegandNum[i];\n }\n wiegandNum[0] = even;\n wiegandNum[25] = odd ^ even;\n return wiegandNum;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:20:34.123", "Id": "456889", "Score": "0", "body": "Wow. What a great answer. Great tricks with `wiegandNum[0] = even;` and the XOR operator. Can you please explain to me `single bit shifting` ? The `for` changed from this: `for(int i = 23; i>=0; i--)` to this `for (int i = 24; i > 0; --i)`. They don't look alike, yet they function exactly the same. What is this magic ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:23:30.647", "Id": "456890", "Score": "1", "body": "No magic at all. :) Your original code started from the most significant bit while this version starts from the least. The advantage is that we can shift the whole number (`dec >>= 1;`) to the right by one bit each time and just test the low bit with `dec & 1`. It's a pretty common trick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:24:46.313", "Id": "456891", "Score": "0", "body": "I will need to do some reading on that. Some drawings will most certainly help :))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:30:44.873", "Id": "456894", "Score": "1", "body": "Just for fun, I added an even shorter version to my answer at the end, but you'll probably want to think about it for a while to understand why it works." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:52:41.790", "Id": "233694", "ParentId": "233683", "Score": "6" } } ]
{ "AcceptedAnswerId": "233694", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T12:13:57.293", "Id": "233683", "Score": "4", "Tags": [ "c++" ], "Title": "Wiegand 26-Bit Calculator - Transforming a decimal number into an 26-Bit binary number" }
233683
<p>This is my first post here so I hope you will be patient if I'm doing something wrong. I made a small website with create-react-app and I would like to request feedback about. This website was a test and I had a limited amount of time to complete it, hence there are no tests nor license, which for the test purposes weren't necessary.</p> <p>The main things I would like to have feedback on are:</p> <p><strong>1) Are my components organized properly?</strong></p> <p><strong>2) Is the pattern I'm using to develop components appropriate?</strong></p> <p>Although I'm posting here some code, I would like to ask if you could take a quick look at my github repository and let me know what you think about it: <a href="https://github.com/sickdyd/foriio" rel="nofollow noreferrer">https://github.com/sickdyd/foriio</a></p> <p>For the components organization I used the following structure:</p> <p><a href="https://i.stack.imgur.com/jL0Wf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jL0Wf.png" alt="enter image description here"></a></p> <p>To avoid having multiple nested folders, I decided to put all of the sub components that belong to a specific component on the same level. The naming should give away the function, and the folder name has the same name as the main component.</p> <p>One quick question: the component src/components/body/UserProfile/UserWorks.js is reused in src/components/body/UserWork/UserWork.js; is it ok to leave them with this structure?</p> <p>The components generally have the following code structure (this is one of the simplest components):</p> <pre><code>import React from 'react'; import PropTypes from 'prop-types'; import Typography from '@material-ui/core/Typography'; import Skeleton from '@material-ui/lab/Skeleton'; import { makeStyles } from '@material-ui/styles'; const useStyles = makeStyles(theme =&gt; ({ bio: { display: "flex", justifyContent: "center", marginTop: theme.spacing(2), color: theme.palette.text.primary, }, })); export default function UserBio(props){ const classes = useStyles(); const { loading, profile, } = props; return ( loading ? &lt;div className={ classes.bio }&gt; &lt;Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} /&gt; &lt;Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} /&gt; &lt;Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} /&gt; &lt;/div&gt; : &lt;div className={ classes.bio }&gt; &lt;Typography&gt; { profile.bio } &lt;/Typography&gt; &lt;/div&gt; ) } UserBio.propTypes = { loading: PropTypes.bool.isRequired, profile: PropTypes.object, } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:45:12.887", "Id": "456880", "Score": "0", "body": "If you'd like to add more code from your repository to your post, don't hesitate :) Anyways, I think your first post is good, welcome to CR!" } ]
[ { "body": "<p>Your file structure is okay, though it is not the \"conventional\" react folder structure. I personally like your approach better than having lots of nested folders with <code>index.js</code> but this is because my workflow relies on searching files by name, and searching for index.js is impossible — you always have to search by file. </p>\n\n<blockquote>\n <p>One quick question: the component src/components/body/UserProfile/UserWorks.js is reused in src/components/body/UserWork/UserWork.js; is it ok to leave them with this structure?</p>\n</blockquote>\n\n<p>As I understand, UserWorks is some component that shows some sort of preview of works; I think that the structure should be the other way around, <code>UserProfile</code> should depend on <code>UserWorks</code> not the other way around. You might even structure it explicitly that <code>UserProfile</code> and <code>UserWork</code> pages (components) depend on a representation component <code>UserWorks</code>, though naming becomes a bit cumbersome. </p>\n\n<h3>Note on using <code>export default</code></h3>\n\n<p>It seems to be standard \"good\" practice to use <code>export default</code> in Javascript, but I personally don't like it for various reasons and one of them shows in <code>UserWork</code>: you are importing <code>UserWorks</code> as <code>UserRelatedWorks</code> this suggests that <code>UserWorks</code> is used with different intention that is originally designed. Named imports would not eliminate this issue completely but would at least force explicit statement <code>import {UserWorks as UserRelatedWorks} from …</code> </p>\n\n<h3>Comments on the code:</h3>\n\n<ol>\n<li><p>lots of unnecessary empty lines, this is a bit unusual. In most cases empty lines are used to group statements together, here they appear to be random and make code harder to read.</p></li>\n<li><p>you are using classes for <code>div.bio</code> but not for <code>Skeleton</code> though those styles are repeated but bio is not (or should not be) </p></li>\n<li><p>no matter value of <code>loading</code> you are returning a container with <code>&lt;div className={classes.bio}&gt;</code>, you can return container and resolve content inside of it based on the <code>loading</code> to avoid duplication.</p></li>\n</ol>\n\n<hr>\n\n<p>In this code <code>filter</code> method is used incorrectly, the callback should return boolean but in this case returns the object itself or null, this relies on implicit type casting to truthy value and is very confusing</p>\n\n<pre><code> works.filter(w =&gt; {\n\n if ((!category) || (category === \"all\")) {\n return w;\n }\n else {\n if (w.category_list.includes(category)) return w;\n }\n\n return null;\n\n })\n</code></pre>\n\n<p>this code should be </p>\n\n<pre><code>works.filter(work =&gt; !category || category === 'all' || w.category_list.includes(category))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T23:57:49.100", "Id": "456957", "Score": "0", "body": "Thank you for your feedback! I edited the code. I usually add white lines because it helps me read through the code, but I see your point. If the standard is to not have them I will clear them out and make the code more compact." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:30:06.570", "Id": "233709", "ParentId": "233685", "Score": "3" } } ]
{ "AcceptedAnswerId": "233709", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T12:56:33.183", "Id": "233685", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "ReactJS, Material UI component and code organization" }
233685
<p>This is my script. I want it to run on a weekly basis on my linux server on a Raspberry Pi 4, to back up all files that may have changed. On the GPIO are just LEDs. It requires a program called notify_run, and a file called "BackupSettings.ini" in its own directory that looks like this:</p> <pre class="lang-none prettyprint-override"><code>[Sources] Folder1=/home/pi/Desktop/Scripts/test/BackupTestEnvironment/Original Drive [Destinations] Folder1=/home/pi/Desktop/Scripts/test/BackupTestEnvironment/Backup Drive </code></pre> <p>...and can have multiple pairs of folders I would like to hear some suggestions to improve it, since im a bloody beginner, so please be patient with me :)</p> <p>Here comes the main Code:</p> <pre><code>"""Import""" import RPi.GPIO as GPIO import shutil, os, hashlib, json, subprocess from configparser import ConfigParser from datetime import date from operator import itemgetter """Init""" config = ConfigParser() config.read('BackupSettings.ini') Sources = dict(config.items('Sources')) Destinations = dict(config.items('Destinations')) Indexnew = [] Indexold = {} DeletedFiles = [] today = date.today().strftime("%Y_%m_%d") GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.OUT) GPIO.setup(21, GPIO.OUT) """Def""" def CreateNewIndex(): global Indexnew for path, dirs, files in os.walk(Source): for file in files: filepath = path+"/"+file sha512_hash = hashlib.sha512() with open(filepath,"rb") as f: for byte_block in iter(lambda: f.read(4096),b""): sha512_hash.update(byte_block) hashsum = sha512_hash.hexdigest() x, filepath = path.split(Source, 1) filepath = filepath+"/" data = {'Name': file, 'Path': filepath, 'Hashsum': hashsum} Indexnew.append(data) with open(Destination+"/"+today+".json", 'w+') as jsonout: json.dump(Indexnew,jsonout) def ImportOldIndexes(): global Indexold files = [f for f in os.listdir(Destination) if os.path.isfile(os.path.join(Destination,f))] if today+".json" in files: files.remove(today+".json") files.sort() for file in files: filepath = Destination+"/"+file Indexold[file] = json.load(open(filepath, "r")) def Compare(): keys = list(Indexold.keys()) keys.sort() global Indexnew global DeletedFiles if Indexold: for x in Indexold[keys[-1]]: counter = 0 for y in Indexnew: if itemgetter('Name', 'Path', 'Hashsum')(x) == itemgetter('Name', 'Path', 'Hashsum')(y): y['Change'] = 'unchanged' elif itemgetter('Name', 'Hashsum')(x) == itemgetter('Name', 'Hashsum')(y): y['Change'] = 'moved' elif itemgetter('Path', 'Hashsum')(x) == itemgetter('Path', 'Hashsum')(y): y['Change'] = 'renamed' elif itemgetter('Name', 'Path')(x) == itemgetter('Name', 'Path')(y): y['Change'] = 'newversion' else: counter = counter + 1 if counter == len(Indexnew): DeletedFiles.append(x) with open(Destination+"/DeletedFiles/"+today+".json", 'w+') as jsonout: json.dump(DeletedFiles,jsonout) for x in Indexnew: counter = 0 for y in Indexold[keys[-1]]: if not itemgetter('Name', 'Path', 'Hashsum')(x) == itemgetter('Name', 'Path', 'Hashsum')(y): if not itemgetter('Name', 'Hashsum')(x) == itemgetter('Name', 'Hashsum')(y): if not itemgetter('Path', 'Hashsum')(x) == itemgetter('Path', 'Hashsum')(y): if not itemgetter('Name', 'Path')(x) == itemgetter('Name', 'Path')(y): counter = counter + 1 if counter == len(Indexold[keys[-1]]): x['Change'] = 'new' with open(Destination+"/"+today+".json", 'w+') as jsonout: json.dump(Indexnew,jsonout) def Execute(): error = 0 for x in Indexnew: if x['Change'] == 'new' or x['Change'] == 'moved' or x['Change'] == 'renamed' or x['Change'] == 'newversion': Copyfrom = Source+x['Path']+x['Name'] Copyto = Destination+"/"+today+x['Path'] if not os.path.exists(Copyto): os.makedirs(Copyto) shutil.copy(Copyfrom, Copyto) sha512_hash = hashlib.sha512() with open(Copyto+x['Name'],"rb") as f: for byte_block in iter(lambda: f.read(4096),b""): sha512_hash.update(byte_block) hashsum = sha512_hash.hexdigest() if not hashsum == x['Hashsum']: error = error + 1 print("Error") if error == 0: print("Success") else: print("Error") GPIO.output(21, True) notify = subprocess.Popen(["notify-run", "send", '"Error during Backup"'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) """Run""" count = 0 for amount in Sources.values(): count = count + 1 Source = Sources["folder"+str(count)] Destination = Destinations["folder"+str(count)] GPIO.output(20, True) CreateNewIndex() ImportOldIndexes() Compare() Execute() GPIO.output(21, False) </code></pre> <p>I really hope I did not make any misstakes formating it after pasting it in here.</p> <p>edit: I forgot to mention that it gets called by crontab</p> <p>edit: It is supposed to run over critical data and it should be as failproof as possible, thats why i used sha512 instead of md5. Also, it should be capable to handle any kind of file it gets hit with. If you have any ideas on additional safety mechanisms, please tell me. The input will contain about 2 TB of Files, reaching from 1kb to 200GB each. I am the only one using it.</p>
[]
[ { "body": "<h1>Style</h1>\n\n<p>Python has an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>, that most programmers tend to follow, although it was originally only written for the standard library strictly speaking. It's worth a read.</p>\n\n<p>The easiest first step to bring your code more in line with the style guide would be to change function and variable names to the usual <code>lowercase_with_underscores</code>.</p>\n\n<p>Constant values, e.g. <code>today</code> for the sake of this program, are usually named with <code>ALL_UPPERCASE_WITH_UNDERSCORES</code>.</p>\n\n<p>Luckily, there is a <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">variety of tools readily available</a> to help you with checking and (auto)fixing some/most of those issues.</p>\n\n<h1>Global variables</h1>\n\n<p>Global variables are usually best to be avoided, since they make it hard(er) to track where which parts of your program state are altered. To get rid of them, you will have to rewrite your functions to accept the relevant inputs as parameter and actually return the (modified) values you are going to work with. An example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def create_new_index(source):\n index_new = []\n # _ is commonly used for \"don't care\" values\n for path, _, files in os.walk(source):\n ...\n\n return index_new\n</code></pre>\n\n<p>I chose to only pass <code>source</code> as argument to the function and also changed it's name since I would also recommend to not write the data in that function. This is not strictly necessary, but helps to keep your functions manageable since they have only a <a href=\"https://dev.to/skill_pathway/single-responsibility-principle-for-dummies-59gb\" rel=\"nofollow noreferrer\">limited responsibility</a>.</p>\n\n<h1>Loop like a native</h1>\n\n<p>Instead of </p>\n\n<blockquote>\n<pre><code>count = 0\nfor amount in Sources.values():\n count = count + 1\n Source = Sources[\"folder\"+str(count)]\n Destination = Destinations[\"folder\"+str(count)]\n</code></pre>\n</blockquote>\n\n<p>where <code>amount</code> is never used, you can use <code>enumerate(...)</code> like so</p>\n\n<pre><code>for count, _ in enumerate(Sources.values(), 1):\n source = Sources[f\"folder\" + str(count)]\n destination = Destinations[\"folder\" + str(count)]\n new_index = create_new_index(source)\n</code></pre>\n\n<p>or if you don't care about the specific order of the folders, just use</p>\n\n<pre><code>for key, source in Sources.items():\n destination = Destinations[key]\n new_index = create_new_index(source)\n</code></pre>\n\n<p>As a bonus the last version also allows you to get rid of keys that have to follow a strict <code>FolderX</code> pattern on the keys/folder names in your config files.</p>\n\n<h1><code>itemgetter</code> and matching</h1>\n\n<p><code>itemgetter</code>s can be reused. </p>\n\n<pre><code>get_nph = itemgetter('Name', 'Path', 'Hashsum')\nget_nh = itemgetter('Name', 'Hashsum')\n...\nif get_nph(x) == get_nph(y):\n # ... do something\nelif get_nh(x) == get_nh(y):\n # ... do something\n# and so on\n</code></pre>\n\n<p>Defining a reusable <code>itemgetter</code> function for each parameter combination you are using is the most straightforward transformation of your code as shown in your question. In your original code you declared a new <code>itemgetter</code> function whenever you needed one. That is unnecessary as the example above shows.</p>\n\n<p>But the code can work without itemgetters altogether, since all you do is compare three attributes of your file for equality and then act accordingly. An alternative implementation of the same approach might look like:</p>\n\n<pre><code>names_match = x['Name'] == y['Name']\npaths_match = x['Path'] == y['Path']\nhashsums_match = x['Hashsum'] == y['Hashsum']\nif names_match and paths_match and hashsums_match:\n y['Change'] = 'unchanged'\nelif names_match and hashsums_match:\n y['Change'] = 'moved'\nelif paths_match and hashsums_match:\n y['Change'] = 'renamed'\nelif names_match and paths_match:\n y['Change'] = 'newversion'\nelse:\n # ...\n</code></pre>\n\n<p>I'd tend to say this is more readable. But that might be a matter of taste.</p>\n\n<h1>Handling paths</h1>\n\n<p>Instead of manually concatenating paths like <code>Destination + \"/\" + TODAY + x['Path']</code>, you can use <code>os.path.join(...)</code> like <code>os.path.join(destination, TODAY, x['Path'])</code>. An other advantage of this function is that it takes care to use the \"correct\" OS specific separator (i.e. <code>\\</code> on Windows, <code>/</code> on Linux), although this not strictly necessary here since the target is Linux only.</p>\n\n<p>Python 3 also offers the <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>PathLib</code></a> module, which makes working with paths, and parts thereof, a little bit more convenient. Maybe have a look at it if you plan to rework your script or for future projects.</p>\n\n<h1>Running the script</h1>\n\n<p>You have marked the portion of your script that is supposed to run on execution with a block comment, <code>\"\"\"Run\"\"\"</code>. That might work for a person looking at your code, but the interpreter does not care to much about it. If you ever would try to <code>import</code> a function from your script because you want to reuse it, the back-up routine will be triggered.</p>\n\n<p>Instead <code>if __name__ == \"__main__\":</code> should be used to (also) tell the interpreter <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">which parts of the file are supposed to be run as script</a>. There is also a <a href=\"https://stackoverflow.com/a/419185/5682996\">nice explanation over at Stack Overflow</a>.</p>\n\n<pre><code>if __name__ == \"__main__\":\n config = ConfigParser()\n config.read('BackupSettings.ini')\n sources = dict(config.items('Sources'))\n destinations = dict(config.items('Destinations'))\n for key, source in sources.items():\n destination = destinations[key]\n new_index = create_new_index(source)\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T10:42:16.493", "Id": "457017", "Score": "0", "body": "Thanks a lot! This is insanely helpful :) What I don´t really understand tho: what do you mean by reusing itemgetter. What I want to express there is I want to determine in which way the values change. I found that a file should be the same if at least 2 of these 3 values are the same. Depending on those values i can see then what kind of change it is. How can I do this by reusing the itemgetter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:00:39.867", "Id": "457021", "Score": "0", "body": "Oh, and I got a technikal question: What happens if the Lists get too long to fit into the 4 GB RAM? Is that even possible (realisticly)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:59:09.293", "Id": "457025", "Score": "0", "body": "I rewrote the `itemgetter` part. Is it clearer now? Regarding your other question, I'd say that its not that easy to calculate. The only thing that one can easily calculate is how much memory the hex representation of all the hashes would take. But then there are the names, paths, and a non-negligible overhead for datatypes in Python as (partial) \"unknowns\". An educated guess would be, that you'd need (lower) 10's of millions of files to fill the RAM on your Pi. But don't quote me on that ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:50:59.280", "Id": "457037", "Score": "0", "body": "Ah, thanks, that is WAY better than my approach :) When im back home i will rework my script and maby I´ll paste my results here in case someone has a similar project, or there are other recommendations then :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:39:24.597", "Id": "457062", "Score": "0", "body": "I just saw on another post about parallelization, and i wonder if it makes sense to use something like the multiprozessing module or the joblib module?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:57:35.707", "Id": "457067", "Score": "0", "body": "For example building the index should be easy to parallelize. It all depends on how you want to use your system. If the back-up has top priority and everything else can wait, then you're free to go and use all of your Pi's resources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:31:10.680", "Id": "457072", "Score": "0", "body": "Allright, i think i will do so, as the backup runs during the night. Thanks again for all the efford you´ve put into me and my work :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:46:32.920", "Id": "233724", "ParentId": "233689", "Score": "3" } } ]
{ "AcceptedAnswerId": "233724", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:47:27.740", "Id": "233689", "Score": "6", "Tags": [ "python", "python-3.x", "linux" ], "Title": "A Backup Script for my Linux Server/NAS" }
233689
<p>I displayed and styled the chart.js and am also using mock data in the array, I just can't get my head around how to populate the data in the chart.js using MVC 5. I have tried lots of different methods and it's displaying data but not displaying the chart. Ideally, I need two datasets; one is for the weekly expense and one for the monthly expense. If anyone can suggest or point me in the right direction it would be much appreciated.</p> <p><strong>Index.cshtml</strong></p> <pre><code> &lt;div style="width: 80%;"&gt; &lt;canvas id="barChart" heigh="400" width="400"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;script&gt; var chart = document.getElementById("barChart").getContext('2d'); Chart.defaults.global.animation.duration = 2000; var barChart = new Chart(chart, { type: 'bar', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], datasets: [{ label: 'Weekly Expenses', fill: true, barTension: 0.1, borderColor: '#2C3E50', borderWidth: 2, borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "#2C3E50", pointBackgroundColor: "#fff", pointBorderWidth: 2, pointHoverRadius: 8, pointHoverBackgroundColor: "#2C3E50", pointHoverBorderColor: "#2C3E50", pointHoverBorderWidth: 5, pointRadius: 10, PointHitRadius:10, data: [20,30,40,50,60,70,80,90,100,120,140,50] }, { label: 'Monthly Expenses', fill: true, barTension: 0.8, backgroundColor: '#2C3E50', borderColor: '#f0c419', borderWidth: 2, borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "#f0c419", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "#f0c419", pointHoverBorderColor: "#f0c419", pointHoverBorderWidth: 2, pointRadius: 1, PointHitRadius:1, data: /*[10,20,30,40,50,60,70,80,90,100,110,120]*/ data } ] }, options: { scales: { yAxes: [ { ticks: { beginAtZero: true, }, }] } } }); &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T07:23:52.367", "Id": "457339", "Score": "0", "body": "Hi. If your code is not finished - perhaps the quesion belongs to stackoverflow? Here on code-review the aim is to work on working code to improve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:13:04.520", "Id": "457353", "Score": "0", "body": "Hi @jakubiszon the code is finished and it works perfectly that's what I need improvement." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:05:17.693", "Id": "233695", "Score": "0", "Tags": [ "c#", "sql-server", "asp.net-mvc-5" ], "Title": "Chart.js - Getting data from database using sql server and asp.net mvc5" }
233695
<p>I've tried to solve AoC day 2 challenge in Haskell (<a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">here</a> - don't worry, it's not a competition so sharing a solution here is OK).</p> <p>The goal is to implement a very simple VM with opcodes 1 (add), 2 (mult) and 99 (exit).</p> <p>I feel like my solution is incredibly verbose. That maybe be because I rely heavily on the state monad (my background is imperative programming, so there's that). Is there anything I could improve without rewriting the whole solution?</p> <p>Here's my code, thanks for all suggestions: </p> <pre class="lang-hs prettyprint-override"><code>import Data.Sequence import Control.Monad.State import Data.List.Split data Machine = Machine { mState :: Seq Int, mPos :: Int, isDone :: Bool } opReadHead :: State Machine Int opReadHead = do machine &lt;- get return $ index (mState machine) (mPos machine) opReadAt :: Int -&gt; State Machine Int opReadAt target = do machine &lt;- get return $ index (mState machine) target opForward :: State Machine () opForward = do machine &lt;- get put $ machine { mPos = mPos machine + 1 } opWrite :: Int -&gt; Int -&gt; State Machine () opWrite target what = do machine &lt;- get put $ machine { mState = update target what (mState machine) } opReadNext :: State Machine Int opReadNext = do a &lt;- opReadHead opForward return a opAdd :: State Machine () opAdd = do aPtr &lt;- opReadNext a &lt;- opReadAt aPtr bPtr &lt;- opReadNext b &lt;- opReadAt bPtr target &lt;- opReadNext opWrite target (a + b) opMult :: State Machine () opMult = do aPtr &lt;- opReadNext a &lt;- opReadAt aPtr bPtr &lt;- opReadNext b &lt;- opReadAt bPtr target &lt;- opReadNext opWrite target (a * b) opExit :: State Machine () opExit = do current &lt;- get put $ current { isDone = True } isMachineDone :: State Machine Bool isMachineDone = do get &gt;&gt;= (return . isDone) opcode :: Int -&gt; State Machine () opcode 1 = opAdd opcode 2 = opMult opcode 99 = opExit opExecuteNext :: State Machine () opExecuteNext = do opValue &lt;- opReadNext opcode opValue runCode :: State Machine () runCode = do done &lt;- isMachineDone if done then return () else opExecuteNext &gt;&gt; runCode evalWith :: Machine -&gt; Int -&gt; Int -&gt; Int evalWith machine noun verb = do fst $ runState (do opWrite 1 noun opWrite 2 verb runCode opReadAt 0 ) machine main :: IO() main = do fileData &lt;- readFile "input" let memory = map read $ splitOn "," fileData let machine = Machine { mState = fromList memory, mPos = 0, isDone = False } let outputs = [(evalWith machine x y, (x, y)) | x &lt;- [0..99], y &lt;- [0..99]] print $ snd $ head $ Prelude.filter ((== 19690720) . fst) outputs <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Use <code>Control.Lens</code> for code this stateful. (<code>Control.Lens.TH</code> must be used to define <code>Machine</code>.) May as well leave out type signatures this homogenous. <code>Control.Monad.Loops</code> often helps against explicit monadic recursion.</p>\n\n<pre><code>opReadAt target = uses mState $ (`index` target)\nopReadNext = mPos &lt;&lt;+= 1 &gt;&gt;= opReadAt\nopWrite target what = mState %= update target what\n\nopBin op = do\n a &lt;- opReadNext &gt;&gt;= opReadAt\n b &lt;- opReadNext &gt;&gt;= opReadAt\n target &lt;- opReadNext\n opWrite target $ op a b \n\nopcode 1 = opBin (+)\nopcode 2 = opBin (*)\nopcode 99 = isDone .= True\n\nrunCode = (opReadNext &gt;&gt;= opCode) `untilM_` use isDone\n\nevalWith :: Int -&gt; Int -&gt; Machine -&gt; Int\nevalWith noun verb = evalState $ do\n opWrite 1 noun\n opWrite 2 verb\n runCode\n opReadAt 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:55:21.527", "Id": "457784", "Score": "0", "body": "I'm very curious how you could improve it using a Lens but the documentation for that is very useless for somebody new. Could you given an example of how it would work?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:26:03.737", "Id": "233708", "ParentId": "233696", "Score": "4" } }, { "body": "<p>Thanks for this, I used your example to finish mine that also uses <code>State</code>:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import System.IO\nimport Data.Sequence\nimport Control.Monad.State\nimport qualified Data.Text as T\nimport Data.Maybe\n\nconvertToInteger :: String -&gt; Int\nconvertToInteger s = read s :: Int\n\ntype CompState = (Int, Seq Int)\ntype CompValue = Int\n\ndata Instruction = Add | Mult | Stop deriving (Show)\n\ninstruction :: State CompState Instruction\ninstruction = state $ \\(pointer, mem) -&gt;\n (case (Data.Sequence.lookup pointer mem) of\n Just 1 -&gt; Add\n Just 2 -&gt; Mult\n Just 99 -&gt; Stop\n _ -&gt; Stop\n , (pointer, mem))\n\ncalcul :: (Int -&gt; Int -&gt; Int) -&gt; State CompState ()\ncalcul operator = state $ \\(pointer, mem) -&gt;\n let addr1 = Data.Sequence.lookup (pointer+1) mem\n addr2 = Data.Sequence.lookup (pointer+2) mem\n op1 = join $ Data.Sequence.lookup &lt;$&gt; addr1 &lt;*&gt; pure mem\n op2 = join $ Data.Sequence.lookup &lt;$&gt; addr2 &lt;*&gt; pure mem\n destAddr = Data.Sequence.lookup (pointer+3) mem \n val = (operator &lt;$&gt; op1 &lt;*&gt; op2)\n newMem = Data.Sequence.update &lt;$&gt; destAddr &lt;*&gt; val &lt;*&gt; pure mem in\n ((), (pointer+4, fromJust newMem))\n\ncomputeStep :: State CompState ()\ncomputeStep = do\n inst &lt;- instruction\n\n _ &lt;- case inst of\n Add -&gt; calcul (+) &gt;&gt; computeStep\n Mult -&gt; calcul (*) &gt;&gt; computeStep\n Stop -&gt; return ()\n\n return ()\n\na = [1,0,0,0,99]\nb = [2,3,0,3,99]\nc = [2,4,4,5,99,0] \nd = [1,1,1,4,99,5,6,0,99]\n\nmain :: IO()\nmain = do\n handle &lt;- openFile \"2-input.txt\" ReadMode\n contents &lt;- hGetContents handle\n\n let inputData = fromList . map convertToInteger . map T.unpack $ T.splitOn (T.pack \",\") (T.pack contents)\n let updatedInputData = update 2 2 (update 1 12 inputData)\n\n print $ snd $ snd $ runState computeStep (0, updatedInputData)\n</code></pre>\n\n<p>Is it shorter or does it only look like it?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T15:21:12.857", "Id": "461005", "Score": "0", "body": "`instruction` should be written in terms of `gets`. `calcul` in terms of `modify`. `Instruction` is superfluous. So's the `Just 99` case. Don't use `Maybe` if you're merely gonna `fromJust`. `snd $ runState` -> `evalState`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T20:27:25.140", "Id": "461040", "Score": "0", "body": "Thanks for your additions which are barely understandable since I could only just get this State thing to work (almost no documentation) and have after this experience moved on from Haskell." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:54:20.807", "Id": "234088", "ParentId": "233696", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:42:58.363", "Id": "233696", "Score": "5", "Tags": [ "haskell" ], "Title": "Advent of code #2 Haskell solution" }
233696
<p>Following scenario: this is the code that resides in Ajax Controller class. It is responsible for handling input in one of the form fields.</p> <p>The logic is as follows:</p> <p>If user-inputted data validate as either Tax Number or Statistical Number, it's supposed to: check for presence of such data in database, and, depending on the result, either make a call to external API (in case DB query is empty) or present the results (in case of input being found in database).</p> <p>If user-inputted data doesn't validate as either Tax or Statistical Number, it is supposed to perform DB query with input treated as the customer name.</p> <p>Below code works as expected. However, it is long and I was forced to repeat some parts. I'm looking to cut down on lines while preserving exact same logic, but I'm highly unsure as to how to make it even more compressed.</p> <pre><code>class AjaxController { public function customerslistAction() { $filterChain = new Zend_Filter(); $filterChain-&gt;addFilter(new Zend_Filter_Digits()) -&gt;addFilter(new Zend_Filter_Null()); $input = $filterChain-&gt;filter($this-&gt;getRequest()-&gt;getParam('name')); $collection = new Def_Model_Collection_Customer(); /* check if $input is TaxNumber */ if (SugApi::isTaxNumber($input)) { $data['tax_number'] = $input; $allFound = $collection-&gt;findByTaxOrStatistical($data); // check and return customer with this TAX_NUMBER if it is in database if (count(($allFound)) &gt; 0) { echo Zend_Json::encode($allFound); return; } // call external api if it isn't in database [catch NotFound Exception] else { try { $sugReport = SugApi::getByTaxNumber($input); } catch (\SugApi\Exception\NotFoundException $e) { $out['results'][] = array('value' =&gt; 'Unknown tax number.'); echo Zend_Json::encode($out); return; } } } /* check if $input is StatisticalNumber */ else if (SugApi::isStatNumber($input)) { $data['stat_number'] = $input; $allFound = $collection-&gt;findByTaxOrStatistical($data); // check and return customer with this STATISTICAL_NUMBER if it is in database if (count($allFound) &gt; 0) { echo Zend_Json::encode($allFound); return; } // call external api if it isn't in database [catch NotFound Exception] else { try { $sugReport = SugApi::getByStatNumber($input); } catch (\SugApi\Exception\NotFoundException $e) { $out['results'][] = array('value' =&gt; 'Unknown statistical number.'); echo Zend_Json::encode($out); return; } } } // if $input is neither TAX_NUMBER nor STATISTICAL_NUMBER, // query database for customer with $input as customer_name else { $collection = new Def_Model_Collection_Customer(); $data = $collection-&gt;fetchAll(array('name' =&gt; $this-&gt;getRequest()-&gt;getParam('name'))); $out = array(); foreach ($data as $val) { $out['results'][] = array( 'id' =&gt; $val['customer_id'], 'value' =&gt; $val['customer_name'], 'info' =&gt; 'Tax Number: '.$val['customer_tax_number'] ); } $json = Zend_Json::encode($out); echo $json; return; } // parse successful external api response into Customer object and save it $customer = new Def_Model_Customer(); $customer-&gt;setOptionsFromSugReport($sugReport); $customer-&gt;save(); $out['results'][] = array( 'id' =&gt; $customer-&gt;customer_id, 'value' =&gt; $customer-&gt;customer_name, 'info' =&gt; 'Tax Number: '.$customer-&gt;customer_tax_number ); echo Zend_Json::encode($out); } } </code></pre>
[]
[ { "body": "<p>If you don't want to repeat yourself (DRY) then consider using multiple methods, and set properties ($this->collection) and/or pass parameters, as necessary. If you are finding yourself nesting if statements inside a method, it is a good indication that you should be using multiple methods.</p>\n\n<p>For example, for your method, it looks like you could cut the database check into their own method.</p>\n\n<p>If you have a return, then there is no need for an else statement :-) </p>\n\n<pre><code>if($a){\n return;\n}\n// no need for else\n</code></pre>\n\n<p>There is no point in setting a variable $json and echo it, just echo it as you did most of the time, but not all.</p>\n\n<p>It looks as though you could break the rest response into it's own method for example with the if count > 0 return true or false to determine the action.</p>\n\n<pre><code>private function method($results){\n if (count(($results)) &gt; 0) {\n echo Zend_Json::encode($result);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Check out this video \"Your code sucks, let's fix it - By Rafael Dohms\" to help with understanding the above.\n<a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=GtB5DAfOWMQ</a></p>\n\n<p>I hope this is helpful!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:02:21.600", "Id": "457027", "Score": "1", "body": "Hi and thanks for your time and input. \nA great remark about the return's and else's - seems I have a bad habit of doing that. I did cut them down now. Seeing your profile picture I feel like I can ask this:\nthe lines with $out['results']: they're both in the code I've put here, but also in findByTaxOrStatistical() collection method, which isn't shown here.\nWhich place would be best to handle such 'representation formatting'?\nWould it be model class? Mapper class? Or just leave it as it is? Is there a general rule to it ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:34:31.810", "Id": "457034", "Score": "0", "body": "It seems like what your doing is creating a REST response. You should understand that is more than outputting JSON. There is also a status code, like 200, that should be set. There are lots of simple REST response libraries out there, and you may want to look at calling one of them rather than echoing JSON, I would say that is a best practice. (also, so it's been said here, done the exact same things wrong, equal learning partner)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:59:38.270", "Id": "457041", "Score": "0", "body": "The functionality you speak about is handled in SugApi service. I did not put its code here, as it wasn't part of the problem that I wanted to solve. The only exception not covered directly by SugApi is visible in the first post (that is, NotFoundException)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:23:51.200", "Id": "233742", "ParentId": "233697", "Score": "1" } } ]
{ "AcceptedAnswerId": "233742", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:44:36.577", "Id": "233697", "Score": "2", "Tags": [ "php" ], "Title": "multiple if statements \"forced\" by database query result & external api response" }
233697
<p>I am looking for a cleaner, more pythonic way to get a list of the name of the months starting with the current month and ending 12 months later.</p> <p>For example, it's December so my list should be </p> <pre class="lang-py prettyprint-override"><code>['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'] </code></pre> <p>Here is how I'm currently doing it:</p> <pre><code>from datetime import datetime currentMonth = datetime.now().month if (currentMonth == 1): theList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] elif (currentMonth == 2): theList = ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan'] elif (currentMonth == 3): theList = ['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb'] elif (currentMonth == 4): theList = ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'] elif (currentMonth == 5): theList = ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr'] elif (currentMonth == 6): theList = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May'] elif (currentMonth == 7): theList = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] elif (currentMonth == 8): theList = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] elif (currentMonth == 9): theList = ['Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'] elif (currentMonth == 10): theList = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'] elif (currentMonth == 11): theList = ['Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'] elif (currentMonth == 12): theList = ['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'] print(theList) </code></pre> <p>Ideas?</p>
[]
[ { "body": "<p>You can work with a single list\n<code>theList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']</code></p>\n\n<p>What you want to do is to start with a certain index and then add 12 elements to a list while you have <code>index%12</code>. So you can do something like</p>\n\n<pre><code>from datetime import datetime\n\ntheList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nmonth = datetime.now().month\nnewList = list()\nfor i in range(12):\n newList.append(theList[(month-1+i)%12])\n\nprint(newList)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:02:43.520", "Id": "233700", "ParentId": "233698", "Score": "2" } }, { "body": "<p>First of call, <code>theList</code> is not a good name for that variable. You can be much more specific in your case! I'd suggest <code>months</code>.</p>\n\n<p>Also, there is no need to have all of those lists hard-coded in your script. Use a single instance of that list, and then create modified versions as you need them.</p>\n\n<p>Edit: I was absolutely sure that there has to be a Python library that has the names already covered, but failed to find it. <a href=\"https://codereview.stackexchange.com/a/233705/92478\">RomanPerekhrest</a> beat me here and correctly identified <a href=\"https://docs.python.org/3/library/calendar.html#calendar.month_abbr\" rel=\"noreferrer\"><code>calendar.month_abbr</code></a> as the way to go.</p>\n\n<p>A <a href=\"https://realpython.com/list-comprehension-python/\" rel=\"noreferrer\">list comprehension</a> like below could to the trick:</p>\n\n<pre><code>months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\ncurrent_month = datetime.now().month - 1\nprint([months[(current_month + i) % 12] for i in range(12)])\n</code></pre>\n\n<p>Or you can use <a href=\"https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html\" rel=\"noreferrer\">slicing</a> to get it even more comfortable:</p>\n\n<pre><code>months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\ncurrent_month = datetime.now().month - 1\nprint(months[current_month:]+months[:current_month])\n</code></pre>\n\n<p>If performance ever should become a concern, you could create a look-up using a dictionary beforehand, so that the computation does not have to be repeated:</p>\n\n<pre><code>MONTHS_TO_COME = {i+1: months[i:]+months[:i] for i in range(12)}\n\n# ... other code ...\n\nmonth = datetime.now().month\nprint(MONTHS_TO_COME[month])\n</code></pre>\n\n<p>Oh, and maybe have a look at the \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a>, aka PEP 8, for some hints on idiomatic formatting commonly found in Python code (e.g. <code>lower_case_with_underscores</code> in variable names).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:31:50.573", "Id": "233703", "ParentId": "233698", "Score": "9" } }, { "body": "<p>Instead of hard-coding month names - delegate all the work to respective libraries.</p>\n\n<p>I would suggest 2 approaches:</p>\n\n<ul>\n<li><p><a href=\"https://docs.python.org/3/library/calendar.html#calendar.month_abbr\" rel=\"noreferrer\"><code>calendar.month_abbr</code></a></p>\n\n<pre><code>from datetime import datetime\nfrom calendar import month_abbr\n\ndef get_forward_month_list():\n month = datetime.now().month # current month number\n return [month_abbr[(month % 12 + i) or month] for i in range(12)]\n</code></pre></li>\n<li><p><a href=\"https://dateutil.readthedocs.io/en/latest/relativedelta.html#module-dateutil.relativedelta\" rel=\"noreferrer\"><code>dateutil.relativedelta.relativedelta</code></a></p>\n\n<pre><code>from datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\n\ndef get_forward_month_list():\n now = datetime.now()\n return [(now + relativedelta(months=i)).strftime('%b') for i in range(12)]\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Both approaches will return the expected/needed list of month names:</p>\n\n<pre><code>print(get_forward_month_list())\n['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:26:50.110", "Id": "456915", "Score": "2", "body": "Awesome. I thought there was a way to do it utilizing a library. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:35:37.713", "Id": "456917", "Score": "0", "body": "@Christopher, you're welcome" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:23:41.007", "Id": "456974", "Score": "11", "body": "To avoid modulos and ors and complicated expressions for skipping the empty [0] I would use `return month_abbr[month:] + month_abbr[1:month]` instead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:35:53.087", "Id": "457061", "Score": "2", "body": "@Christopher said \"*I thought there was a way to do it utilizing a library.*\" The only thing the library did was provide the `month_abbr` list. It's the same as your first definition of `theList`, so, in terms of coding, all the library did was save a few characters of typing. — Thinking at a higher level though, libraries guarantee getting the same abbreviations as everyone else, and that should the world decide to make changes to the official abbreviation list (e.g. add a new month) your code will handle it with no changes on your part. And if a user prefers French, that's what they'll see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:22:12.907", "Id": "457071", "Score": "1", "body": "@njzk2 Absolutely. I've been staring at `(month % 12 + i) or month` for far too long. I still don't get why the naive solution `(month + i) % 12` wouldn't work? What am I missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:43:57.727", "Id": "457077", "Score": "0", "body": "Oh nm, lol. I knew `0` didn't work from the start, then forgot it at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:39:13.407", "Id": "457098", "Score": "1", "body": "@njzk2 — Another good reason for not using the `%12` method is that it makes an assumption about the number of elements in a list obtained from a library. In this case, I doubt a thirteenth month will be added anytime soon, but as a general principle, it's not good to make assumptions about what something else provides. Even if the library were something that the program's author maintains, it's still not good to use hard-wired numbers. Changing the library would require changing this code. `0`, `1`, and `many` are the only good numbers to use when programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:16:33.390", "Id": "457150", "Score": "0", "body": "Am I missing something? `month = 9\n\nfor i in range (12):\n print((month % 12 + i) or month)` yields 9 through 20." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:16:42.423", "Id": "457151", "Score": "0", "body": "It's a little clunky, but `(month +1+i)%12 -1` should work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T04:27:21.173", "Id": "457179", "Score": "0", "body": "@JollyJoker I was wondering the same thing, until I looked at the doc and realized that empty 0 is always there" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:39:42.553", "Id": "233705", "ParentId": "233698", "Score": "22" } }, { "body": "<p>I'd recommend using the built-in <code>strftime</code> rather than defining your own list of strings:</p>\n\n<pre><code>import datetime\n\ndate = datetime.date.today()\nmonths = []\nfor _ in range (12):\n months.append(date.strftime(\"%b\"))\n date = date.replace(month=(date.month % 12 + 1))\n</code></pre>\n\n<p>Because someone will always complain when you can't find a way to do a loop like this as a list comprehension, here's a way to do it in a single line of code with a cheesy <code>timedelta</code> (this doesn't work for arbitrarily long sequences because 30 days isn't exactly one month, but for your use case the rounding errors won't add up enough to matter):</p>\n\n<pre><code>months = [(datetime.date.today().replace(day=15) + datetime.timedelta(days=30*n)).strftime(\"%b\") for n in range(12)]\n</code></pre>\n\n<p>although to make this readable I think you'd want to break it up a little:</p>\n\n<pre><code>months = [\n (datetime.date.today().replace(day=15) + \n datetime.timedelta(days=30*n)).strftime(\"%b\") \n for n in range(12)\n]\n</code></pre>\n\n<p>IMO the <code>for</code> loop version is cleaner. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:49:55.217", "Id": "233706", "ParentId": "233698", "Score": "3" } }, { "body": "<p>Shamelessly ripping off @RomanPerekhrest 's answer. You can't rotate a list in Python but you can a deque, and the collections module always needs more love:</p>\n\n<pre><code>from datetime import datetime\nfrom calendar import month_abbr\nfrom collections import deque\n\ndef get_forward_months():\n months = deque(month_abbr[1:])\n months.rotate(1-datetime.now().month)\n return months\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:46:07.520", "Id": "457066", "Score": "1", "body": "I don't think you need the list comprehension. `months = deque(month_abbr[1:])` should work, shouldn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:31:12.127", "Id": "457073", "Score": "0", "body": "@MattM. Yes, even better, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:06:42.507", "Id": "233784", "ParentId": "233698", "Score": "8" } }, { "body": "<p>My solution is similar to some of the others here. However, it doesn't use loops, math, conditional logic, or hard-coded month names. That should make it more resistant to bugs.</p>\n<pre><code>import calendar\nfrom datetime import datetime\n\nmonthList = lambda month: \\\n calendar.month_abbr[month:] + \\\n calendar.month_abbr[1:month]\n\ncurrentMonth = datetime.now().month\n\nprint(monthList(currentMonth))\n</code></pre>\n<p>The output:</p>\n<pre><code>['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']\n</code></pre>\n<p>This uses Python's <code>calendar</code> module, because it includes a <code>month_abbr</code> list with all the month name abbreviations. It has an empty string at element 0 and the month names are in elements 1–12.</p>\n<pre><code>['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n</code></pre>\n<p>The simplest solution is to use slices of that list, taking into account that the elements needed start with index 1.</p>\n<p>What this solution does is take a slice of <code>month_abbr</code> starting with the current month to the end of the list (<code>calendar.month_abbr[month:]</code>) and appends a slice of <code>month_abbr</code> starting with the first month <em><strong>up to but not including</strong></em> the current month (<code>calendar.month_abbr[1:month]</code>).</p>\n<h2>Localization</h2>\n<p>An additional benefit to using the <code>calendar.month_abbr</code> list is that it is <strong><em>localized</em></strong>. If the locale in the program's environment changes to one with a different language, then the month abbreviation list automatically contains the names of months in that language. For example, updating the above code to switch locales, the following code will print the month list in the language of the default locale (English in this example), then print them in German and Hebrew (as an example of non-Latin script).</p>\n<pre><code>import calendar\nimport locale\nfrom datetime import datetime\n\nmonthList = lambda month: \\\n calendar.month_abbr[month:] + \\\n calendar.month_abbr[1:month]\n\ncurrentMonth = datetime.now().month\n\nprint(locale.getlocale(),\n monthList(currentMonth))\n\nlocale.setlocale(locale.LC_ALL, 'de_DE')\nprint(locale.getlocale(),\n monthList(currentMonth))\n\nlocale.setlocale(locale.LC_ALL, 'he_IL')\nprint(locale.getlocale(),\n monthList(currentMonth))\n</code></pre>\n<p>The output:</p>\n<pre><code>('en_US', 'UTF-8') ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']\n('de_DE', 'ISO8859-1') ['Okt', 'Nov', 'Dez', 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep']\n('he_IL', 'ISO8859-8') ['אוק', 'נוב', 'דצמ', 'ינו', 'פבר', 'מרץ', 'אפר', 'מאי', 'יונ', 'יול', 'אוג', 'ספט']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:54:59.273", "Id": "491141", "Score": "0", "body": "Good answer, but it would be better if your observations preceded your alternate code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:31:28.457", "Id": "491147", "Score": "0", "body": "Thanks! How would it be better? Do you mean I should put the explanation of using and slicing`calendar.month_abbr` before the code? I had originally written it that way. Then I thought the impatient TL;DR crowd (of which I'm a member) might like to see the solution and output as the very first thing, so I rearranged it. I could be persuaded to arrange it back again, especially if your comment gets a lot of votes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T16:43:43.833", "Id": "491153", "Score": "0", "body": "Your initial version would have been better, since this sight is about the original posters code and not about alternate solutions." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:43:27.500", "Id": "250323", "ParentId": "233698", "Score": "1" } } ]
{ "AcceptedAnswerId": "233705", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:47:15.250", "Id": "233698", "Score": "13", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Python Code for List of Month Names starting with current month" }
233698
<p>I am collecting 3 years of data and building a string that will be used with an ASP Literal control. The method <code>GetListOfMeetingBygroupId</code> takes in a <code>groupID</code> and <code>year</code> and will return meeting for that group and year.</p> <pre><code> MeetingService ms = new MeetingService(); int groupId = 574; //Meeting int totalYearCount = 3; StringBuilder sbMeeting = new StringBuilder(); DateTime aDate = DateTime.Now; for (int x = 1; x &lt;= totalYearCount; x++) { var list = ms.GetListOfMeetingBygroupId(groupId, aDate.Year); sbMeeting.AppendFormat("&lt;p&gt;&lt;b&gt;{0}&lt;/p&gt;&lt;/b&gt;",aDate.ToString("yyyy")); foreach (var meeting in list) { sbMeeting.Append("&lt;p&gt;"); DateTime meetingendDate = Convert.ToDateTime(meeting.MeetingDateList.Select(c =&gt; c.StartDate).Max()); DateTime meetingstartDate = Convert.ToDateTime(meeting.MeetingDateList.Select(c =&gt; c.StartDate).Min()); int totalMeetingPresentation = ms.GetListOfPresentationsBymeetingId(meeting.MeetingId).Count(); sbMeeting.Append(meetingstartDate.ToString("dddd, MMMM dd yyyy")); sbMeeting.Append("&lt;br&gt;"); sbMeeting.Append(meeting.Type.Name); sbMeeting.Append("&lt;br&gt;"); if (totalMeetingPresentation &gt; 0) { sbMeeting.AppendFormat("&lt;a class='body'href=meetingdetails.aspx?meetingId={0}&gt;{1}&lt;/a&gt;", meeting.MeetingId, "Minutes and Presentations"); } else { var meetingMinFile = ms.GetMeetingFile(meeting.MeetingId); sbMeeting.AppendFormat("&lt;td&gt;&lt;a href=../../../Common/FileManager.ashx?FileManagerId={0}&gt;{1}&lt;/a&gt;&lt;/td&gt;", meetingMinFile.FileManagerId, "Minutes"); } sbMeeting.Append("&lt;p&gt;"); sbMeeting.Append("&lt;br&gt;"); sbMeeting.Append("&lt;/p&gt;"); } aDate = aDate.AddYears(-1); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:45:15.033", "Id": "456933", "Score": "0", "body": "Have you tested the output of this code? I can see multiple broken HTML tags in there." } ]
[ { "body": "<p>I'll focus on the C# part of the code, but please run the output HTML through a <a href=\"https://validator.w3.org/\" rel=\"nofollow noreferrer\">validator</a> because at first glance I count no fewer than five HTML tags that are mismatched, misplaced, or simply broken.</p>\n\n<h1>Outer loop</h1>\n\n<p>You're not using the loop variable <code>x</code> anywhere. This suggests that the loop should be refactored around the thing that you're <em>actually</em> iterating over, which seems to be a <em>range of years</em>.</p>\n\n<p>Each year is just an integer; you can get a range of integers using <code>Enumerable.Range</code>. You want the most recent <code>totalYearCount</code> years (inclusive of this year), so start the range at <code>nowYear - totalYearCount + 1</code>. You want this year <em>first</em>, so reverse the sequence too.</p>\n\n<pre><code>foreach (var year in Enumerable\n .Range(aDate.Year - totalYearCount + 1, totalYearCount)\n .Reverse())\n{\n var list = ms.GetListOfMeetingBygroupId(groupId, year);\n // ...\n}\n</code></pre>\n\n<p>You can replace <code>aDate.ToString(\"yyyy\")</code> accordingly.</p>\n\n<h1>Naming</h1>\n\n<p>When using <code>camelCase</code> and <code>PascalCase</code>, each distinct word should start with a capital letter. <code>GetListOfMeetingByGroupId</code>, <code>GetListOfPresentationsByMeetingId</code>, <code>meetingStartDate</code>, <code>meetingEndDate</code>, and so on.</p>\n\n<p>Type prefixes like <code>sb</code> don't help much, especially when abbreviated. Rename that variable to better reflect what it actually is: it's a builder for the output, so maybe <code>outputBuilder</code> instead of <code>sbMeeting</code>.</p>\n\n<p><code>list</code> is a really generic name for something we know to be a collection of meetings, so call it <code>meetings</code> or <code>meetingList</code>.</p>\n\n<h1>Code we haven't seen</h1>\n\n<p>It's advised to post or link to all supporting code. It's at least relevant because of this here:</p>\n\n<pre><code>Convert.ToDateTime(meeting.MeetingDateList.Select(c =&gt; c.StartDate).Max());\n</code></pre>\n\n<p>What's the type of <code>c.StartDate</code>? You're converting it to a <code>DateTime</code> <em>after getting the maximum date</em> -- so it's probably not a <code>DateTime</code> already -- which begs the question <em>how are you sorting the dates</em>? I suspect you might've wanted the order switched:</p>\n\n<pre><code>meeting.MeetingDateList.Max(c =&gt; Convert.ToDateTime(c.StartDate));\n</code></pre>\n\n<p>Note that I've used the overload for <code>Max</code> that takes a selector so that I can avoid the unnecessary <code>Select</code>.</p>\n\n<h1>General readability</h1>\n\n<p>Your spacing is inconsistent. Consistent spacing would make for better readability, so I offer these suggestions:</p>\n\n<ul>\n<li>Use exactly one indent per <code>{}</code> block -- your inner <code>foreach</code> loop is double-indented.</li>\n<li>Avoid empty lines of padding within <code>{}</code> blocks -- see your <code>for</code> loop and the <code>else</code> block.</li>\n<li>Parameters should be separated by a comma and one space -- see your first <code>sbMeeting.AppendFormat(...)</code>.</li>\n</ul>\n\n<p>All of those hard-coded HTML strings should be refactored out into some kind of template. They have no business being encoded inline in the method like that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:57:55.200", "Id": "457158", "Score": "0", "body": "What do you mean template?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:19:17.107", "Id": "233726", "ParentId": "233699", "Score": "2" } }, { "body": "<p>These lines look nice and readable</p>\n\n<pre><code> sbMeeting.Append(\"&lt;p&gt;\");\n sbMeeting.Append(\"&lt;br&gt;\");\n sbMeeting.Append(\"&lt;/p&gt;\");\n</code></pre>\n\n<p>but if you want to have a little more performance, just use one string.</p>\n\n<pre><code> sbMeeting.Append(\"&lt;p&gt;&lt;br&gt;&lt;/p&gt;\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:32:04.300", "Id": "233727", "ParentId": "233699", "Score": "2" } } ]
{ "AcceptedAnswerId": "233726", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:50:57.473", "Id": "233699", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Collecting 3 years of data and building a string" }
233699
<p>I'm using <a href="https://adventofcode.com/" rel="noreferrer">advent of code 2019</a> to start learning Python. I've read the Python style guide, and I'm trying to write readable and reusable code.</p> <p>This piece of code is an implementation of the IntCode computer used in many of the assignments. If you'd like to see code for the specific assignments, it's on my <a href="https://github.com/jorn86/adventofcode2019" rel="noreferrer">Github</a>.</p> <p>Here's the code for the IntCode computer itself. Any suggestions for improvement are welcome, especially relating to the 'pythonic' way of doing things. For reference, my background is in Java.</p> <pre><code>import threading from typing import List class IntCoder: _memory = [] __pointer = 0 __relative_base = 0 def __init__(self, memory: List[int]): self._memory = memory def run(self): while self.__step(): pass def get_input(self): raise ValueError('No input defined') def handle_output(self, value): print(value) def read_pointer(self): return self.read(self.__pointer) def read(self, index): return self._memory[index] def __step(self): instruction = self._memory[self.__pointer] opcode = instruction % 100 mode1 = (instruction // 100) % 10 mode2 = (instruction // 1000) % 10 mode3 = instruction // 10000 if opcode == 1: self.__add(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2), self.__index(self.__pointer + 3, mode3)) elif opcode == 2: self.__mul(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2), self.__index(self.__pointer + 3, mode3)) elif opcode == 3: self.__in(self.__index(self.__pointer + 1, mode1)) elif opcode == 4: self.__out(self.__val(self.__pointer + 1, mode1)) elif opcode == 5: self.__if_true(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2)) elif opcode == 6: self.__if_false(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2)) elif opcode == 7: self.__lt(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2), self.__index(self.__pointer + 3, mode3)) elif opcode == 8: self.__eq(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2), self.__index(self.__pointer + 3, mode3)) elif opcode == 9: self.__arb(self.__val(self.__pointer + 1, mode1)) elif opcode == 99: return False else: raise ValueError('Unknown opcode {} in instruction {}'.format(opcode, instruction)) return True def __val(self, address, mode): index = self._memory[address] if mode == 0: return self._memory[index] elif mode == 1: return index elif mode == 2: return self._memory[index + self.__relative_base] else: raise ValueError('Unknown parameter mode {}'.format(mode)) def __index(self, address, mode): if mode == 0: return self._memory[address] elif mode == 2: return self._memory[address] + self.__relative_base raise ValueError('Got mode {} for index only type param'.format(mode)) def __add(self, first, second, result): self._memory[result] = first + second self.__pointer += 4 def __mul(self, first, second, result): self._memory[result] = first * second self.__pointer += 4 def __in(self, index): self._memory[index] = self.get_input() self.__pointer += 2 def __out(self, value): self.handle_output(value) self.__pointer += 2 def __if_true(self, first, second): self.__pointer = second if first != 0 else self.__pointer + 3 def __if_false(self, first, second): self.__pointer = second if first == 0 else self.__pointer + 3 def __lt(self, first, second, result): self._memory[result] = 1 if first &lt; second else 0 self.__pointer += 4 def __eq(self, first, second, result): self._memory[result] = 1 if first == second else 0 self.__pointer += 4 def __arb(self, value): self.__relative_base += value self.__pointer += 2 @staticmethod def extended_memory(program, size): memory = [0] * size memory[0:len(program)] = program return memory @staticmethod def read_file(file): with open(file, 'r') as f: return [int(s) for s in f.read().split(',')] class IntCoderWithIo(IntCoder): def __init__(self, memory, input_values: List[int]): super(IntCoderWithIo, self).__init__(memory) self.input_values = (n for n in input_values) self.output = [] def get_input(self): return next(self.input_values) def handle_output(self, value): self.output.append(value) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:48:17.103", "Id": "456919", "Score": "0", "body": "Please add an excerpt of the programming challenge to the question itself. Links can rot. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:56:45.560", "Id": "456921", "Score": "0", "body": "There are multiple IntCode challenges from Advent of Code, can you specify which days this one fulfills the requirements for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:13:24.813", "Id": "456937", "Score": "0", "body": "Do you have a particular Python3 version you are targeting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T09:05:09.693", "Id": "457014", "Score": "0", "body": "@SimonForsberg It's the combined final product from specifications found in days 2, 5, 7 and 9. Day 9 has a test program that validates the entire thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:25:25.217", "Id": "457056", "Score": "0", "body": "@Jorn Great. You’ve got all the specifications. Now you should edit your post and add the specifications to it. Links can rot; adding the specs preserves the integrity of your question for future readers. Also, maybe you made a mistake in your implementation not covered in day 9 tests; if we knew the specs, we can see if you covered them all. Maybe there are efficiencies suggested by the spec that have been missed; we could catch those too." } ]
[ { "body": "<h2>Unused Imports</h2>\n\n<p>You've imported <code>threading</code>, but you are not using it anywhere in this module.</p>\n\n<h2>Dunder</h2>\n\n<p>Dunder, or double-underscore, members have special meaning in Python. Specifically, the Python interpreter does a form of name-mangling, to prevent member names defined in the parent class from colliding with member names defined in a derived class. This also prevents the derived class from accessing members defined in the parent class. I doubt this is what you were intending here. Avoid creating your own double underscores members.</p>\n\n<h2>Class Variables</h2>\n\n<p>Java lets you initialize member variables outside the constructor; Python does not. What you are doing is ugly, dangerous, and will bite you down the road.</p>\n\n<pre><code>class IntCoder:\n\n _memory = [] # Class member\n _pointer = 0 # Class member\n _relative_base = 0 # Class member\n\n def __init__(self, memory: List[int]):\n self._memory = memory # Instance member\n</code></pre>\n\n<p>This code creates 3 class member variables (Ie, <code>static</code> in Java terminology), and then the <code>IntCoder()</code> constructor creates one instance member, shadowing the first class member.</p>\n\n<p>When Python looks up <code>self.member</code>, it first looks in the <code>self</code> object's dictionary for <code>member</code>. If that fails, it will also look in the class's dictionary. Assignments to <code>self.member</code> will always create <code>member</code> in the object instance.</p>\n\n<p>Now consider:</p>\n\n<pre><code> self._pointer += 4\n</code></pre>\n\n<p>If <code>_pointer</code> is defined in the instance object, this is interpreted as:</p>\n\n<pre><code> self._pointer = self._pointer + 4\n</code></pre>\n\n<p>If <code>_pointer</code> is not defined in the instance object, but exists in the class, this is interpreted as looking up the class member, and creating the instance member:</p>\n\n<pre><code> self._pointer = IntCoder._pointer + 4\n</code></pre>\n\n<p>Yikes! Mutating code interpretation!</p>\n\n<p>You really want each <code>IntCoder</code> to have its own, independent state, so they each should create their own instance members in the constructor:</p>\n\n<pre><code>class IntCoder:\n\n def __init__(self, memory: List[int]):\n self._memory = memory \n self._pointer = 0 \n self._relative_base = 0\n</code></pre>\n\n<h2>Pointer Management</h2>\n\n<p>These next few items all go together ...</p>\n\n<h3><code>self.read_pointer()</code></h3>\n\n<p>Never called. Why is this here?</p>\n\n<h3><code>instruction</code> fetching</h3>\n\n<pre><code> instruction = self._memory[self.__pointer]\n</code></pre>\n\n<p>Looks like that could have been <code>instruction = self.read_pointer()</code>. But ...</p>\n\n<h3>Separation of concerns</h3>\n\n<pre><code> def __add(self, first, second, result):\n self._memory[result] = first + second\n self.__pointer += 4\n</code></pre>\n\n<p>Whoa, whoa, hold the phone. Ok, I understand you are adding the values <code>first</code> and <code>second</code> together, and storing the result in memory at address <code>result</code>. But where the heck did that <code>self.__pointer += 4</code> come from? And why 4?</p>\n\n<pre><code> if opcode == 1:\n self.__add(self.__val(self.__pointer + 1, mode1), self.__val(self.__pointer + 2, mode2), self.__index(self.__pointer + 3, mode3))\n</code></pre>\n\n<p>Ok, looking back, we can see that we got a value using from <code>self._pointer + 1</code>, a second value using <code>self._pointer + 2</code>, and use <code>self._pointer + 3</code> to get the address to store the result. So that explains 3 of the increment of 4...</p>\n\n<pre><code> instruction = self._memory[self.__pointer]\n</code></pre>\n\n<p>Oh ya, and the instruction itself in the 4th value.</p>\n\n<p>What is the <code>IntCoder</code> really doing? It is:</p>\n\n<ol>\n<li>Fetching the opcode</li>\n<li>Fetching the first operand, or index to it</li>\n<li>Fetching the second operand, or index to it</li>\n<li>Fetching the destination address or index</li>\n</ol>\n\n<p>Or, to summarize, it is fetching, ... and implicit in the fetch is an increment of the pointer.</p>\n\n<pre><code> def _fetch(self):\n value = self._memory[self._pointer]\n self._pointer += 1\n return value\n</code></pre>\n\n<p>Now you can use:</p>\n\n<pre><code> instruction = self._fetch()\n</code></pre>\n\n<p>and know that if you called <code>_fetch()</code> again, the next value would be read, and then the next, and the next. No need to externally code <code>self._pointer += 1</code> anymore. Let's do the same for <code>_val()</code>:</p>\n\n<pre><code> def _val(self, mode):\n index = self._fetch()\n if mode == 0:\n return self._memory[index]\n if mode == 1:\n return index\n if mode == 2:\n return self._memory[index + self._relative_base]\n raise ValueError(f\"Unknown parameter mode {mode}\")\n</code></pre>\n\n<p><strong>Note</strong>: Python 3.6 introduced f-strings, which allow you to embed variables right in strings, rather than needing <code>.format(...)</code></p>\n\n<p>If you also added the <code>_fetch()</code> to <code>_index</code>, you'd could now write:</p>\n\n<pre><code> if opcode == 1:\n self._add(self._val(mode1), self._val(mode2), self._index(mode3))\n</code></pre>\n\n<p>and</p>\n\n<pre><code> def _add(self, first, second, result):\n self._memory[result] = first + second\n</code></pre>\n\n<h2>Decoding Instructions</h2>\n\n<p>A large chain of <code>if opcode == 0: elif opcode == 1: elif opcode == 2: elif opcode == 3: ...</code> is an indication of doing something wrong, or at least the non-Pythonic way.</p>\n\n<p>Methods are first class objects in Python, and can be used as values and stored in containers. Which means you can use a dictionary to decode and dispatch based on the opcode:</p>\n\n<pre><code>class IntCoder:\n\n def __init__(self):\n self._opcodes = { 1: self._add,\n 2: self._mul,\n 3: self._in,\n ...\n }\n\n def _step(self):\n instruction = self._fetch()\n opcode = instruction % 100\n mode1 = (instruction // 100) % 10\n mode2 = (instruction // 1000) % 10\n mode3 = instruction // 10000\n\n try:\n self._opcodes[opcode](mode1, mode2, mode3)\n except KeyError:\n raise ValueError('Unknown opcode {opcode} in instruction {instruction-1}')\n\n def _add(self, mode1, mode2, mode3):\n a = self._val(mode1)\n b = self._val(mode2)\n dst = self._index(mode3)\n self._memory[dst] = a + b\n\n def _in(self, mode1, mode2, mode3):\n index = self._index(mode1)\n self._memory[index] = self.get_input()\n</code></pre>\n\n<p>Note we've changed thing a bit. The responsibility for fetching the values to add, and the destination to store the results into has moved into the individual functions. Additionally, we are passing unnecessary information to the <code>_in()</code> method; it doesn't need the <code>mode2</code> and <code>mode3</code> values, but it needs those arguments since with this dispatch method, all the methods have to use a common parameter list.</p>\n\n<h2>Iterators</h2>\n\n<p>The following is creating and storing a generator expression, to walk through the list of values, returning the values one at a time:</p>\n\n<pre><code>self.input_values = (n for n in input_values)\n</code></pre>\n\n<p>Internally, <code>for n in input_values</code> is walking through <code>input_values</code>, return each value one at a time. It works because <code>input_values</code> is an iterable. We can retrieve an iterator for that iterable object and use that directly.</p>\n\n<pre><code>self.input_values = iter(input_values)\n</code></pre>\n\n<p>Then you could pass in any <code>input_values: Iterable[int]</code>, instead of just lists.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T08:38:28.430", "Id": "457008", "Score": "0", "body": "Very helpful, thank you! It's going to take me a while to work through all of this. The first question I have is on the dunder, I took it to be a kind of 'private'. I understand I should define `pointer` as an instance variable only, but would you recommend also making it visible? Nothing outside the class should need to access it. Oh, and the reason `memory` only has a single underscore is that it should not need to be visible, except I'm reading it in a test. The Java equivalent would be `@VisibleForTesting` with package visibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T10:45:23.360", "Id": "457018", "Score": "0", "body": "I made a lot of improvements based on your comments. Thanks again for the input! One more question: Am I using type hints correctly? Should I be using more of them? They are currently on the constructor only, should they also be on the 'public' methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:51:43.787", "Id": "457165", "Score": "1", "body": "\"Private\" in Python is by convention; it is not enforced. A single leading underscore implies private/protected. Checkers (like PyLint) will detected accesses to `variable._member` and complain, where as `self._member` is allowed. However, in Python, \"we're all consenting adults\", and nothing prevents you from playing with another object's private members. Not even dunders: `print(coder._IntCoder__pointer)` works just fine. Feel free to access `uut._member` from test code all you want; people will be happy test code exists, and not complain about private member access." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T23:00:29.803", "Id": "457167", "Score": "1", "body": "Your type-hint usage looked correct, albeit sparse. If you are using type-hints, all public members should have type-hints. All public members should have `\"\"\"docstrings\"\"\"`, too. This helps automatic documentation generation, allowing other people to use your class without needing to read the source code. Internal (private/protected) members would also benefit from type-hints, as this will allow static analysis tools to detect bugs or inconsistencies. But the more your document these internals, the more likely people will be to reach in & access your private members, so double edged sword." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T23:24:58.283", "Id": "233735", "ParentId": "233702", "Score": "6" } } ]
{ "AcceptedAnswerId": "233735", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:16:20.667", "Id": "233702", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "IntCode computer in Python 3" }
233702
<p>I wrote a function that I use to preprocess pandas dataframes before running them through a machine learning model. The function works perfectly, however I don't think it's the most pythonic way to write it.</p> <p>This function accepts a list of words:</p> <pre><code>['here', 'is', 'a','sample', 'of','what','the','function','accepts'] </code></pre> <pre class="lang-py prettyprint-override"><code>def clean_text(x): stopwords_english = stopwords.words('english') for i,word in enumerate(x): if word.lower() in stopwords_english: x[i] = '' else: for punct in "/-'": x[i] = word.replace(punct, ' ') for punct in '&amp;': x[i] = word.replace(punct, f' {punct} ') for punct in '?!.,"#$%\'()*+-/:;&lt;=&gt;@[\\]^_`{|}~' + '“”’': x[i] = word.replace(punct, '') return x </code></pre> <p>Here I am using <code>enumerate</code> to change the value inside of the list. I would have assumed a more pythonic way of doing it would be writing it as follows:</p> <pre class="lang-py prettyprint-override"><code>def clean_text(x): stopwords_english = stopwords.words('english') for word in x: if word.lower() in stopwords_english: word = '' else: for punct in "/-'": word = word.replace(punct, ' ') for punct in '&amp;': word = word.replace(punct, f' {punct} ') for punct in '?!.,"#$%\'()*+-/:;&lt;=&gt;@[\\]^_`{|}~' + '“”’': word = word.replace(punct, '') return x </code></pre> <p>The function is being called as follows:</p> <pre class="lang-py prettyprint-override"><code>train['question_text'].progress_apply(lambda x: clean_text(x)) </code></pre> <p>Where <code>train</code> is a pandas dataframe and 'question_text' is a column in the dataframe.</p> <p>Is my current implementation the most pythonic way, or is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:00:58.983", "Id": "456910", "Score": "3", "body": "Are you applying `clean_text` to `pandas.Series` sequence? Post a context of calling" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:47:37.627", "Id": "456918", "Score": "0", "body": "@RomanPerekhrest Thanks for the heads up, I edited it and included how the function is called. Please note that i am using progress_apply because i am using the tqdm library to monitor the progress." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:21:05.293", "Id": "456923", "Score": "1", "body": "@A Merii, if initially `train['question_text']` column contains a list of words in each cell , imagine that after replacement the resulting list could have multiple gaps like `['', 'is', 'a','', 'of','what','the','','']` - is that expected in your case? or the result could be returned as a plain text ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:41:41.217", "Id": "456927", "Score": "0", "body": "@RomanPerekhrest Funny thing is, I was just revising my code then i realized that i need to tweak the function a bit to actually drop the empty cells rather than replace them with an empty string. Please correct me if I am wrong but the best way to do that would be to use the 'del' operator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:49:28.473", "Id": "456928", "Score": "0", "body": "The `yield` operator mentioned by @RootTwo below takes care of dropping the unwanted words through the use of the conditional statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:50:00.717", "Id": "457080", "Score": "1", "body": "BTW, your code isn't stable, i.e. your function applied twice will not yield the same result as if you apply your function once. You might want to replace `'&'` with regex that looks for an ampersand that isn't surrounded by spaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:17:32.197", "Id": "457118", "Score": "0", "body": "@Accumulation, yes you are completely right, thanks for the heads up. :D" } ]
[ { "body": "<p>This may be a good case for generator functions. And splitting it into two parts might make things more flexible: first, remove the stopwords; and second, handle the punctuation. </p>\n\n<p>Also, <code>str.maketrans</code> and <code>str.translate</code> can do the punctuation mapping.</p>\n\n<pre><code>def remove_stopwords(text_iterable, stopwords):\n for word in text_iterable:\n if word.lower() not in stopwords:\n yield word\n\n\ndef handle_punctuation(text_iterable, table):\n for word in text_iterable:\n yield word.translate(table)\n\n\n# format is (\"chars\", \"replacement\") \nmappings = ((\"/-'\", ' '),\n ('&amp;', ' &amp; '),\n ('?!.,\"#$%\\'()*+-/:;&lt;=&gt;@[\\\\]^_`{|}~' + '“”’', None))\n\ntable = str.maketrans({c:v for k,v in mappings for c in k})\n\nstopword_free = remove_stopwords(text, stopwords)\ncleaned_text = handle_punctuation(stopword_free, table)\n</code></pre>\n\n<p><code>cleaned_text</code> is a generator, use <code>list(handle_punctuation(stopword_free, table))</code> if you need an actual list of words.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:28:02.253", "Id": "456925", "Score": "0", "body": "Thanks for the answer, is there a specific advantage to using a generator in the case? I am passing the function as a lamda function as follows: train['question_text'].progress_apply(lambda x: list(remove_stopwords(x)))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:32:03.620", "Id": "456931", "Score": "1", "body": "I find generator functions work well as filters. Small ones are easy to understand (and code). And they can be composed to make more complicated filters. For example, if you wanted to also remove words containing foreign letters. It would be relatively easy to add another filter function generator to the chain of filters.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T08:08:13.613", "Id": "457004", "Score": "0", "body": "Its far easier to manipulate generator code because you avoid hard-coding your values also if you need to change something in your code in the future you only have to change it in 1 place." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:06:10.393", "Id": "233721", "ParentId": "233710", "Score": "10" } }, { "body": "<p>Honestly, I can not consider neither of proposed approaches (except for applying <em>generators</em>) as efficient enough.<br></p>\n\n<p>Here are my arguments:</p>\n\n<ul>\n<li><p><strong><code>stopwords.words('english')</code></strong> sequence. <br>As <code>clean_text(x)</code> will be applied for <strong>each</strong> column cell it's better to move a common sequence of stopwords to the <em>top level</em> at once. But that's easy. <code>stopwords.words('english')</code> is actually a <strong>list</strong> of stopwords and a much more efficient would be to convert it into <strong><code>set</code></strong> object for fast containment check (in <code>if word.lower() in stopwords_english</code>):</p>\n\n<pre><code>stopwords_english = set(stopwords.words('english'))\n</code></pre></li>\n<li><p>instead of <em>yielding</em> a words that aren't contained in <code>stopwords_english</code> set for further replacements - in opposite, words that are <em>stopwords</em> can be just skipped at once:</p>\n\n<pre><code>if word.lower() in stopwords_english:\n continue\n</code></pre></li>\n<li><p>subtle nuance: the pattern <code>\"/-'\"</code> at 1st replacement attempt (<code>for punct in \"/-'\"</code>) is actually <strong>contained</strong> in a longer pattern of punctuation chars <code>?!.,\"#$%\\'()*+-/:;&lt;=&gt;@[\\\\]^_`{|}~' + '“”’'</code>.<br>Thus, it's unified into a single pattern and considering that there could be multiple consequent occurrences of punctuation/special char within a word - I suggest to apply a compiled regex pattern with <code>+</code> quantifier (to replace multiple occurrences at once) defined at top level.</p></li>\n</ul>\n\n<hr>\n\n<p>Finally, the optimized approach would look as follows:</p>\n\n<pre><code>import re\n\n...\nstopwords_english = set(stopwords.words('english'))\npunct_pat = re.compile(r'[?!.,\"#$%\\'()*+-/:;&lt;=&gt;@\\[\\\\\\]^_`{|}~“”’]+')\n\n\ndef clean_text(x):\n for word in x:\n if word.lower() in stopwords_english:\n continue\n if '&amp;' in word:\n word = word.replace('&amp;', ' &amp; ')\n yield punct_pat.sub('', word)\n</code></pre>\n\n<p>Applied as:</p>\n\n<pre><code>train['question_text'].progress_apply(lambda x: list(clean_text(x)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:16:22.693", "Id": "457032", "Score": "0", "body": "How about one more step to make it use list comprehension? Something like `punct_pat.sub('', word.replace('&', ' & ')) for word in x if word.lower() not in stopwords_english`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:34:30.003", "Id": "457047", "Score": "0", "body": "@JollyJoker, for simple cases and if the function is unlikely to be extended - yes, list comprehension could be straightforward and good. But I've use a single `for` loop to show how the flow goes and it's easier to extend it with potential additional transformations/substitutions without loss of readability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:12:37.363", "Id": "233725", "ParentId": "233710", "Score": "6" } } ]
{ "AcceptedAnswerId": "233721", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:34:58.703", "Id": "233710", "Score": "9", "Tags": [ "python", "python-3.x", "iterator" ], "Title": "Manipulating list values in python" }
233710
<p>This is the first time I am writing R code to access/manipulate and save data. The SQL query I would normally run then save to a spreadsheet, read it into R, save to another sheet then copy and paste that yet to another spreadsheet, then import back into SQL-Server.</p> <p>Too much going on so I wanted to put it all together into one script. The SQL Script is fairly straightforward:</p> <pre><code>SELECT PtNo_Num , a.addr_line1 + ', ' + a.Pt_Addr_City + ', ' + a.Pt_Addr_State + ', ' + a.Pt_Addr_Zip AS [FullAddress] , a.Pt_Addr_Zip , a.Pt_Addr_City + ', ' + a.Pt_Addr_State + ', ' + a.Pt_Addr_Zip AS [PartialAddress] FROM smsdss.c_patient_demos_v AS A LEFT OUTER JOIN smsdss.BMH_PLM_PtAcct_V AS B ON A.pt_id = B.Pt_No AND A.from_file_ind = B.from_file_ind LEFT OUTER JOIN SMSDSS.c_geocoded_address AS C ON B.PtNo_Num = C.Encounter WHERE a.Pt_Addr_City IS NOT NULL AND a.addr_line1 IS NOT NULL AND a.Pt_Addr_State IS NOT NULL AND a.Pt_Addr_Zip IS NOT NULL AND b.Plm_Pt_Acct_Type = 'I' AND b.tot_chg_amt &gt; 0 AND LEFT(B.PTNO_NUM, 1) != '2' AND LEFT(B.PTNO_NUM, 4) != '1999' AND B.Dsch_Date &gt;= '2019-01-01' AND A.addr_line1 != '101 HOSPITAL RD' AND C.Encounter IS NULL </code></pre> <p>The R script so far is as below:</p> <pre><code># Lib Load ---- if(!require(pacman)) install.packages(&quot;pacman&quot;) pacman::p_load( # DB Packages &quot;DBI&quot;, &quot;odbc&quot;, # Tidy &quot;tidyverse&quot;, &quot;dbplyr&quot;, &quot;writexl&quot;, # Mapping Tools &quot;tmaptools&quot; ) # Connection Obj ---- con &lt;- dbConnect( odbc(), Driver = &quot;SQL Server&quot;, Server = &quot;BMH-HIDB&quot;, Database = &quot;SMSPHDSSS0X0&quot;, Trusted_Connection = &quot;TRUE&quot; ) # Tables ---- pav &lt;- dplyr::tbl( con , in_schema( &quot;smsdss&quot; , &quot;BMH_Plm_PtAcct_V&quot; ) ) %&gt;% filter( tot_chg_amt &gt; 0 , Dsch_Date &gt;= '2019-01-01' , Plm_Pt_Acct_Type == &quot;I&quot; ) %&gt;% select( Plm_Pt_Acct_Type , tot_chg_amt , PtNo_Num , Pt_No , Dsch_Date , from_file_ind ) pdv &lt;- tbl( con , in_schema( &quot;smsdss&quot; , &quot;c_patient_demos_v&quot; ) ) # Query ---- geo_add &lt;- tbl( con , in_schema( &quot;smsdss&quot; , &quot;c_geocoded_address&quot; ) ) a &lt;- pdv %&gt;% left_join( pav , by = c( &quot;pt_id&quot;=&quot;Pt_No&quot; , &quot;from_file_ind&quot; = &quot;from_file_ind&quot; ) , keep = T ) add_geo &lt;- a %&gt;% left_join( geo_add , by = c( &quot;PtNo_Num&quot; = &quot;Encounter&quot; ) , keep = T ) %&gt;% select( PtNo_Num , addr_line1 , Pt_Addr_City , Pt_Addr_State , Pt_Addr_Zip , ZipCode , Plm_Pt_Acct_Type , tot_chg_amt , Dsch_Date ) %&gt;% filter( !is.na(Pt_Addr_City) , !is.na(addr_line1) , !is.na(Pt_Addr_State) , !is.na(Pt_Addr_Zip) , !is.na(Plm_Pt_Acct_Type) , !is.na(tot_chg_amt) , !is.na(Dsch_Date) , addr_line1 != '101 Hospital Rd' , is.na(ZipCode) ) # Make df ---- df &lt;- tibble() # Necessary? df &lt;- add_geo %&gt;% as_tibble() %&gt;% filter(str_sub(PtNo_Num, 1, 1) != 2) origAddress &lt;- df %&gt;% mutate( FullAddress = str_c( addr_line1 , Pt_Addr_City , Pt_Addr_State , Pt_Addr_Zip , sep = ', ' ) , PartialAddress = str_c( Pt_Addr_City , Pt_Addr_State , Pt_Addr_Zip , sep = ', ' ) ) %&gt;% select( PtNo_Num , FullAddress , Pt_Addr_Zip , PartialAddress ) %&gt;% rename( Encounter = PtNo_Num , ZipCode = Pt_Addr_Zip ) </code></pre> <p>It seems quite long compared to the SQL, is there a way to write this better or is it what it is so to speak.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:58:44.237", "Id": "456909", "Score": "0", "body": "those table & column names are pretty bad" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:24:57.343", "Id": "456914", "Score": "1", "body": "@dustytrash please don't review the code in the comments. Instead write an answer . Thanks!" } ]
[ { "body": "<p>The following are a few suggestions on how I'd write the SQL as a stored procedure. Then call it from R.</p>\n<p><strong>Source Control</strong></p>\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free &amp; private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n<p><strong>Formatting</strong></p>\n<p>I use the following tools for SSMS and Visual Studio, <a href=\"https://www.apexsql.com/sql-tools-refactor.aspx\" rel=\"nofollow noreferrer\">ApexSQL Refactor</a> and <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n<p><strong>Schema Names</strong></p>\n<p>Always reference the schema when selecting an object e.g. <code>[dbo].[Sales]</code>.</p>\n<ul>\n<li>Also check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow noreferrer\"><em>Clean Code</em></a>. It will change the way you think about naming conventions.</li>\n</ul>\n<hr />\n<h2>Revised SQL</h2>\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start.</p>\n<pre><code>CREATE PROCEDURE [dbo].[Patient_Addresses]\n(\n @Dsch_Date_Start AS DATE = '01-JAN-2019'\n , @addr_line1_Rule1 AS VARCHAR(50) = N'101 HOSPITAL RD'\n , @PTNO_NUM_Rule2 AS VARCHAR(1) = N'2'\n , @PTNO_NUM_Rule3 AS VARCHAR(50) = N'1999'\n , @Plm_Pt_Acct_Type_Invoice AS VARCHAR(1) = N'I'\n)\nAS\n\nBEGIN\n\n /*\n --use variables to document why the column is being filtered makes it easyier to understand\n DECLARE @Dsch_Date_Start AS DATE = '01-JAN-2019'; \n DECLARE @addr_line1_Rule1 AS VARCHAR(50) = N'101 HOSPITAL RD';\n DECLARE @PTNO_NUM_Rule2 AS VARCHAR(1) = N'2';\n DECLARE @PTNO_NUM_Rule3 AS VARCHAR(4) = N'1999';\n DECLARE @Plm_Pt_Acct_Type_Invoice AS VARCHAR(1) = N'I';\n */\n\n SELECT \n [PtNo_Num] --missing table/view alias\n , [FullAddress] = [a].[addr_line1] + ', ' + [a].[Pt_Addr_City] + ', ' + [a].[Pt_Addr_State] + ', ' + [a].[Pt_Addr_Zip] --column alias is easyier to read from the left\n , [a].[Pt_Addr_Zip]\n , [PartialAddress] = [a].[Pt_Addr_City] + ', ' + [a].[Pt_Addr_State] + ', ' + [a].[Pt_Addr_Zip]\n FROM\n [smsdss].[c_patient_demos_v] AS [a] --it's not within the best practices to use a prefix or suffix for views\n LEFT OUTER JOIN [smsdss].[BMH_PLM_PtAcct_V] AS [b] --there are a lot of conditions, this may be better done in another view.\n ON [a].[pt_id] = [b].[Pt_No] \n AND [a].[from_file_ind] = [b].[from_file_ind] \n AND [a].[Pt_Addr_City] IS NOT NULL --moving criteria to the join may speed up your results\n AND [a].[addr_line1] IS NOT NULL\n AND [a].[Pt_Addr_State] IS NOT NULL\n AND [a].[Pt_Addr_Zip] IS NOT NULL\n AND [a].[addr_line1] != @addr_line1_Rule1\n AND [b].[Plm_Pt_Acct_Type] = @Plm_Pt_Acct_Type_Invoice\n AND [b].[tot_chg_amt] &gt; 0\n AND LEFT([b].[PTNO_NUM], 1) != @PTNO_NUM_Rule2\n AND LEFT([b].[PTNO_NUM], 4) != @PTNO_NUM_Rule3\n AND [b].[Dsch_Date] &gt;= @Dsch_Date_Start\n LEFT OUTER JOIN [smsdss].[c_geocoded_address] AS [c] \n ON [b].[PtNo_Num] = [c].[Encounter] \n AND [c].[Encounter] IS NULL\n ;\n\nEND \n\nGO\n</code></pre>\n<h2>Possible R script:</h2>\n<pre><code>library(RODBCext)\n\ndbhandle &lt;- odbcDriverConnect('driver={SQLServer};server=xxx;database=xxx;trusted_connection=true') \n\nsqlText &lt;- paste(&quot;EXEC [dbo].[Patient_Addresses] @Dsch_Date_Start='01-JAN-2019', @addr_line1_Rule1='101 HOSPITAL RD', @PTNO_NUM_Rule2='2', @PTNO_NUM_Rule3='1999', @Plm_Pt_Acct_Type_Invoice='I'&quot;)\n\ndata &lt;-sqlExecute(channel = dbhandle\n, query = sqlText\n, data = list(PtNo_Num, FullAddress, Pt_Addr_Zip, PartialAddress)\n, fetch = TRUE) \n\nodbcCloseAll() \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:37:32.750", "Id": "251881", "ParentId": "233712", "Score": "2" } } ]
{ "AcceptedAnswerId": "251881", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T17:55:18.190", "Id": "233712", "Score": "2", "Tags": [ "sql-server", "r" ], "Title": "Reading customer data" }
233712
<p>I have created a wrapper for displaying messages with ArcPy and IDLE (as that is all I have available to myself due to certain circumstances) as I frequently use both to test and develop new tools. However I find myself repeating <code>print</code> statements and <code>arcpy</code> functions to display feedback.</p> <p>Unfortunately, it has to be in compatible with Python 2.7.</p> <pre class="lang-py prettyprint-override"><code>"""REMOVED HEADER""" import sys from time import strftime import arcpy def display_title(title, char_limit=100): # Format the title, and provide a border above and below to seperate the # title title = ("\n{0}\n{1:^" + str(char_limit) + "}\n{0}\n").format( "-" * char_limit, title.upper()) # Display the title print(title) arcpy.AddMessage(title) def display_message(message, char_limit=100): # Add the time to the message, and this will also run the # beautify_message function message = add_time_to_message(message, char_limit) # Display the message print(message) arcpy.AddMessage(message) def display_warning(message, char_limit=100): # Add the time to the message, and this will also run the # beautify_message function message = add_time_to_message("WARNING: " + message, char_limit) # Display the message print(message) arcpy.AddWarning(message) def display_error(message, char_limit=100, traceback=False): # Add the time to the message, and this will also run the # beautify_message function message = add_time_to_message("Error" + message, char_limit) # Add the Python traceback information (if available) if traceback: tracebackInfo = traceback.format_exc() if tracebackInfo != "None\n": message += "\n\nPython Traceback Information:\n" message += tracebackInfo # Display the message print(message) arcpy.AddError(message) # Terminate the Script now sys.exit() def display_parameters(parameters, char_limit=100): # Make sure that the input type is correct if isinstance(parameters, tuple) or isinstance(parameters, list): if len(parameters) &gt; 1: # Then there is more than one, print a list var_string = "Parameter list:\n" for var in parameters: var_string += "{} = {}\n".format(var[0], var[1]) # Remove the last "\n" var_string[:-1] else: var_string = "{} = {}".format(parameters[0][0], parameters[0][1]) # Format the message string message = add_time_to_message(var_string, char_limit) # Display the message print(message) arcpy.AddMessage(message) # Format the message so it displays nicely within the progress box def beautify_message(message, char_limit=100): # Create an empty list of beautified lines processed_lines = [] # Split the message into lines that are defined with a new line split_message = message.split("\n") # Loop through the each split line for line in split_message: # Set the counter to zero counter = 0 # Loop though each split line to check the length while len(line) &gt; char_limit: # Then this line is too long, split it up split_line = line[counter:(counter + 1) * char_limit] # Capture the last space just in case space = True if split_line[-1] == " " else 0 # Split it on spaces split_line = split_line.split() # Add the chunk to lines processed_lines.append(" ".join(split_line[:-1])) # Take the left over bit and add it back to line line = split_line[-1] + " " * space + line[( counter + 1) * char_limit:] # Add the last bit to lines processed_lines.append(line) # Return the final output return processed_lines # Add the timestamp and indent message def add_time_to_message(message, char_limit=100): # Determine the current time in string format to be included in some # messages current_time = strftime("%x %X") + " - " # Determine the limit for each line if including the time limit = char_limit - len(current_time) # Break the message up into lines of the right length lines = beautify_message(message, limit) # Add the time and the first line message = current_time + lines[0] + "\n" # Add the rest of the lines for line in lines[1:]: message += " " * len(current_time) + line + "\n" # Remove the extra "\n" character message = message[:-1] # Return the final output return message </code></pre> <p>Any and all constructive criticism welcome!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:16:43.777", "Id": "233713", "Score": "6", "Tags": [ "python", "python-2.x", "arcpy" ], "Title": "Python - Displaying messages in ArcPy/IDLE" }
233713
<p>This is a simple password generator. What do you think about it? I am learning C for a while at school and at home. This just has a mix of symbols, lowercase, uppercase and numbers, with a configurable length.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main() { int i = 0; int n = 0; int randomizer = 0; srand((unsigned int)(time(NULL))); char numbers [] = "1234567890"; char letter [] = "abcdefghijklmnoqprstuvwyzx"; char letterr [] = "ABCDEFGHIJKLMNOQPRSTUYWVZX"; char symbols [] = "!@#$%^&amp;*(){}[]:&lt;&gt;?,./"; printf("\nHow long password:"); scanf("%d", &amp;n); char password[n]; randomizer = rand() % 4; for (i=0;i&lt;n;i++) { if(randomizer == 1) { password[i] = numbers[rand() % 10]; randomizer = rand() % 4; printf("%c", password[i]); } else if (randomizer == 2) { password[i] = symbols[rand() % 26]; randomizer = rand() % 4; printf("%c", password[i]); } else if (randomizer == 3) { password[i] = letterr[rand() % 26]; randomizer = rand() % 4; printf("%c", password[i]); } else { password[i] = letter[rand() % 21]; randomizer = rand() % 4; printf("%c", password[i]); } } return main(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:07:55.710", "Id": "456946", "Score": "5", "body": "This is a very small subset of Unicode passwords." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:10:04.403", "Id": "457001", "Score": "11", "body": "Don’t actually use passwords generated with this for anything, by the way – beyond the bias Edward mentioned, `rand()` is weak, predictable, and reversible on most platforms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T09:42:10.710", "Id": "457016", "Score": "9", "body": "You should treat all characters equally, otherwise you reduce the randomness of the distribution. With your current approach, a given numeric character is more than twice as likely as any non-numeric character P(\"1\") = 1/4 * 1/10 = 1/40, P(\"A\") = 1/4 * 1/26 = 1/104" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:14:20.950", "Id": "457262", "Score": "3", "body": "Variable name `letterr` for capital letters seems lazy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:34:06.710", "Id": "457464", "Score": "2", "body": "This assignment doesn't require that something from each group be used, so why even have groups? I.e. use `\"1234567890abc…xyzABC…XYZ!@#$%^&*(){}[]:<>?,./\"`, and most of the other code will collapse into one small loop. — Or better yet, assuming ASCII, just pick a random integer between 33 and 126 and use that as the character and you don't even need a list of characters." } ]
[ { "body": "<p>Take this line from every branch and put it at the end of the loop:</p>\n\n<blockquote>\n<pre><code>printf(\"%c\", password[i]);\n</code></pre>\n</blockquote>\n\n<p>Take this from every branch and put it at the start of the loop (and delete it from before the loop):</p>\n\n<blockquote>\n<pre><code>randomizer = rand() % 4;\n</code></pre>\n</blockquote>\n\n<p>As Schwern observes, you can also turn the <code>if</code> chain into a <code>switch</code>/<code>case</code>, which is a bit faster and easier to read.</p>\n\n<p>This makes the loop look like:</p>\n\n<pre><code>for (i=0;i&lt;n;i++)\n{\n randomizer = rand() % 4;\n switch (randomizer) {\n case 1:\n password[i] = numbers[rand() % 10];\n break;\n case 2:\n password[i] = symbols[rand() % 26];\n break;\n case 3:\n password[i] = letterr[rand() % 26];\n break;\n default:\n password[i] = letter[rand() % 21];\n break;\n }\n printf(\"%c\", password[i]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:07:04.863", "Id": "456945", "Score": "0", "body": "Why stop? `struct { char *const str; size_t n; } table[] = { { numbers, sizeof numbers - 1 }, { symbols, sizeof symbols - 1 }, ... }, *t; for(i = 0; i < n; i++) t = table + rand() % (sizeof table / sizeof *table), password[i] = t->str(rand() % t->n);`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:39:22.170", "Id": "233717", "ParentId": "233715", "Score": "7" } }, { "body": "<p>I see some things that I think could help you improve your code.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>All of the logic here is in <code>main</code> in one rather long and dense chunk of code. It would be better to decompose this into separate functions.</p>\n\n<h2>Check return values for errors</h2>\n\n<p>The call to <code>scanf</code> can fail. You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources. Rigorous error handling is the difference between mostly working versus bug-free software. You should strive for the latter.</p>\n\n<h2>Use more whitespace to enhance readability of the code</h2>\n\n<p>Instead of crowding things together like this:</p>\n\n<pre><code>for (i=0;i&lt;n;i++)\n</code></pre>\n\n<p>most people find it more easily readable if you use more space:</p>\n\n<pre><code>for (i=0; i &lt; n; i++)\n</code></pre>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>Instead of hard-coding the constants 26 and 4 in the code, it would be better to use a <code>#define</code> or <code>const</code> and name them.</p>\n\n<h2>Avoid <code>scanf</code> if you can</h2>\n\n<p>There are so many <a href=\"http://stackoverflow.com/questions/2430303/disadvantages-of-scanf\">well known problems with <code>scanf</code></a> that you're usually better off avoiding it. </p>\n\n<h2>Don't recursively call <code>main</code></h2>\n\n<p>The <code>main()</code> function can be called recursively in C, but it's a bad idea. You could blow up your stack and there's really no good reason to do that here. Just use a loop. See <a href=\"https://stackoverflow.com/questions/4238179/calling-main-in-main-in-c\">https://stackoverflow.com/questions/4238179/calling-main-in-main-in-c</a> for details.</p>\n\n<h2>Use a better random number generator</h2>\n\n<p>You are currently using </p>\n\n<pre><code>password[i] = numbers[rand() % 10];\n</code></pre>\n\n<p>There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See <a href=\"http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130\">this answer</a> for details, but I'd recommend changing that to the <code>rand_lim</code> in that link and also duplicated below.</p>\n\n<h2>Results</h2>\n\n<p>Here's an alternative that uses all of these ideas. It also gets a length from the command line so there's no need for a prompt or <code>scanf</code>. It eliminates the need for counting characters and uses the better random number generator mentioned above:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n#include &lt;string.h&gt;\n\nint rand_lim(int limit) {\n/* return a random number between 0 and limit inclusive.\n */\n\n int divisor = RAND_MAX/(limit+1);\n int retval;\n\n do { \n retval = rand() / divisor;\n } while (retval &gt; limit);\n\n return retval;\n}\n\nchar picker(const char *charset) {\n return charset[rand_lim(strlen(charset)-1)];\n}\n\nint main(int argc, char *argv[])\n{\n if (argc != 2) {\n puts(\"Usage: pwgen len\");\n return 1;\n }\n int len = atoi(argv[1]);\n if (len &lt;= 0) {\n puts(\"Length must be a positive non-zero integer\"); \n return 2;\n }\n const char* groups[] = {\n \"1234567890\", // numbers\n \"abcdefghijklmnoqprstuvwyzx\", // lowercase\n \"ABCDEFGHIJKLMNOQPRSTUYWVZX\", // uppercase\n \"!@#$%^&amp;*(){}[]:&lt;&gt;?,./\", // symbols\n };\n const size_t numGroups = sizeof(groups)/sizeof(groups[0]);\n srand((unsigned int)(time(NULL)));\n\n // only proceed if we got a number\n for ( ; len; --len) {\n unsigned group = rand_lim(numGroups-1);\n putchar(picker(groups[group]));\n }\n putchar('\\n');\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:02:45.700", "Id": "457414", "Score": "1", "body": "I like most of your suggestions. But I think the biggest problem in OP's sample is use of a poor random generator to make a \"random\" password. I take issue with the *Use a better random number generator* section recommend to replace `rand()` with `rand() / 10`. Point to `getrandom()` or `RtlGenRandom()` or even `/dev/urandom`. The treatment of uniformity in your code sample is a good consideration. On some platforms, you can use the `arc4random_uniform()` function to generate numbers in uniform range without rolling your own. (Unfortunately, it's not in Linux libc.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:17:13.153", "Id": "457417", "Score": "0", "body": "@ConradMeyer: I chose to approach the problem with portability in mind, hence `rand_lim` uses only standard library functions. As for the larger problem, I'd go further and say that this entire password generation approach [is deeply flawed](https://xkcd.com/936/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T19:38:12.787", "Id": "457579", "Score": "1", "body": "The C standard doesn't require implementations to provide a real random number generator, but any real implementation that you'd be writing a program like this for does. Portability is generally a good aspiration, but doesn't mean we should be providing dangerous examples of \"corrected\" password generator code that uses non-random inputs. People really do copy/paste code off of stackoverflow, and those people are the same ones who are going to think `rand`/`random` are random. Anyway, that's just my opinion. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:52:30.140", "Id": "462914", "Score": "0", "body": "Did you intend \"don't use `scanf` because it's unreliable, better use `atoi`\" to be a joke, or was it an accident?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:40:54.760", "Id": "233718", "ParentId": "233715", "Score": "38" } }, { "body": "<p>There is a bug in this line:</p>\n\n<pre><code>password[i] = symbols[rand() % 26];\n</code></pre>\n\n<p><code>symbols</code> is only 21 characters long, so this line triggers undefined behavior when <code>rand() % 26</code> is greater than 21 (and when <code>rand() % 26</code> is exactly 21, it puts a null byte in the password). You meant for this 26 to go with <code>letter</code> instead, and for the 21 to go with <code>symbols</code>.</p>\n\n<p>This would be less likely to happen if you avoid using \"magic\" numbers. The error is harder to make (or at least, easier to spot) if you write this instead:</p>\n\n<pre><code>password[i] = symbols[rand() % (sizeof symbols - 1)]\n</code></pre>\n\n<p>Of course, you can also <code>#define</code> a macro (as Edward's answer also suggests), but I would still define it using <code>sizeof</code>:</p>\n\n<pre><code>#define NUM_SYMBOLS (sizeof symbols - 1)\n</code></pre>\n\n<p>Using <code>sizeof</code> to calculate the size, rather than using a literal value like <code>26</code>, ensures that you will not forget to update the count if the size of the array changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:18:03.620", "Id": "233747", "ParentId": "233715", "Score": "14" } }, { "body": "<p>I don't know if this is just an exercise to learn about working with strings and numbers, or if you ever intend to use this to generate real passwords. But if you do, this line can be a serious problem:</p>\n\n<pre><code>srand((unsigned int)(time(NULL)));\n</code></pre>\n\n<p>Since you are using the current time, in seconds, to seed the pseudo-random number generator, you have severly limited the number of possible passwords. If I know which day you ran this program to generate a password, there are only 86400 possible passwords I need to test. That's an entropy of 16 bits. If I can guess the hour, you are down to 12 bits. And if I know the exact time, perhaps because your mail with encrypted text has it in the headers, I <em>know</em> your password.</p>\n\n<p>(<code>RAND_MAX</code> is only guaranteed by the standard to be at least 32767, which would correspond to 15 bits of entropy, but on my machine it is 2147483647, which is 31 bits of entropy.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:47:45.417", "Id": "457409", "Score": "0", "body": "I agree! I think this is the biggest problem. `rand()` looks like a random number interface, but it very much isn't. It's not even a good fast simulation generator. Be careful not to confuse the *range* of `rand()` with *entropy*, though. Your `rand` has a 31-bit range but 0 bits of entropy. OP would be well served to learn about `getrandom()` or `getentropy()` if supported by their development platform, or simply opening `/dev/urandom` if not. (Or pick any of the secure CSPRNG APIs on Windows 10+ — they're all backed by the same, good algorithm.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:57:33.020", "Id": "462915", "Score": "0", "body": "`RAND_MAX` is independent of the entropy of the random number generator. Just adding `srand_bytes(const char *, size_t)` to the API could improve the entropy without touching `RAND_MAX`. This means your argument is flawed. `RAND_MAX` only describes the entropy of a single call to `rand()`, and for that, an entropy of 15 bits is enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:01:29.837", "Id": "462917", "Score": "0", "body": "@RolandIllig: Yes, I agree that RAND_MAX isn't really relevant to the entropy of the generated passwords." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:05:45.947", "Id": "233756", "ParentId": "233715", "Score": "10" } }, { "body": "<p>This is a good start!<br>\nYou do have a couple of bugs though. Firstly, these two lines:</p>\n\n<pre><code> password[i] = symbols[rand() % 26];\n</code></pre>\n\n<p>and</p>\n\n<pre><code> password[i] = letter[rand() % 21];\n</code></pre>\n\n<p>seem to have their numbers mixed up - swap the <code>21</code> and <code>26</code> here.</p>\n\n<p>Secondly, this line is bad practice. It may work, but is not the 'right' way to do this. My coding teacher would have had a hissy-fit if they'd seen this! </p>\n\n<pre><code>char password[n];\n</code></pre>\n\n<p>I was taught that variable declarations should pretty much always be right at the top of a function. The 'right' way to deal with this is to simply declare a char pointer, and then use <code>malloc</code> to allocate the correct amount of memory to the string when you know it's size, and don't forget to free the memory when it's no longer being used.</p>\n\n<pre><code>char *password = NULL;\n\nprintf(\"\\nHow long password:\");\nscanf(\"%d\", &amp;n);\n\npassword = (char *)malloc((n + 1) * sizeof(char)); /* String length +1 for NULL terminator */\n\n...\n\nfree(password);\n</code></pre>\n\n<p>Thirdly, sanitize your inputs - always assume your end user is the world's biggest idiot, and when asked to enter <code>How long password:</code>, may just enter <code>twelve</code> as their answer, or even just <code>cabbage</code>. A simple loop can do this, and a minor change to your prompt can help reduce invalid answers that crash your program:</p>\n\n<pre><code> do\n {\n printf(\"\\nHow long password (8-32):\");\n scanf(\"%d\", &amp;n);\n } while ((n &lt; 8) || (n &gt; 32));\n\n</code></pre>\n\n<p>Fourthly, I would personally use <code>switch</code>/<code>case</code> rather than <code>if</code>/<code>else</code> <code>if</code>/<code>else</code>, but that is just a personal preference in this case.</p>\n\n<p>Finally, I can only agree with everything in Edward's response.</p>\n\n<p>Here is your code with the changes I'd make:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\n#define ALPHA_SIZE 26\n#define NUM_SIZE 10\n#define SYM_SIZE 21\n\nvoid main()\n{\n int i, n;\n char *password = NULL;\n\n srand((unsigned int)(time(NULL)));\n\n do\n {\n printf(\"\\nHow long password (8-32):\");\n scanf(\"%d\", &amp;n);\n } while ((n &lt; 8) || (n &gt; 32));\n\n password = (char *)malloc((n + 1) * (sizeof(char)));\n printf(\"%s\", makePassword(password, n));\n\n free(password);\n}\n\nchar *makePassword(char *pwd, int pwd_length)\n{\n int i, randomizer;\n char numbers[] = \"1234567890\";\n char letter[] = \"abcdefghijklmnoqprstuvwyzx\";\n char letterr[] = \"ABCDEFGHIJKLMNOQPRSTUYWVZX\";\n char symbols[] = \"!@#$%^&amp;*(){}[]:&lt;&gt;?,./\";\n\n for (i=0; i&lt;pwd_length; i++)\n {\n randomizer = rand() % 4;\n\n switch(randomizer)\n {\n case 0: pwd[i] = getPwdChar(numbers, NUM_SIZE);\n break;\n\n case 1: pwd[i] = getPwdChar(letter, ALPHA_SIZE);\n break;\n\n case 2: pwd[i] = getPwdChar(letterr, ALPHA_SIZE);\n break;\n\n case 3: pwd[i] = getPwdChar(symbols, SYM_SIZE);\n break;\n\n default: break;\n }\n }\n password[pwd_length] = NULL;\n\n return (pwd);\n}\n\nchar getPwdChar(char *charlist, int len) \n{\n return (charlist[(rand() / (RAND_MAX / len))]);\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:58:02.933", "Id": "457038", "Score": "44", "body": "*I was taught that variable declarations should pretty much always be right at the top of a function.* I disagree; variables should not be declared until they are initialized, and in the smallest possible scope, to avoid accidentally \"leaking\" values from commonly used variable names like `i` and `n`, and to increase the chance you will get a compiler error or warning if you make a mistake. \"Always put your variables at the top of a function\" is a holdover from C89 when all variables *had* to be declared at the top of a function. Today, it's bad advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:02:08.157", "Id": "457042", "Score": "14", "body": "Also, while I would also use `malloc` here, it's not *more correct* than using a VLA (variable-length array). Your teacher may have had a fit but that's just their opinion, not gospel truth. What *is* gospel truth is that `void main()` is non-standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:07:09.337", "Id": "457163", "Score": "12", "body": "@StefanCole \"I was taught that variable declarations should pretty much always be right at the top of a function.\" The days of C89 are long past us." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:08:44.460", "Id": "457164", "Score": "7", "body": "`rand() % 21` I think this causes a modulo bias, because RAND_MAX isn't perfectly divisible by 21." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:17:25.020", "Id": "457234", "Score": "6", "body": "C89 requires variables to be defined at beginning of scope blocks, which is wider than just the start of functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:38:42.927", "Id": "457323", "Score": "3", "body": "`void main` should be `int main`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:04:53.717", "Id": "457415", "Score": "0", "body": "`rand()` is an unfortunately named legacy C API. I'd suggest using one of the interfaces designed to generate numbers for secrets like passwords: `getrandom()` on Unix (or `getentropy()` on OpenBSD), `RtlGenRandom()` on Windows. That said, @Alexander-ReinstateMonica's point about bias is still a factor and Edward's answer shows a construction to correctly avoid it. If you're on a BSD platform, there is also the libc `arc4random_uniform()`, which generates a (good) random number with uniform probability in some range up to `UINT32_MAX - 1`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:53:32.330", "Id": "457441", "Score": "2", "body": "*may just enter 'twelve' as their answer, or even just 'cabbage'.* or may enter `Ctrl+D` and send EOF as an input. I've seen some programs to crash in a funny way when treated like this. I'm not sure your loop would work properly when treated this way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:51:25.990", "Id": "457465", "Score": "0", "body": "Many more compilers support C89 than C99. It depends what one is doing. _Eg_, [MSVC conformance with C](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#C) and [Does MSVC2017 fully support C99](https://stackoverflow.com/questions/48615184/does-visual-studio-2017-fully-support-c99)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:17:22.913", "Id": "457529", "Score": "2", "body": "@Neil MSVC is a C++ compiler. C++ also allows declaring variables anywhere in the code, although it does not have VLAs. Anyway, the OP is clearly using C99 (or later), so I'm not sure what your point is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:06:37.510", "Id": "457582", "Score": "1", "body": "@trentcl my point is . . . what was my point? . . . just because it's old, doesn't mean it's not relevant; especially when the suggestion is fundamentally different wrt allocation. However, you have a point, this is C99 code, and passwords generally have a practical length limit." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:45:34.293", "Id": "233764", "ParentId": "233715", "Score": "6" } }, { "body": "<ol>\n<li><p>Don't initialize dynamic character arrays with a character string. I.e. don't, for an (implicitly) auto variable, write:</p>\n\n<pre><code>char numbers [] = \"1234567890\";\n</code></pre>\n\n<p>As written, the array is copied from a constant to an automatic variable at run time.\nInstead write:</p>\n\n<pre><code>char *numbers = \"1234567890\";\n</code></pre>\n\n<p>Or better still:</p>\n\n<pre><code>char const *const numbers = \"1234567890\";\n</code></pre>\n\n<p>Alternatively, move it outside the function to make it global, or declare it static (in which case the array is initialized at compile and load time). Thus, it is also reasonable to write something like:</p>\n\n<pre><code>static char const numbers[] = \"1234567890\";\n</code></pre></li>\n<li><p>Don't use <code>rand()</code> and <code>srand()</code>. They really are just to old and decrepit. At the very least, use <code>rand48()</code> and <code>srand48()</code>. Better still, find a cryptographic grade random number generator and use that. This goes along with a previously mentioned \"don't use <code>scanf()</code>\". (There are a few other functions you shouldn't touch, like <code>gets()</code>.)</p></li>\n<li><p>If you try to develop this more fully, you may start getting extra restrictions, like don't use both \"0\" and \"O\", or both \"1\" and \"l\". These two are about eliminating confusing characters. Another might be to change the symbol set, as many sites use restricted symbol sets. (And I note you already eliminated \", ', `, and ; yourself.) Thus, I suggest dynamically building a single list of acceptable characters, and using a dynamic length for said list.</p></li>\n<li><p>Personally, I've always like generating passwords by generating cryptographic-grade random characters (i.e. 8 bit samples) and then discarding unacceptable (unprintable) characters. I'm sure there are reasons why this isn't good.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:43:37.390", "Id": "457282", "Score": "0", "body": "Why not `static const char numbers[] = \"1234567890\";` inside the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:38:44.340", "Id": "457295", "Score": "0", "body": "@Martin: That is fine either inside or outside the function. The point was to have it compile/load time initialized instead of run time initialized. I did say \"make it global, or declare it static\". One can of course do both, though the sematics of static at the global scope are different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:21:56.937", "Id": "457404", "Score": "0", "body": "4) is perfectly fine as long as you simply remove the unprintable characters and then repeat until you've got a long enough string. This is one of the standard ways how to get unbiased modulo N random numbers. The JDK does it this way (loop until you get a number smaller than the largest number that cannot be mapped unbiased into the different buckets)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:51:44.847", "Id": "457410", "Score": "0", "body": "I'd suggest avoiding any of the non-cryptographic unseeded libc PRNGs, including `rand48`. Just skip directly to `getrandom()`, or if you're on an older platform, `/dev/urandom`, or on Windows (especially 10+), there are good CSPRNG APIs available there that I don't memorize the names for :-)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T03:26:31.760", "Id": "233835", "ParentId": "233715", "Score": "3" } }, { "body": "<p>Coming back to the already mentioned recursively main logic.</p>\n\n<p>If you run the program logic to often with that you can generate a stack overflow and run out of memory.</p>\n\n<p>You can use a forever loop instead:</p>\n\n<pre><code>int main()\n{\n for(;;) {\n // youre code here\n }\n return 0;\n}\n</code></pre>\n\n<p>Another advantage of changing to <code>for(;;)</code> not mentioned yet:\nThis way you can also refactor some stuff out before the <code>for(;;)</code> like the constants.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:11:46.930", "Id": "457274", "Score": "0", "body": "It's a good point, but I did actually mention that in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:12:57.117", "Id": "457276", "Score": "0", "body": "you are right I over read it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:08:37.687", "Id": "233883", "ParentId": "233715", "Score": "1" } }, { "body": "<p>Previous commenters have alluded to the fact that the rand() function provided by programming language libraries is at best pseudorandom and incapable of providing secure passwords. It would be reasonable to use the /dev/random device (<a href=\"https://en.wikipedia.org/wiki//dev/random\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki//dev/random</a>) on unix-like systems, or the Microsoft library CryptGenRandom on Windows systems (<a href=\"https://en.wikipedia.org/wiki/CryptGenRandom\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/CryptGenRandom</a> -- lighter-weight alternative here: <a href=\"https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/</a>) as sources of randomness, as these use observed external events (e.g., from device drivers) to generate a random number pool rather than using a pseudorandom generator whose outputs can be predicted. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:55:49.223", "Id": "457412", "Score": "0", "body": "Hi Eric! I totally agree that use of `rand` is concerning here and agree with your suggested replacements. One language quibble, though: `rand` isn't \"at best pseuodrandom.\" It's explicitly required to be a deterministic sequence generator by the C standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:57:38.030", "Id": "457437", "Score": "0", "body": "Good point. My comment \"at best pseudorandom\" referred to the real concern that the rand() implementation could itself be defective. Don't laugh! -- some nice examples are given [here](https://inst.eecs.berkeley.edu/~cs161/fa08/Notes/random.pdf)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T19:30:13.833", "Id": "457578", "Score": "0", "body": "Ah, sure. \"Nine, nine, nine, nine...\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:05:12.400", "Id": "233895", "ParentId": "233715", "Score": "2" } } ]
{ "AcceptedAnswerId": "233718", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T18:29:10.447", "Id": "233715", "Score": "23", "Tags": [ "c", "random", "generator" ], "Title": "Random password generator in C" }
233715
<p>With some basic knowledge of Python and referring a lot of sources, I have written the code below. But it takes half an hour for execution. How can I reduce the time? I read about vectorization but not understanding how exactly I can use it here.</p> <p>In this, I have to read 2D skeleton images( Size 1980x1080) and Depth images (size 512x424). As I have to do mapping of both the images of different sizes and form a 3D Skelton, depth_to_xyz_and_rgb(uu, vv, dep) function does that. Here the skeleton Image is generated from the OpenPose Library of Facebook. The skeleton image mainly has 25 key-points and those 25 key-points are joined together to form a 2D skeleton. The main task is to calculate Gait Parameters which could be found out if we know the 3D co-ordinate of each joint. Initially, I was generating 3D Point cloud to view if the code generates it properly or not and as the code was generating it properly and I didn't need the point cloud file for further processing, I have removed that part of code.</p> <p>Now here I am mainly saving the 2D skeleton location of 25 key-points of a skeleton and 3D values of 25 key-points. I have added a sample of generated excel file as a sample in the link below. </p> <pre><code>import math import sys from PIL import Image import numpy as np import scipy.io as sio import os scalingFactor = 5000.0 fx_d=365.3768 fy_d=365.3768 cx_d=253.6238 cy_d=211.5918 fx_rgb=1054.8082 fy_rgb=1054.8082 cx_rgb=965.6725 cy_rgb=552.0879 RR = np.array([ [0.99991, -0.013167,-0.0020807], [0.013164,0.99991,-0.0011972], [-0.0020963,0.0011697,1] ]) TT = np.array([ 0.052428,0.0006748,0.000098668 ]) extrinsics=np.array([[.99991,-0.013167,-0.0020807,0.052428],[0.013164,0.99991,-0.0011972,0.0006748],[-0.0020963,0.0011697,1,0.000098668],[0,0,0,1]]) path = 'G:\\SENDA\\Proband_172\\GAIT\\RG1_color\\mat\\' file_lists = os.listdir(path) path3 = 'G:\\SENDA\\Proband_123\\GAIT\\RG1_Depth\\selected\\' included_extensions = ['bmp'] file_lists3 = [fn for fn in os.listdir(path3) if any(fn.endswith(ext) for ext in included_extensions)] path4 = 'G:\\SENDA\\Proband_123\\GAIT\\RG1_results\\skeleton\\' file_lists4 = os.listdir(path4) path6 = 'G:\\SENDA\\Proband_123\\GAIT\\RG1_results\\' file_lists6 = os.listdir(path6) def init_maxvalue(): for center in centers3: if center==(0,0): continue min_xy.append(sys.float_info.max) min_vex.append((0,0)) p_vex.append((0,0,0)) def depth_rgb_registration(rgb,depth): # f=open("RecordAll.xls",'w') # Taking second argument i.e the depth image name init_maxvalue() rgb = Image.open(rgb) depth = Image.open(depth).convert('L') # convert image to monochrome if rgb.mode != "RGB": raise Exception("Color image is not in RGB format") for v in range(depth.size[0]): for u in range(depth.size[1]): try: (p,x,y)=depth_to_xyz_and_rgb(v,u,depth) # this gives p = [pcx, pcy,pcz] #aligned(:,:,0) = p except: continue if (x &gt; rgb.size[0]-1 or y &gt; rgb.size[1]-1 or x &lt; 1 or y &lt; 1 or np.isnan(x) or np.isnan(y)): continue x = round(x) y = round(y) color=rgb.getpixel((x,y)) #print(color) min_distance((x,y),p) if color==(0,0,0): p[0]=0 p[1]=0 p[2]=0 continue #if.write("%f .%f %f \n"%(p[0],p[1],p[2])) points.append(" %f %f %f %d %d %d 0\n"%(p[0],p[1],p[2],255,0,0)) i=0 x=[] y=[] z=[] for val in min_vex: f.write(str(val)+' '+str(p_vex[i])+''); points.append(" %f %f %f %d %d %d 0\n"%(p_vex[i][0],p_vex[i][1],p_vex[i][2],0,255,0)) x.append(p_vex[i][0]) y.append(p_vex[i][1]) z.append(p_vex[i][2]) i=i+1 else: f.write("\n") # f.close() def min_distance(val,p): i=0 for center in centers3: if center==(0,0): continue temp=math.sqrt(math.pow(center[0]-val[0],2)+math.pow(center[1]-val[1],2)) if temp&lt;min_xy[i]: min_xy[i]=temp min_vex[i]=val p_vex[i]=p i=i+1 def depth_to_xyz_and_rgb(uu , vv,dep): # get z value in meters pcz =dep.getpixel((uu, vv)) if pcz==60: return pcx = (uu - cx_d) * pcz / fx_d pcy = (vv - cy_d) * pcz / fy_d # apply extrinsic calibration P3D = np.array( [pcx , pcy , pcz] ) P3Dp = np.dot(RR , P3D) - TT # rgb indexes that P3D should match uup = P3Dp[0] * fx_rgb / P3Dp[2] + cx_rgb vvp = P3Dp[1] * fy_rgb / P3Dp[2] + cy_rgb # return a point in the point cloud and its corresponding color indices return P3D , uup , vvp if __name__ == '__main__': f=open("Proband_123_RG1.xls",'w') for idx, list1 in enumerate(file_lists4): # Iterate through items of list2 for i in range(len(file_lists3)): if list1.split('.')[0] == file_lists3[i].split('.')[0]: rgb = os.path.join(path4, list1) depth = os.path.join(path3,sorted(file_lists3)[i]) m = sorted(file_lists)[idx] mat2 = sio.loadmat(os.path.join(path,m)) abc= list1.split('.')[0] centers2 = mat2['b2'] centers3 =np.array(centers2).tolist() min_xy=[] min_vex=[] p_vex=[] image_list = [] image_list2 = [] points = [] depth_rgb_registration(rgb,depth) f.close </code></pre> <p>The below part of the code takes maximum time for execution because it does Rotation and Translation for almost every pixel considering first depth image. In my images, RGB images have a lot of zeros, so if this process can be reversed then it could reduce the time I think. I just got an idea and I am working on it. <a href="http://nicolas.burrus.name/index.php/Research/KinectCalibration" rel="nofollow noreferrer">Link for algorithm</a></p> <pre><code>def depth_to_xyz_and_rgb(uu , vv,dep): # get z value in meters pcz =dep.getpixel((uu, vv)) if pcz==60: return pcx = (uu - cx_d) * pcz / fx_d pcy = (vv - cy_d) * pcz / fy_d # apply extrinsic calibration P3D = np.array( [pcx , pcy , pcz] ) P3Dp = np.dot(RR , P3D) - TT # rgb indexes that P3D should match uup = P3Dp[0] * fx_rgb / P3Dp[2] + cx_rgb vvp = P3Dp[1] * fy_rgb / P3Dp[2] + cy_rgb # return a point in the point cloud and its corresponding color indices return P3D , uup , vvp </code></pre> <ul> <li>Link for images and mat files <a href="https://drive.google.com/drive/u/1/folders/1cGcBaqDD_OckufO5keAT0WClMkOGq-Kf" rel="nofollow noreferrer">Images and Mat files</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:18:54.613", "Id": "456930", "Score": "0", "body": "What's the size of the input images? Have you tried profiling smaller inputs to see what the scaling looks like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:46:37.053", "Id": "456940", "Score": "0", "body": "@mast Skeleton images are of 6MB and Depth data is of 214 KB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:35:26.377", "Id": "457060", "Score": "0", "body": "Also, what's the 3D point cloud formed of? The skeleton, the background? If you could maybe post images of what the expected result is, I'm pretty sure I can help you out :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T13:33:48.450", "Id": "467333", "Score": "0", "body": "\"Expecting reduction in time to atleast 5 minutes\" is a pretty unreasonable expectation, when you're asking random people for IP." } ]
[ { "body": "<p>There are several things that make it is needlessly difficult to figure out what this code is supposed to do. </p>\n\n<ul>\n<li>Using lots of global variables (<code>f</code>, <code>min_xy</code>, <code>min_vex</code>, etc.) for passing data in to and out of functions makes it difficult to see when a \nvariable's value might be set or changed. </li>\n<li>Many variables with similar, non-descriptive names (<code>list1</code>, <code>list3</code>, \n<code>center2</code>, <code>center3</code>, etc.) make it more difficult to figure out what the variables purpose is.</li>\n<li>No docstrings describing what a function does or how it is used.</li>\n</ul>\n\n<p>Presuming your system isn't too old, it's likely that the processor has multiple cores. So one way to speed things up would be to use the <code>multiprocessing</code> library. First, create a list of <code>(rgb_file, depth_file)</code> pairs.\nThen use a process pool to process the list.</p>\n\n<p>Something like:</p>\n\n<pre><code>from multiprocessing import Pool\n\nfrom collections import default dict\nfrom pathlib import Path\n\n\ndef process_pair(rgb, depth):\n # code to process one image goes here\n ...\n\n\nif __name__ == '__main__':\n\n base = Path('G:/SENDA/Proband_123/GAIT')\n skeleton_path = base / 'RG1_results/skeleton'\n image_path = base / 'RG1_Depth/selected'\n\n rgb_depth_pairs = defaultdict(list)\n\n for skeleton in skeleton_path.iterdir():\n rgb_depth_pairs[skeleton.stem].append(skeleton)\n\n included_extensions = ['bmp']\n images = [fn for ext in included_extensions for fn in image_path.glob(f'*.{ext}')]\n\n for image in images:\n rgb_depth_pairs[image.stem].append(image)\n\n rgb_depth_pairs = [item for item in rgb_depth_pairs.items() if len(item)==2]\n\n\n with Pool() as p:\n p.starmap_async(process_pairs, rgb_depth_pairs)\n</code></pre>\n\n<p>(Note: This code has not been tested or otherwise debugged)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-08T16:52:13.390", "Id": "467889", "Score": "0", "body": "Yes. I should have given some more details about the code. Still learning to write code in Python. I will try to do what you said above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-08T07:27:57.020", "Id": "238553", "ParentId": "233722", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:33:44.873", "Id": "233722", "Score": "6", "Tags": [ "python", "numpy", "opencv" ], "Title": "Dealing with lot of images and multiplications" }
233722
<p>I need to implement <a href="https://www.boost.org/doc/libs/1_71_0/doc/html/boost_asio/reference/basic_stream_socket/async_read_some.html" rel="nofollow noreferrer">async_read_some</a> from Boost Asio. The reason is here <a href="https://stackoverflow.com/questions/59223064/implementing-behaviour-of-boostasio-for-a-class">https://stackoverflow.com/questions/59223064/implementing-behaviour-of-boostasio-for-a-class</a> but I don't think it's relevant. Mainly because my code does not use I/O, but I want to fool OpenVPN3 into thinking it's using I/O.</p> <p><code>async_read_some</code> passes a buffer and a handler and returns immediately. When Asio fills the buffer it calls the handler, which delivers the data.</p> <p>I created a class called <code>AsyncChannel</code> where, on one side, it receives an <code>async_read_some</code> call (stored in a <code>Reader</code>) and in the other it receives data (called <code>Buffer</code>) to be written to <code>Reader</code>. The job of the class is to match a read with a write. That is, fill the asio buffer with data when data is available. Since sometimes <code>Reader</code>'s buffer can be smaller than <code>Buffer</code>, it becomes a little difficult to do these matches.</p> <pre><code>#include &lt;queue&gt; #include &lt;mutex&gt; #include &lt;future&gt; #include &lt;atomic&gt; #include &lt;condition_variable&gt; template &lt;class Buffer, class Reader&gt; class AsyncChannel { public: typedef std::function&lt;void()&gt; Task; AsyncChannel() { shouldContinue.store(true); } void emplace_reader(Reader &amp;&amp;reader) { { std::unique_lock&lt;std::mutex&gt; lock{readerMutex}; readerFifo.emplace(std::forward(reader)); } match(); } void emplace_buffer(Buffer &amp;&amp;buffer) { { std::unique_lock&lt;std::mutex&gt; lock{bufferMutex}; bufferFifo.emplace(std::forward(buffer)); } match(); } /* If both FIFOs are not empty, it means we can match a read with a write */ void match() { std::unique_lock&lt;std::mutex&gt; readerLock{readerMutex}; std::unique_lock&lt;std::mutex&gt; bufferLock{bufferMutex}; if (!reader.empty() &amp;&amp; !buffer.empty()) { auto r = readerFifo.front(); auto w = bufferFifo.front(); /* If the read buffer has sufficient size we can simply copy the write buffer */ if (r-&gt;size() &lt;= w.size()) { readerFifo.pop(); bufferFifo.pop(); readerLock.unlock(); bufferLock.unlock(); { std::unique_lock&lt;std::mutex&gt; lock{tasksMutex}; tasks.emplace([r, w]() { //Copies all bytes from w into r (not cheap) r.receive(w); //Finally calls the Reader handler r.deliver(); }); } tasksConditionVariable.notify_all(); } /* Otherwise, we can copy only up to r.size() of w for each r. Do not pop buffer since it still has data to be read on next iteration */ else { readerFifo.pop(); readerLock.unlock(); bufferLock.unlock(); { std::unique_lock&lt;std::mutex&gt; lock{tasksMutex}; tasks.emplace([r, w]() { //Copies r.size() bytes from w into r (not cheap) r.receive(w, r.size()); //Makes w point to the non consumed part of its buffer w.consumed(r.size()); //Finally calls the Reader handler r.deliver(); }); } } } } void stop() { shouldContinue.store(false); } void taskExecutor() { while (shouldContinue.load()) { std::unique_lock&lt;std::mutex&gt; lock{tasksMutex}; //Only unblocks when tasks is not empty tasksConditionVariable.wait(lock, [] { return !tasks.empty() }); { //Check again because it could have had an element in between here and wait if (!tasks.empty()) { auto &amp;task = tasks.front(); task(); } } } } ~AsyncChannel() { //Blocks until taskExecutor loop stops. It's not good do block but what can I do? stop(); } private: //TODO: add size control to these queues so it won't eat all RAM in case reader or writer stop emplacing std::queue&lt;Buffer&gt; bufferFifo; std::queue&lt;Reader&gt; readerFifo; std::queue&lt;Task&gt; tasks; std::mutex tasksMutex; std::condition_variable tasksConditionVariable; std::mutex bufferMutex; std::mutex readerMutex; std::atomic&lt;bool&gt; shouldContinue; }; </code></pre> <p>I'd like to know if this code is efficient in doing the matches of a <code>Reader</code> with a <code>Buffer</code> and if anyone can think of improvements. Note that when <code>AsyncChannel</code> is destructed, it first needs to wait for a copy to finish. This could be prevented by, instead of running a task executor, spawning <code>std::async</code>s, but I've heard that spawning lots of <code>std::async</code>s is much more costly than a single-threaded task executor.</p> <p>Note that I have to use a not cheap memory copy. I don't think it's possible to exchange Asio's buffer with a Buffer that came from the other side, so a not cheap memory copy is needed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:13:02.433", "Id": "456976", "Score": "1", "body": "It is hard to review - you need examples of the Buffer and Reader. Also codereview is for reviewing a working code. You didn't test this code. You never pop elements from `tasks` queue - you only stack em up. Either you perform only first task repeatedly or you miss tasks from time to time and repeat certain tasks at random. At any rate this is a memory leak." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T20:14:48.033", "Id": "233723", "Score": "1", "Tags": [ "c++", "boost" ], "Title": "Implementing boost::asio's async_read_some" }
233723
<p>I was playing around with the "eight queens" problem, just to see how I could use C++ algorithms to write less code.</p> <p>I figured out a way to find the next unused column using <code>find_if_not</code>. I am showing both ways of writing it. Assume we are looping over every valid "file" on a given "rank" ( in C++ terms, I am looping over rows and columns in an 8x8 matrix.)</p> <ul> <li><code>used</code> is simply a set of column indexes that are currently occupied by a queen.</li> <li><code>col</code> is the current index of the column where we will try to place the next queen.</li> </ul> <p>Note for efficiency, the array of column indexes would not be created where it's shown in the code.</p> <p>Method1:</p> <pre><code>set&lt;unsigned&gt;::iterator it; for (; col &lt; 8; ++col) { it = used.find(col); if (it == used.end()) break; } if (it != used.end()) return false; </code></pre> <p>Method2:</p> <pre><code>array&lt;unsigned, 8&gt; colIdx{ 0, 1, 2, 3, 4, 5, 6, 7 }; auto it = find_if_not(colIdx.begin() + col, colIdx.end(), [&amp;used](unsigned colIdx) { return used.find(colIdx) != used.end(); }); if (it == colIdx.end()) return false; else col = *it; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T07:28:14.457", "Id": "457340", "Score": "0", "body": "\"Note for efficiency, the array of column indexes would not be created where it's shown in the code.\" Next time, please add your *actual* code. Code Review doesn't handle hypothetical code well, hence it being off-topic (as noted in our [help/on-topic])." } ]
[ { "body": "<p>Manually listing the numbers from 0 to 7 is a bad sign; I would definitely consider your first method more readable.</p>\n\n<p>Have you considered using an array(-like) of booleans instead of a set, though?</p>\n\n<pre><code>// given array&lt;bool, 8&gt; used;\nauto const it = std::find(used.cbegin() + col, used.cend(), false);\n\nif (it == used.cend())\n return false;\n\ncol = std::distance(used.cbegin(), it);\n</code></pre>\n\n<p>It should be faster, too, with no downside that I can think of (since your set and array capacity will be the same).</p>\n\n<p>Then there’s the possibility that the overall code can be structured so you only need an iterator and never an index (except to produce results)…</p>\n\n<p>Alternatively, it still makes the first method simpler.</p>\n\n<pre><code>for (; col &lt; 8; ++col)\n if (!used[col])\n break;\n\nif (col == 8)\n return false;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>while (used[col])\n if (++col == 8)\n return false;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:27:04.967", "Id": "233760", "ParentId": "233728", "Score": "0" } }, { "body": "<p>I prefer Method 2 because the loop is replaced by a standard algorithm, which has a fixed meaning and is hence widely known.</p>\n\n<p>As far as hardcoding the <code>colIdx</code> array is concerned, you can use <code>std::iota()</code> to generate the numbers instead.</p>\n\n<p>Also, you use magic number for loop counter in Method 1, it should be replaced with <code>used.size()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:38:32.690", "Id": "233762", "ParentId": "233728", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:45:29.813", "Id": "233728", "Score": "2", "Tags": [ "c++", "c++11", "comparative-review" ], "Title": "Find the next empty column on a chessboard" }
233728
<p>I'm developing a toy project for monitoring some network parameters. Now I'm implementing a feature that will allow to measure a packet round trip between hosts by measuring time between TCP SYNC and TCP SYNC/ACK. One of the options for feeding this application with packets will be setting up capture on network device. I implemented class 'PacketReceiver' which responsibility is:</p> <ul> <li>Listening on given network interface</li> <li>Dispatch packets for subscribed observers</li> </ul> <p>Aim of the project is to learn by making mistakes and getting feedback, so each constructive critique is very welcomed.</p> <p>My considerations:</p> <ul> <li>Does the locking on every layer on every packet in <code>DistributePacket</code> function could/should be done better? </li> <li><code>DistributePacket</code> function iterates over every layer of packet and does find by protocol and then iterates over every observer. It will probably impact performance. How it could be optimized?</li> <li>Is interface of the class appropriate? Maybe something should be decoupled according to best practices?</li> <li>Is the code readable? Is there anything that could make it more readable?</li> <li>Is there something that could be improved in terms of best programming practices?</li> </ul> <p>PacketReceiver.cpp</p> <pre><code>#include &lt;PcapLiveDevice.h&gt; #include &lt;iostream&gt; #include &lt;functional&gt; #include "PacketReceiver.h" #include "TcpLayer.h" void PacketReceiver::OnPacketArrived(pcpp::RawPacket* pPacket, pcpp::PcapLiveDevice* pDevice, void* userCookie){ auto packet = std::make_shared&lt;pcpp::Packet&gt;(pPacket); auto packetReceiver = static_cast&lt;PacketReceiver*&gt;(userCookie); packetReceiver-&gt;m_packetQueue.Enqueue(std::move(packet)); } bool PacketReceiver::StartCapturing() { auto&amp; devices = pcpp::PcapLiveDeviceList::getInstance(); auto deviceList = devices.getPcapLiveDevicesList(); pcpp::PcapLiveDevice* wlp7s0 = devices.getPcapLiveDeviceByName(m_captureName); if(!wlp7s0){ std::cout &lt;&lt; "Device: wlp7s0 was not found." &lt;&lt; std::endl; return false; } if(!wlp7s0-&gt;open()){ std::cout &lt;&lt; "Device wlp7s0 could not be opened." &lt;&lt; std::endl; return false; } if(!wlp7s0-&gt;startCapture(OnPacketArrived, this)){ std::cout &lt;&lt; "Unable to start capturing." &lt;&lt; std::endl; return false; } } bool PacketReceiver::AddFilter(PacketObserverShPtr observer, const pcpp::ProtocolType protocol) noexcept{ auto attachedObserver = m_packetObservers.find(observer); if(attachedObserver==m_packetObservers.end()) { return false; } { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); auto subscribedObservers = m_protocolToObserver[protocol]; subscribedObservers.insert(observer); } return true; } bool PacketReceiver::RemoveFilter(PacketObserverShPtr observer, const pcpp::ProtocolType protocol) noexcept{ auto attachedObserver = m_packetObservers.find(observer); if(attachedObserver==m_packetObservers.end()) { return false; } auto subscribedObservers = m_protocolToObserver.find(protocol); if(subscribedObservers==m_protocolToObserver.end()) { return false; } auto protocolObserver = subscribedObservers-&gt;second.find(observer); if(protocolObserver!=subscribedObservers-&gt;second.end()){ std::unique_lock&lt;std::mutex&gt; lock(m_mutex); subscribedObservers-&gt;second.erase(protocolObserver); } return true; } bool PacketReceiver::Attach(PacketObserverShPtr observer) noexcept{ std::unique_lock&lt;std::mutex&gt; lock(m_mutex); auto result = m_packetObservers.insert(observer); if(!result.second) return false; return true; } bool PacketReceiver::Detach(PacketObserverShPtr observer) noexcept{ auto searchResult = m_packetObservers.find(observer); if(searchResult==m_packetObservers.end()) { return false; } { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); m_packetObservers.erase(searchResult); for(auto&amp; protocol: m_protocolToObserver){ protocol.second.erase(observer); } } return true; } void PacketReceiver::MainLoop() { while(m_runThread){ auto packet = m_packetQueue.Dequeue(); DistributePacket(std::move(packet)); } } void PacketReceiver::OnThreadStarting() { StartCapturing(); } void PacketReceiver::DistributePacket(std::shared_ptr&lt;pcpp::Packet&gt; packet) { for(auto currentLayer = packet-&gt;getFirstLayer(); currentLayer!=NULL; currentLayer=packet-&gt;getFirstLayer()){ auto protocol = currentLayer-&gt;getProtocol(); std::unique_lock&lt;std::mutex&gt; lock(m_mutex); auto observers = m_protocolToObserver.find(protocol); if(observers!=m_protocolToObserver.end()){ for(auto&amp; observer : observers-&gt;second){ observer-&gt;Update(std::move(packet)); } } } } PacketReceiver::PacketReceiver(const std::string &amp;captureName) : m_captureName(captureName) { } </code></pre> <p>PacketReceiver.hpp</p> <pre><code>#pragma once #include &lt;PcapLiveDeviceList.h&gt; #include &lt;atomic&gt; #include &lt;thread&gt; #include &lt;zmq.hpp&gt; #include &lt;set&gt; #include &lt;map&gt; #include "PacketQueue.h" #include "Thread.h" #include "Interfaces.h" class PacketReceiver : public Thread { public: PacketReceiver(const std::string&amp; captureName); using PacketObserverShPtr = std::shared_ptr&lt;IObserver&lt;std::shared_ptr&lt;pcpp::Packet&gt; &gt; &gt;; bool Attach(PacketObserverShPtr observer) noexcept; bool Detach(PacketObserverShPtr observer) noexcept; bool AddFilter(PacketObserverShPtr observer, const pcpp::ProtocolType protocol) noexcept; bool RemoveFilter(PacketObserverShPtr observer, const pcpp::ProtocolType protocol) noexcept; private: void MainLoop() override; void OnThreadStarting() override; bool StartCapturing(); static void OnPacketArrived(pcpp::RawPacket* pPacket, pcpp::PcapLiveDevice* pDevice, void* userCookie); void DistributePacket(std::shared_ptr&lt;pcpp::Packet&gt; packet); PacketQueue m_packetQueue; std::set&lt;PacketObserverShPtr &gt; m_packetObservers; std::map&lt;pcpp::ProtocolType, std::set&lt;PacketObserverShPtr&gt; &gt; m_protocolToObserver; std::mutex m_mutex; std::string m_captureName; }; </code></pre>
[]
[ { "body": "<p>I will give you some tips related to packet processing:</p>\n\n<ul>\n<li>Have mutex/lock for every read packet is a bad idea in terms of performance</li>\n<li>Copy packets form one place to another is also a bad idea, you should move packets or keep reference the same part, take into consideration that memory copy operations are expensive for a packet application like yours.</li>\n</ul>\n\n<p>In general your code is readable and is clear what you want to achieve, I will suggest you to use a profiler in order to find the bottlenecks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:47:03.617", "Id": "233880", "ParentId": "233729", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:01:56.000", "Id": "233729", "Score": "2", "Tags": [ "c++" ], "Title": "PacketReceiver for multithreaded NetworkMonitor project" }
233729
<p>This is another review on <a href="https://codereview.stackexchange.com/questions/214273/fixing-medical-claim-files-through-text-file-read-write-v2">a program I've asked about before</a>, now translated from VBA into C#. I'm sure I've brought over a lot of bad habits with me, so I'm spotlighting some key areas I'd love open-ended feedback on.</p> <p>This is a WPF desktop app.</p> <hr> <p><strong>Program Function</strong></p> <p>As before, this program makes emergency changes to medical claim files, delivers all the corrected files analysts need, and produces a changelog as well for their review. </p> <hr> <p><strong>Main method - Fix names changed to protect the innocent</strong> </p> <pre><code>class FixTextFiles { [System.STAThreadAttribute()] //[System.Diagnostics.DebuggerNonUserCodeAttribute()] //[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] static void Main() { var model = new Model(); ActiveFixes activeFixes = new ActiveFixes(); ActiveReports activeReports = new ActiveReports(); FileInfo[] files = null; if (!ModelIsSetUpBasedOnArgumentsOrUI(model, activeFixes, activeReports, ref files)) { return; } var DoubleProgressBar = new ViewPlusViewModel.DoubleProgressBar(); DoubleProgressBar.ProgressBarFilesCompleted.Maximum = files.GetUpperBound(0) + 1; DoubleProgressBar.Show(); DoubleProgressBar.Activate(); for (var i = files.GetLowerBound(0); i &lt;= files.GetUpperBound(0); i++) { DoubleProgressBar.ProgressBarFilesCompleted.Value = i; DoubleProgressBar.LabelFilesCompleted.Content = "Files Completed: " + i + " / " + DoubleProgressBar.ProgressBarFilesCompleted.Maximum + ", " + files[i].Name; string entireFile = File.ReadAllText(files[i].FullName); if (entireFile != string.Empty) { var originalFileLines = entireFile.Split(new string[] { model.Delimiter1 }, StringSplitOptions.None); var revisedFileLines = entireFile.Split(new string[] { model.Delimiter1 }, StringSplitOptions.None); activeFixes.ResetIndicatorsOnNewFile(); activeReports.ResetIndicatorsOnNewFile(); DoubleProgressBar.ProgressBarLinesCompleted.Maximum = originalFileLines.GetUpperBound(0) + 1; // --- Begin Manipulation --- for (var currentLineNumber = originalFileLines.GetLowerBound(0); currentLineNumber &lt;= originalFileLines.GetUpperBound(0); currentLineNumber++) { DoubleProgressBar.ProgressBarLinesCompleted.Value = currentLineNumber; DoubleProgressBar.LabelLinesCompleted.Content = "Lines Completed: " + currentLineNumber + " / " + DoubleProgressBar.ProgressBarLinesCompleted.Maximum; // --- Ongoing variables --- var currentLine = originalFileLines[currentLineNumber]; var segmentType = currentLine.Substring(0, currentLine.IndexOf(model.Delimiter3)); // --- Fixes --- if (activeFixes.FixClassThatFixesIndividualLines1 != null) { // check things and do FixClass1 methods } if (activeFixes.FixClassThatFixesIndividualLines2 != null) { // check things and do FixClass2 methods } // repeat for 40+ fix/report classes } DoubleProgressBar.ProgressBarLinesCompleted.Value = DoubleProgressBar.ProgressBarLinesCompleted.Maximum; DoubleProgressBar.ProgressBarFilesCompleted.Value = i + 1; if (activeReports.Count == 0) { if (model.CreateChangelogSheets) { WriteOriginalAndUpdatedSegmentsToCSVAndNoteDifferences(originalFileLines, revisedFileLines, files[i]); } WriteUpdatedSegmentsToNewFile(revisedFileLines, model.Delimiter1, files[i], model.FixedFilesDestination); } if (activeReports.ReportClassThatReportsOnWholeFiles1 != null) { // check things and do ReportClass1 methods } if (activeReports.ReportClassThatReportsOnWholeFiles2 != null) { // check things and do ReportClass2 methods } } } activeFixes.ReprotectSettingsSheets(); activeReports.ReprotectSettingsSheets(); var tempDirectoryPath = Path.Combine(new string[] { Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "(Program Name)" }); if (Directory.Exists(tempDirectoryPath)) { try { Directory.Delete(tempDirectoryPath, true); } catch (IOException e) { } } UpdateTelemetryFile(files[0].DirectoryName, files.GetUpperBound(0) + 1, activeFixes, activeReports); if (model.LaunchedFromBatchFile == false) { MessageBox.Show("All files have been fixed and saved to the same folders as the source files with \"Fixed\" added to their filenames. No original files have been modified."); } } </code></pre> <hr> <p><strong>This is mostly a console app with some light UI tacked on for easy user configuration - start getting ready for user config</strong></p> <pre><code> private static bool ModelIsSetUpBasedOnArgumentsOrUI(Model model, ActiveFixes activeFixes, ActiveReports activeReports, ref FileInfo[] files) { var commandLineArgs = Environment.GetCommandLineArgs(); switch (commandLineArgs.GetUpperBound(0)) { case 0: if (!UserPromptedSettingsWereWrittenToModel(ref model, ref activeFixes, ref activeReports)) { return false; } files = GetFilesToWorkWith(); if (files.Length == 0) { return false; } else { return true; } case 7: // Model is setup based on command line arguments instead } } </code></pre> <hr> <p><strong>This is the major UI portion - user goes through a sequence of two main config windows (and potentially one child window) before selecting their files with <code>GetFilesToWorkWith()</code></strong></p> <pre><code> public static bool UserPromptedSettingsWereWrittenToModel(ref Model model, ref ActiveFixes activeFixes, ref ActiveReports activeReports) { var viewModel = new ViewModel(); viewModel.Setup(); var tempDirectoryPath = Path.Combine(new string[] { Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "(Program name)", "Model Data" }); if (!Directory.Exists(tempDirectoryPath)) { Directory.CreateDirectory(tempDirectoryPath); } var tempFilePath = Path.Combine(new string[] { tempDirectoryPath, "Fixes Reports List.csv" }); File.WriteAllText(tempFilePath, Properties.Resources.Fixes_Reports_List); viewModel.FixesReportsTable = GeneralTools.GetDataTableFromCSV(tempFilePath, "|", true, false); var parseSettings = new ViewPlusViewModel.ParseSettings(); parseSettings.InitializeComponent(); var fixSelector = new ViewPlusViewModel.FixSelector(viewModel); fixSelector.InitializeComponent(); var seeAllFixesReports = new ViewPlusViewModel.SeeAllFixesReports(viewModel); seeAllFixesReports.InitializeComponent(); parseSettings.ShowDialog(); var nextWindowToOpen = "TBD"; while (!string.IsNullOrEmpty(nextWindowToOpen) &amp;&amp; !nextWindowToOpen.Equals("Select Text Files")) { switch (GetNextWindowToOpen(parseSettings, fixSelector, seeAllFixesReports)) { case "Parse Settings": parseSettings.ShowDialog(); break; case "Fix Selector": fixSelector.ShowDialog(); break; case "See All Fixes And Reports": if (fixSelector.FixesOrReports.Equals("Fixes")) { seeAllFixesReports.UpdateTableType("Fix"); } if (fixSelector.FixesOrReports.Equals("Reports")) { seeAllFixesReports.UpdateTableType("Report"); } seeAllFixesReports.ShowDialog(); break; case "Select Text Files": nextWindowToOpen = "Select Text Files"; break; case null: parseSettings.Close(); if (fixSelector.IsLoaded) fixSelector.Close(); if (seeAllFixesReports.IsLoaded) { seeAllFixesReports.Close(); } return false; } } if (fixSelector.FixesOrReports.Equals("Fixes")) { activeFixes.Setup(fixSelector.ActiveFixes, viewModel.FixesReportsTable); } if (fixSelector.FixesOrReports.Equals("Reports")) { activeReports.Setup(fixSelector.ActiveReports, viewModel.FixesReportsTable); } model.Setup(parseSettings.Delimiter1, parseSettings.Delimiter2, parseSettings.Delimiter3, parseSettings.Delimiter4, Convert.ToBoolean(parseSettings.CreateChangelogSheets)); parseSettings.Close(); fixSelector.Close(); if (seeAllFixesReports.IsLoaded) { seeAllFixesReports.Close(); } return true; } </code></pre> <hr> <p><strong>Since I'm <code>new</code>ing and <code>ShowDialog</code>ing UIwindows from the code rather than <code>Main()</code>ing in a window in a more pure WPF fashion, I use code to determine where to go next</strong></p> <pre><code> private static string GetNextWindowToOpen(ViewPlusViewModel.ParseSettings parseSettings, ViewPlusViewModel.FixSelector fixSelector, ViewPlusViewModel.SeeAllFixesReports seeAllFixesReports) { if (fixSelector.GoBack) { fixSelector.GoBack = false; return "Parse Settings"; } if (parseSettings.GoToNextWindow || seeAllFixesReports.GoToNextWindow || seeAllFixesReports.GoBack) { parseSettings.GoToNextWindow = false; seeAllFixesReports.GoToNextWindow = false; seeAllFixesReports.GoBack = false; return "Fix Selector"; } if (fixSelector.GoToChildWindow) { fixSelector.GoToChildWindow = false; return "See All Fixes And Reports"; } if (fixSelector.GoToNextWindow) { fixSelector.GoToNextWindow = false; return "Select Text Files"; } return null; } </code></pre> <hr> <p><strong>The first UI window, ParseSettings - users put in 5 values for the Model. Delimiter names changed to protect the innocent.</strong></p> <pre><code>public partial class ParseSettings : Window { public static readonly DependencyProperty Delimiter1Property = DependencyProperty.Register("Delimiter1", typeof(string), typeof(ParseSettings), new PropertyMetadata("(Default A)")); public static readonly DependencyProperty Delimiter2Property = DependencyProperty.Register("Delimiter2", typeof(string), typeof(ParseSettings)); public static readonly DependencyProperty Delimiter3Property = DependencyProperty.Register("Delimiter3", typeof(string), typeof(ParseSettings), new PropertyMetadata("(Default B)")); public static readonly DependencyProperty Delimiter4Property = DependencyProperty.Register("Delimiter4", typeof(string), typeof(ParseSettings), new PropertyMetadata("(Default C)")); public static readonly DependencyProperty CreateChangelogSheetsProperty = DependencyProperty.Register("CreateChangelogSheets", typeof(string), typeof(ParseSettings), new PropertyMetadata("True")); public string Delimiter1 { get { return GetValue(Delimiter1Property) as string; } set { SetValue(Delimiter1Property, value); } } public string Delimiter2 { get { return GetValue(Delimiter2Property) as string; } set { SetValue(Delimiter2Property, value); } } public string Delimiter3 { get { return GetValue(Delimiter3Property) as string; } set { SetValue(Delimiter3Property, value); } } public string Delimiter4 { get { return GetValue(Delimiter4Property) as string; } set { SetValue(Delimiter4Property, value); } } public string CreateChangelogSheets { get { return GetValue(CreateChangelogSheetsProperty) as string; } set { SetValue(CreateChangelogSheetsProperty, value); } } public bool GoToNextWindow { get; set; } public ParseSettings() { InitializeComponent(); GoToNextWindow = false; } protected void MakeChangelogSheetsButton_Clicked(object sender, RoutedEventArgs e) { var senderAsButton = sender as Button; if (senderAsButton == ButtonCreateChangelogSheets) { switch (this.CreateChangelogSheets) { case "True": this.CreateChangelogSheets = "False"; senderAsButton.Background = Brushes.Pink; break; case "False": this.CreateChangelogSheets = "True"; senderAsButton.Background = Brushes.PaleGreen; break; } } } private void SeeIfGoToNextWindowButtonCanBeEnabled(object sender, TextChangedEventArgs e) { if (Validation.GetHasError(this.InputDelimiter1) || Validation.GetHasError(this.InputDelimiter2) || Validation.GetHasError(this.InputDelimiter3) || Validation.GetHasError(this.InputDelimiter4)) { this.ButtonSelectFixesOrReports.IsEnabled = false; } else { this.ButtonSelectFixesOrReports.IsEnabled = true; } } private void GoToNextWindow_Click(object sender, RoutedEventArgs e) { if (sender == this.ButtonSelectFixesOrReports) { this.GoToNextWindow = true; } this.Hide(); } } </code></pre> <hr> <p><strong>The second UI window, FixSelector - users can search for desired fixes or pick from a telemetry file-populated list of the most popular. Each fix listed in either search results or the popular options is a button in a <code>ListView</code> that can be clicked to activate the fix, change the button's color visually, and add or remove it from appropriate <code>ListView</code>-populating dictionaries</strong></p> <pre><code>public partial class FixSelector : Window { public static readonly DependencyProperty FixesOrReportsProperty = DependencyProperty.Register("FixesOrReports", typeof(string), typeof(FixSelector), new PropertyMetadata("Fixes")); public static readonly DependencyProperty SegmentFixNameSearchProperty = DependencyProperty.Register("SegmentFixNameSearch", typeof(string), typeof(FixSelector)); public string FixesOrReports { get { return GetValue(FixesOrReportsProperty) as string; } set { SetValue(FixesOrReportsProperty, value); } } public string SegmentFixNameSearch { get { return GetValue(SegmentFixNameSearchProperty) as string; } set { SetValue(SegmentFixNameSearchProperty, value); } } public bool GoToNextWindow { get; set; } public bool GoToChildWindow { get; set; } public bool GoBack { get; set; } public List&lt;(string FixOrReportName, long CountInTelemetryFile)&gt; MostPopularFixes { get; set; } public List&lt;(string FixOrReportName, long CountInTelemetryFile)&gt; MostPopularReports { get; set; } public DataTable CompleteFixesReportsTable { get; set; } public DataTable CompatibilityTable { get; set; } public Dictionary&lt;string, string&gt; ActiveFixes { get; set; } public Dictionary&lt;string, string&gt; ActiveReports { get; set; } public Dictionary&lt;Button, Button&gt; ClickedButtonsByAddedButtonsInSelectedFixes { get; set; } public Dictionary&lt;Button, Button&gt; ClickedButtonsByAddedButtonsInSelectedReports { get; set; } public Dictionary&lt;Button, Button&gt; AddedButtonsInSelectedFixesByClickedButtons { get; set; } public Dictionary&lt;Button, Button&gt; AddedButtonsInSelectedReportsByClickedButtons { get; set; } public FixSelector(ViewModel viewModel) { InitializeComponent(); GoToNextWindow = false; GoToChildWindow = false; GoBack = false; MostPopularFixes = viewModel.MostPopularFixes; MostPopularReports = viewModel.MostPopularReports; PopulateMostPopularOptionsListView(); CompleteFixesReportsTable = viewModel.FixesReportsTable; CompatibilityTable = viewModel.CompatibilityTable; ActiveFixes = new Dictionary&lt;string, string&gt;(); ActiveReports = new Dictionary&lt;string, string&gt;(); ClickedButtonsByAddedButtonsInSelectedFixes = new Dictionary&lt;Button, Button&gt;(); ClickedButtonsByAddedButtonsInSelectedReports = new Dictionary&lt;Button, Button&gt;(); AddedButtonsInSelectedFixesByClickedButtons = new Dictionary&lt;Button, Button&gt;(); AddedButtonsInSelectedReportsByClickedButtons = new Dictionary&lt;Button, Button&gt;(); } private void PopulateMostPopularOptionsListView() { this.MostPopularOptions.Items.Clear(); if (this.FixesOrReports.Equals("Fixes")) { if (!(this.MostPopularFixes is null)) { for (var i = 0; i &lt; this.MostPopularFixes.Count; i++) { var button = new Button { Content = this.MostPopularFixes[i].FixOrReportName }; button.Click += new RoutedEventHandler(this.IndividualFixReportButton_Click); this.MostPopularOptions.Items.Add(button); } } } if (this.FixesOrReports.Equals("Reports")) { if (!(this.MostPopularReports is null)) { for (var i = 0; i &lt; this.MostPopularReports.Count; i++) { var button = new Button { Content = this.MostPopularReports[i].FixOrReportName }; button.Click += new RoutedEventHandler(this.IndividualFixReportButton_Click); this.MostPopularOptions.Items.Add(button); } } } } protected void FixesOrReportsButton_Clicked(object sender, RoutedEventArgs e) { var senderAsButton = sender as Button; if (senderAsButton == ButtonFixesOrReports) { switch (this.FixesOrReports) { case "Fixes": this.FixesOrReports = "Reports"; senderAsButton.Background = Brushes.LightBlue; PopulateMostPopularOptionsListView(); this.SelectedFixes.Visibility = Visibility.Hidden; this.SelectedReports.Visibility = Visibility.Visible; if (this.ActiveReports.Count == 0) { this.ButtonSelectTextFiles.IsEnabled = false; } break; case "Reports": this.FixesOrReports = "Fixes"; senderAsButton.Background = Brushes.Orange; PopulateMostPopularOptionsListView(); this.SelectedFixes.Visibility = Visibility.Visible; this.SelectedReports.Visibility = Visibility.Hidden; this.ButtonSelectTextFiles.IsEnabled = true; break; } PopulateSearchResults(this.SearchResults, e as TextChangedEventArgs); } } protected void PopulateSearchResults(object sender, TextChangedEventArgs e) { this.SearchResults.Items.Clear(); if (string.IsNullOrEmpty(this.SegmentFixNameSearch)) { return; } string typeToReturn; if (this.FixesOrReports.Equals("Fixes")) { typeToReturn = "Fix"; } else { typeToReturn = "Report"; } var nameFilter = GetCompleteFixesReportsTableRowFilterNameExpression(); this.CompleteFixesReportsTable.DefaultView.RowFilter = nameFilter + " AND FixOrReport = '" + typeToReturn + "'"; var matchingFixesTable = this.CompleteFixesReportsTable.DefaultView.ToTable(); var matchingFixesList = new List&lt;(string Name, string Description)&gt;(); for (var i = 0; i &lt; matchingFixesTable.Rows.Count; i++) { matchingFixesList.Add((Name: matchingFixesTable.Rows[i]["Name"].ToString(), Description: matchingFixesTable.Rows[i]["Description"].ToString())); } for (var i = 0; i &lt; matchingFixesList.Count; i++) { var button = new Button { Content = matchingFixesList[i].Name, ToolTip = matchingFixesList[i].Description }; button.Click += new RoutedEventHandler(this.IndividualFixReportButton_Click); if (typeToReturn.Equals("Fix")) { if (this.ActiveFixes.ContainsKey(button.Content.ToString())) { button.Background = Brushes.PaleGreen; } } if (typeToReturn.Equals("Report")) { if (this.ActiveReports.ContainsKey(button.Content.ToString())) { button.Background = Brushes.PaleGreen; } } this.SearchResults.Items.Add(button); } } private void IndividualFixReportButton_Click(object sender, RoutedEventArgs e) { var senderAsButton = sender as Button; if (senderAsButton.Background == Brushes.PaleGreen) { senderAsButton.Background = (Brush)new BrushConverter().ConvertFrom("#FFDDDDDD"); RemoveFixOrReportFromAppropriateDictionary(senderAsButton); } else { senderAsButton.Background = Brushes.PaleGreen; AddFixOrReportToAppropriateDictionary(senderAsButton); } } private void GoToNextWindow_Click(object sender, RoutedEventArgs e) { if (sender == ButtonSelectTextFiles) { this.GoToNextWindow = true; } if (sender == ButtonBackToParseSettings) { this.GoBack = true; } if (sender == ButtonSeeAllFixesReports) { this.GoToChildWindow = true; } this.Hide(); } } </code></pre> <hr> <p><strong>Last major section: Based upon the dictionary of selected fixes or reports, here's how those <code>ActiveFixes/ActiveReports</code> classes get populated</strong></p> <pre><code> class ActiveFixes { public long Count { get; set; } public DataTable FixesReportsTable { get; set; } public Fixes.FixClass1 FixClass1 { get; set; } public Fixes.FixClass2 FixClass2 { get; set; } // etc. for 40+ fixes public ActiveFixes() { Count = 0; } public void Setup(Dictionary&lt;string, string&gt; selectionsFromFixSelector, DataTable fixesReportsTable) { this.FixesReportsTable = fixesReportsTable; InstantiateSelectionsAsProperties(selectionsFromFixSelector); var properties = this.GetType().GetProperties(); for (var i = properties.GetLowerBound(0); i &lt;= properties.GetUpperBound(0); i++) { if (!properties[i].Name.Equals("Count") &amp;&amp; !properties[i].Name.Equals("FixesReportsTable")) { if (properties[i].GetValue(this) != null) { this.Count += 1; var activeFix = properties[i].GetValue(this) as IFixReport; var fixName = ConversionMethods.GetFixReportNameFromIFixReportName(properties[i].Name); var fixRows = this.FixesReportsTable.Select("Name = '" + fixName + "'"); activeFix.Settings = _(ProgramName)Tools.GetSettingsSheet(fixRows[0]["SettingsSheet"].ToString()); if (activeFix.Settings != null) { activeFix.Settings.Unprotect(); activeFix.ConfirmAndSpeedUpSettingsSheet(); } activeFix.Setup(); } } } } public void InstantiateSelectionsAsProperties(Dictionary&lt;string, string&gt; selectionsFromFixSelector) { foreach (var key in selectionsFromFixSelector.Keys) { switch (key) { case "Fix Class 1 Full Name": this.FixClass1 = new Fixes.FixClass1(); break; case "Fix Class 2 Full Name": this.FixClass2 = new Fixes.FixClass2(); break; // etc. } } } </code></pre>
[]
[ { "body": "<p>A couple of small pointers. I'm skipping over larger architecture issues because it seems that this code is not the complete example of working code.</p>\n\n<ol>\n<li>Local variables are usually started with lower case letter, so I would suggest renaming <code>DoubleProgressBar</code> to <code>doubleProgressBar</code></li>\n<li>You are iterating over <code>files</code> with this <code>for (var i = files.GetLowerBound(0); i &lt;= files.GetUpperBound(0); i++)</code>. Why not just use ordinary <code>for (var i = 0; i &lt; files.Length; i++)</code>?</li>\n<li>You are using some string in switch cases. I would suggest using Enums, because those are safer to change, even if they are not as expressive as a string can be. Also, with enums you get a better support from tools.</li>\n<li>In <code>Main</code> you seem to be using regular string concat (\"a\" + \"b\" + \"c\"). Consider using string interpolation or string.Format()</li>\n<li>In <code>Main</code> you are settings <code>files = null</code> and then passing it as a <code>ref</code> parameter. When you are initializing a value inside method (\"multiple return values\"), you should use <code>out</code> (see <code>Int32.TryParse</code>-for example). You could also use tuples to avoid <code>out</code> and <code>ref</code> (C# 7 onwards?). </li>\n</ol>\n\n<p>On general note, I would avoid methods that do multiple things. Method <code>ModelIsSetUpBasedOnArgumentsOrUI</code> does answer to that question, but it also initializes the files. If possible, those should be done in separate methods to make to code easier to understand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T21:19:05.447", "Id": "457305", "Score": "0", "body": "Thanks for these! Is there more that I could provide you with that would enable you to comment on larger architecture?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T10:41:58.220", "Id": "457502", "Score": "0", "body": "If I understood correctly, that code isn't currently compiling. At least `case 7:` is missing implementation and `ActiveFixes`-class seems to also miss the end of the file. The repository would of course be the best but I'm guessing that's proprietary code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:06:25.183", "Id": "457594", "Score": "0", "body": "case 7: is indeed missing implementation and you're right, I cut some uninteresting methods out of the end of the ActiveFixes class. You're also right that the code is proprietary, sorry!\n\nThe program compiles and works well so far, but it's still in the piloting stages. Now's a good time for me as a brand new C# programmer to get feedback and rearchitect where beneficial.\n\nI've actually already decided while waiting for more answers on this question to do more work outside of the main FixTextFiles class, and to split things up more decisively between Fixes and Reports." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:49:17.710", "Id": "457860", "Score": "0", "body": "I understand. I added couple of things to my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:59:18.343", "Id": "457913", "Score": "0", "body": "I got the most value out of your additions. Thank you for coming back to this answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:15:37.807", "Id": "233870", "ParentId": "233730", "Score": "2" } } ]
{ "AcceptedAnswerId": "233870", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:07:40.510", "Id": "233730", "Score": "3", "Tags": [ "c#", "wpf" ], "Title": "Fixing Medical Claim Files through Text File Read/Write v3" }
233730
<p>I am studying C while listening to a lecture by myself. When I was studying coding and listening to a lecture, I heard that writing code should be concise and maintainable. But I didn't know if I was doing well, so I felt the need for feedback. But it's hard to find anyone who can give us feedback, and I don't know where to ask.</p> <p>I am Korean and I am using a translator because I am not good at English. Please understand if the context feels a little strange</p> <p>For example How do you make this code simpler and more intuitive?</p> <p>Output</p> <blockquote> <pre><code>* ** *** **** ***** **** *** ** * </code></pre> </blockquote> <p>Program:</p> <pre><code>#include&lt;stdio.h&gt; int main(void) { int i, j; int n = 5; for (i = 1; i &lt;= n; ++i) { for (j = 1; j &lt;= i; ++j) putchar('*'); putchar('\n'); } for (i = n - 1; i &gt;= 1; --i) { for (j = 1; j &lt;= i; ++j) putchar('*'); putchar('\n'); } return 0; } </code></pre> <p>Would it be better to write if? Would it be better to have a variable name other than n?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:57:37.093", "Id": "456952", "Score": "3", "body": "Welcome to Code Review! This is a good first question and I’m sure people here will help." } ]
[ { "body": "<p><code>printf</code> already has the ability to print various lengths of stars, using the formatter <code>%.*s</code>. In this code, I avoid multiple nested loops by simply calculating how many stars I want on each line, and passing that number to <code>printf</code>.</p>\n\n<p>I think this code is much shorter and simpler than nested for-loops.</p>\n\n<p>I added in the \"goes-to\" operator just for fun:<br>\neg: <code>while (n --&gt; 0)</code>, which is read as, <em>\"while N goes to zero\"</em></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n int n = 8;\n char stars[n];\n memset(stars, '*',n);\n\n int i = n;\n while(i --&gt; 0)\n printf(\"%.*s\\n\", n-i, stars);\n\n while(n --&gt; 0)\n printf(\"%.*s\\n\", n, stars);\n\n return 0;\n}\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>Success #stdin #stdout 0s 4460KB\n*\n**\n***\n****\n*****\n******\n*******\n********\n*******\n******\n*****\n****\n***\n**\n*\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T00:42:39.317", "Id": "456961", "Score": "1", "body": "I like the question and I like the answer, why is the answer downvoted ? Please explain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T00:58:31.670", "Id": "456962", "Score": "4", "body": "@BobRun The answer provides no explanation as to why it's an improvement to the OP's code. Code only answers [aren't really accepted by the community](https://codereview.meta.stackexchange.com/a/856/153917)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T01:42:54.920", "Id": "456963", "Score": "2", "body": "While I respect your opinion, I believe we learn a lot by simply reading code, and in this case reading the code is more efficient than a lot of explanations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T01:57:26.327", "Id": "456964", "Score": "5", "body": "\"I added in the \"goes-to\" operator just for fun\" please don't. This will just confuse beginners, which the OP seems to be. **Especially** if you don't explain why the \"goes-to\" \"\"operator\"\" works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T02:07:43.223", "Id": "456966", "Score": "0", "body": "In this case the comment added to the answer is just very confusing, there is no \"go to\" or \"goes to\" when you read the code it is simply, execute the next instruction as long as i is more than zero and then decrease i by one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:23:38.440", "Id": "456977", "Score": "2", "body": "I agree that `goes-to` and the answer structure are both problematic. That said - even though the OP didn't ask specifically about performance, this `memset` method will probably outperform individual `putchar` calls." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:45:29.320", "Id": "233733", "ParentId": "233732", "Score": "-3" } }, { "body": "<p>A function to print a line of stars of some length seems like a good idea to me.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nstatic void print_star_line(int count)\n{\n int i;\n\n for (i = 1; i &lt;= count; ++i)\n putchar('*');\n\n putchar('\\n');\n}\n\nint main(void)\n{\n int i;\n int n = 5;\n\n for (i = 1; i &lt;= n; ++i)\n print_star_line(i);\n\n for (i = n - 1; i &gt;= 1; --i)\n print_star_line(i);\n\n return 0;\n}\n</code></pre>\n\n<p>Notice how it’s clearer at a glance what’s happening in <code>main</code>, and that the shared logic is in one place so it can be examined on its own. Plus, if you ever want to make changes to how a line is printed, you only have to make those changes once.</p>\n\n<p>Apart from that, in C89, that’s about as good as it gets! Your code is pretty clean. Well done.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:03:42.133", "Id": "233745", "ParentId": "233732", "Score": "5" } }, { "body": "<p>The issue of performance hasn't specifically been raised, but it's worth addressing (for giggles):</p>\n\n<p>Individual calls to <code>putchar</code>, while programatically simple, are slower than sending out entire strings at a time from a buffer. @jxh had posted an answer using basically this principle, though I wouldn't make it recursive since a loop is perfectly fine and won't blow your stack.</p>\n\n<p>To illustrate the difference: using your original code (but with <code>n=20000</code>), I get</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ gcc -std=c18 -Wall -O3 -march=native -o slow pyramid-slow.c\n$ time ./slow &gt; /dev/null\nreal 0m0.832s\nuser 0m0.808s\nsys 0m0.023s\n</code></pre>\n\n<p>Using the same size but <code>puts</code>-based code, we get</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ gcc -std=c18 -Wall -O3 -march=native -o fast pyramid-fast.c\n$ time ./fast &gt; /dev/null\n\nreal 0m0.058s\nuser 0m0.039s\nsys 0m0.019s\n</code></pre>\n\n<p>The <code>puts</code> code is:</p>\n\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint main(void) {\n const int n = 20000;\n\n char *buf = malloc(n + 1);\n assert(buf);\n memset(buf, '*', n);\n buf[n] = '\\0';\n\n int i;\n for (i = n-1; i &gt;= 0; i--)\n puts(buf + i);\n for (i = 1; i &lt; n; i++)\n puts(buf + i);\n\n return 0;\n}\n</code></pre>\n\n<p>This code offers a fourteen-fold speedup for the shown size. The reason for this is that printing to the screen is effectively a file operation, and file operations are faster when they operate on large blocks of memory instead of on one byte at a time.</p>\n\n<p>All of this should be taken with a grain of salt, since it's nearly guaranteed that performance is not a concern for your application. Even so, this method avoids having to write nested loops and is thus more readable, as long as you can wrap your head around the loop indexing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:17:02.607", "Id": "457070", "Score": "1", "body": "It's quite silly to micro-optimize beginner-level programs like this - none will benefit from that. The correct optimized solution is otherwise to make a compile-time script which generates the following C source: https://godbolt.org/z/oq8Hej. And behold, it outperforms your malloc example by executing many thousand times faster..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:34:42.480", "Id": "457129", "Score": "0", "body": "@Lundin depends on what you're optimizing for. Both your code and your binary take up more disk space and are unmaintainable. My proposal is a happy medium between maintainability, simplicity and reasonable runtime. It's broad optimization but certainly not micro-optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:47:07.923", "Id": "457157", "Score": "0", "body": "My suggestion for printing strings and for using recursion was for clarity, rather than optimization. But I know that recursion in a non-functional language is not always considered clear, so the answer was deleted." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:51:22.167", "Id": "233749", "ParentId": "233732", "Score": "3" } }, { "body": "<p>In addition to the remarks by Ry-, it is good practice to keep for loops trivial. Trivial in this context means <code>for(int i=0; i&lt;n; i++)</code>. This is the purest and most readable form of for loop. </p>\n\n<ul>\n<li>It is praxis to always iterate from 0 to n whenever possible, since numbers start with 0 and arrays in C use zero-indexing.</li>\n<li>Downcounting for loops or for loops with complex condition/iteration expressions are harder to read.</li>\n<li>(<em>Advanced</em>) Up-counting, simple loops are more likely to be data cache-friendly than other loops.</li>\n</ul>\n\n<p>We can move the complexity inside the for loop body instead (I modified the code posted by Ry-):</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nstatic void print_star_line (int count)\n{\n for (int i=0; i&lt;count; i++)\n {\n putchar('*');\n }\n putchar('\\n');\n}\n\nint main (void)\n{\n int n = 5;\n\n for(int i=0; i&lt;n; i++)\n {\n print_star_line(i+1);\n }\n for(int i=0; i&lt;n; i++)\n {\n print_star_line(n-i-2);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Now all loops are trivial and easy to read, the complexity lies in the expression passed on to the function instead.</p>\n\n<hr>\n\n<p>Note that this code also places the <code>int</code> declarations inside the for loop, which is how code should be written in standard C. </p>\n\n<p>If your source of learning is hopelessly outdated, someone might teach you to use the 30 years old, 20 years obsolete \"C90\" standard, which doesn't allow this. If so, you need a newer source of learning.</p>\n\n<hr>\n\n<p>The variable name <code>n</code> is fine though vague. It is common style to use <code>n</code> or a <code>_N</code> suffix when counting something.</p>\n\n<p>Similarly, <code>i</code> stands for <em>iterator</em> and is the industry standard name for a loop iterator. <code>j</code> means nothing, it's just the letter that follows <code>i</code> in the alphabet, so it is commonly used when nesting loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:04:21.500", "Id": "233792", "ParentId": "233732", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T22:36:09.620", "Id": "233732", "Score": "3", "Tags": [ "c" ], "Title": "ASCII-art pyramid" }
233732
<p>A bit of background. In the application I work on there are emails sent to notify users about articles they need to review. Each email+recipient pair is stored in database and may be assigned a different creation date ( called <code>DateCreated</code> ) due to emails being generated over some time.</p> <p>I needed to calculate how many times the emails were sent and how many recipients were there on each turn. For this reason I grouped emails which come in quick succession into groups. I used a TimeSpan of 30 minutes after each "first" email in a group. In order to do it I needed to store the dates defining groups "somewhere". I used a separate method to wrap my grouping function. The TimeSpan I used is safe, mailing ever only takes up to 2 minutes. Also separate mailings usually happen on separate dates.</p> <p>My questions here are - Is this easy enough to understand? Could I code it simpler? Any other advice is also welcome.</p> <p>And yes - this should be fixed in the database, there should be a <code>mailing</code> table there but there isn't and I cannot achieve it easily at the moment.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UserCommunication { public class ArticleEmailSummary { public int ArticleId { get; } public int EmailTemplateId { get; } public DateTime DateCreated { get; } public int RecipientCount { get; } private ArticleEmailSummary(IGrouping&lt;DateTime, ArticleEmail&gt; grouping) { ArticleId = grouping.First().ArticleId; EmailTemplateId = grouping.First().EmailTemplateId; DateCreated = grouping.Key; RecipientCount = grouping.Count(); } public static List&lt;ArticleEmailSummary&gt; List(int ArticleId, int emailTemplateId) { // get email list from db List&lt;ArticleEmail&gt; emails = ArticleEmail.List(ArticleId, emailTemplateId); // order it ascending by creation date IOrderedEnumerable&lt;ArticleEmail&gt; emailsWithOrder = emails.OrderBy(e =&gt; e.DateCreated); // group into sublists, each group cachet up to X minutes of emails occuring after the first one IEnumerable&lt;IGrouping&lt;DateTime, ArticleEmail&gt;&gt; groups = emailsWithOrder.GroupBy(GetGroupingFunction()); // convert groupings to summaries and return return groups.Select(grouping =&gt; new ArticleEmailSummary(grouping)).ToList(); } private static Func&lt;ArticleEmail, DateTime&gt; GetGroupingFunction() { // I am curious of other dev's opinion on this method :) TimeSpan maxMailingTime = TimeSpan.FromMinutes(30); DateTime lastDate = DateTime.MinValue; return delegate (ArticleEmail email) { if (email.DateCreated - lastDate &gt; maxMailingTime) { // the mailing was not sent within maxMailingTime from the start of first email in series // we will update the lastDate and this will group the emails into a separate group lastDate = email.DateCreated; } // now we return the value which groups our emails return lastDate; }; } } } </code></pre> <p>Edits:</p> <ul> <li>changed <code>emailTemplateId</code> to be of type <code>int</code> - it was just an <code>enum</code> ( with values such as "articleForApproval", "expiringArticle", etc. ), my bad, this must have been confusing indeed</li> <li><code>ArticleEmail.List(...)</code> simply returns <code>List&lt;ArticleEmail&gt;</code> that match the specified type of email and specific article</li> <li><p>as requested here, is the <code>ArticleEmail</code> class, a bit simplified for the purpose of this question:</p> <pre><code>public class ArticleEmail { public int ArticleId { get; } public int EmailTemplateId { get; } public DateTime DateCreated { get; } public int RecipientId { get; } public static List&lt;ArticleEmail&gt; List( int articleId, int emailTemplateId ) { // return instances from db } } </code></pre></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:07:29.350", "Id": "456973", "Score": "1", "body": "When you reference custom objects, it's hard to fully appreciate what you're doing without seeing the code for those objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:48:54.997", "Id": "457101", "Score": "1", "body": "you'll need to provide the `ArticleEmail` and `EmailTemplateId` classes as well. So, we can have a full understanding on how your code logic works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:04:46.317", "Id": "457137", "Score": "0", "body": "I added the `ArticleEmail` class as requested and updated `EmailTemplateId` to use `int` type consistently. Sorry for confusing you guys and thanks for your time and effort." } ]
[ { "body": "<p>This</p>\n\n<pre><code>private static Func&lt;ArticleEmail, DateTime&gt; GetGroupingFunction()\n {\n // I am curious of other dev's opinion on this method :)\n\n TimeSpan maxMailingTime = TimeSpan.FromMinutes(30);\n DateTime lastDate = DateTime.MinValue;\n\n return delegate (ArticleEmail email)\n {\n if (email.DateCreated - lastDate &gt; maxMailingTime)\n {\n // the mailing was not sent within maxMailingTime from the start of first email in series\n // we will update the lastDate and this will group the emails into a separate group\n lastDate = email.DateCreated;\n }\n\n // now we return the value which groups our emails\n return lastDate;\n };\n }\n</code></pre>\n\n<p>I would just write as:</p>\n\n<pre><code> private static readonly TimeSpan maxMailingTime = TimeSpan.FromMinutes(30);\n private static readonly DateTime lastDate = DateTime.MinValue;\n private static readonly Func&lt;ArticleEmail, DateTime&gt; GroupingFunction = \n email =&gt; (email.DateCreated - lastDate &gt; maxMailingTime) ? email.DateCreated : lastDate; \n</code></pre>\n\n<p>To initialize a constant TimeSpan you can just use </p>\n\n<pre><code>new TimeSpan(30, 0, 0, 0);\n</code></pre>\n\n<p>that is a constant of 30 days. Your way with FromMinutes is intended to compute an floating point, like 3.76 days into a TimeSpan and is much slower and inaccurate, since it's floating point operations, not integer.</p>\n\n<p>While I'm not sure what you want with subtracting DateTime.MinValue, which is actually 0 or 1/1/1.\nDo you just want to convert a DateTime to a TimeSpan by computing the TimeSpan from 1/1/1 up to the Date ? Creative, but actually useless.</p>\n\n<p>You can get the same with</p>\n\n<pre><code> const long maxMailingTicks = 30*60*1000000L; // 30minutes\n if (email.DateCreated.Ticks &gt; maxMailingTicks)\n</code></pre>\n\n<p>Let's think on.\nHow can a Date ever be smaller than 30minutes ? Do you really want to deal or Check on Dates in the first 30minutes of the life of Jesus Christ ?</p>\n\n<p>So where do we end up ? </p>\n\n<pre><code> private static readonly Func&lt;ArticleEmail, DateTime&gt; = email =&gt; email.DateCreated;\n</code></pre>\n\n<p>If we assume, the email was not send to notify of the birth of Jesus, there is nothing left to do.</p>\n\n<p>But if you want to keep your test:</p>\n\n<pre><code> private static readonly Func&lt;ArticleEmail, DateTime&gt; GroupingFunction = email =&gt; \n email.DateCreated.Ticks &gt; maxMailingTicks ? email.DateCreated : DateTime.MinValue;\n</code></pre>\n\n<p>To Have this possibly working on Linq to SQL also, you rather use \n<code>Expression&lt;Func&lt;ArticleEMail, DateTime&gt;&gt;</code> as the Type of the function. There is nothing else to do than exchanging the return type/type of my field. When dealing with Dates and SQL you have to use some special functions sometimes, there could be a revision necessary, but with just \"Func\", its definitly impossible ever to become SQL at all.\nThis would definitly work on SQL:</p>\n\n<pre><code> private static readonly Expression&lt;Func&lt;ArticleEmail, DateTime&gt;&gt; = email =&gt; email.DateCreated;\n</code></pre>\n\n<p>Actually your code was too long. I just dealed with the last 10 lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:27:43.177", "Id": "457122", "Score": "0", "body": "`GetGroupingFunction` declares `lastDate` in order to make it persist between invocations of the returned `delegate`. The delegate updates this value when it finds current item diverges from the last stored value too much ( the assignment `lastDate = email.DateCreated;` ) This way the `lastDate` is moved forward in time as the call to `emailsWithOrder.GroupBy` progresses over items. Your answer kind of proves my code is indeed somewhat hard to understand despite my efforts to make it clean and readable. Now I need to figure out how to make it easier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:38:36.727", "Id": "457133", "Score": "0", "body": "I see, my mistake. In this case it's just not useable for grouping. You have to have a function that is returning always the same, if you call it twice. And this does not, it depends on how often it was called before. It's the same rules as for a Hashcode.\nHowever, just to make this more readable, make this thing a class, with properties and methods, and take this Method as your delegate. In this way you also have access to your last date. Actually the compiler is doing exactly the same, that is called a closure (around local variables)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:43:58.027", "Id": "457135", "Score": "0", "body": "It is working code (actually tested) which correctly groups emails into frames of time. When we find an email which does not fit into a 30 minute frame of time starting at `lastDate` we update this date. The subsequent records which fall into the time frame use the `lastDate` as their grouping value without updating it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:01:30.473", "Id": "457159", "Score": "0", "body": "if you group (2001,2002,2003) it will result in 3 groups, if you group(2003,2002,2001) it will result in 1 group, if it's (2002, 2003, 2001) it will be 2 groups. Maybe this is desired behavior, but this is not what people usually consider as grouping. I'm assuming the algorithm reads the data in a linear way, but since we shall not make assumptions on the implementation of GroupBy, the result is unpredictable. It depends on the order of elements. You have ascending sorted data and want to form clusters, it's a creative idea - but it's kind of manual obfuscation to hide this behind a GroupBy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T00:29:03.433", "Id": "457173", "Score": "0", "body": "Don't worry about the orders of dates I sort the records right before grouping." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:54:41.097", "Id": "233804", "ParentId": "233739", "Score": "3" } }, { "body": "<p>This combines the GroupBy and the following Select into Once.\nIt should be easier to understand and much more performant, cause it does not involve the LINQ-GroupBy algorithm. It's your algorithm that does the grouping.</p>\n\n<pre><code>private static IEnumerable&lt;ArticleEmailSummary&gt; \nMakeGroups(IOrderedEnumerable&lt;ArticleEmail&gt; emails)\n{\n TimeSpan maxMailingTime = new TimeSpan(30, 0, 0, 0); // could be a static readonly field also\n DateTime lastDate = DateTime.MinValue;\n\n var list = new List&lt;ArticleEMail&gt;();\n\n foreach(var email in emails)\n {\n if (email.DateCreated - lastDate &gt; maxMailingTime)\n {\n // the mailing was not sent within maxMailingTime from the start of first email in series\n // we will update the lastDate and this will group the emails into a separate group\n\n if (list.Count &gt; 0)\n {\n yield return new ArticleEMailSummary(list); \n list = new List&lt;ArticleEMail&gt;();\n }\n\n lastDate = email.DateCreated;\n }\n list.Add(email);\n }\n Debug.Assert(list.Count &gt; 0);\n yield return new ArticleEMailSummary(list); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:15:45.260", "Id": "233821", "ParentId": "233739", "Score": "3" } }, { "body": "<p>I would advise against the use of <code>GroupBy</code> in this case. It seems dangerous to do so and is very hard to understand. I would recommend something like this:</p>\n\n<pre><code>public static bool WasSendShortlyAfter(this ArticleEmail email, ArticleEmail start)\n{\n var maxMailingTime = TimeSpan.FromMinutes(30);\n var diff = email.DateCreate - start.DateCreate;\n\n return diff &gt;= TimeSpan.Zero &amp;&amp; diff &lt;= maxMailingTime;\n}\n</code></pre>\n\n<p>and then you can do this:</p>\n\n<pre><code>var groupStarters = emails\n .Where(potentialStart =&gt; !emails\n .Any(email =&gt; potentialStart.WasSendShortlyAfter(email)));\nvar groups = groupStarters\n .Select(start =&gt; emails.Where(email =&gt; email.WasSendShortlyAfter(start));\n</code></pre>\n\n<p>Remarks:</p>\n\n<ul>\n<li>Alternatively <code>WasSendShortlyAfter</code> could be a member method of <code>ArticleEmail</code>.</li>\n<li>It would be nice if <code>maxMailingTime</code> would be configurable in some way.</li>\n<li>Not sure how performant my solution is. If the operation is performance critical there might be better options.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:52:23.133", "Id": "457247", "Score": "1", "body": "Yes, one especially curious effect occured when I returned IEnumerable<ArticleEmailSummary> instead ot List<ArticleEmailSummary>. It was iterated multiple times and used same grouping function. The function was not resetting its state at any point. After iterating once, which returned correct groups it kept returning one group with all emails ( because `lastDate` was set to the last group ). I like your idea of `groupStarters` - I'll experiment around it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:03:30.833", "Id": "233856", "ParentId": "233739", "Score": "3" } } ]
{ "AcceptedAnswerId": "233856", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T01:50:11.403", "Id": "233739", "Score": "4", "Tags": [ "c#", "linq" ], "Title": "C# + Linq - grouping objects by frames of time found in the data" }
233739
<h1>Advent of Code 2019: Day 4</h1> <p>I'm doing <a href="https://adventofcode.com/" rel="noreferrer">Advent of Code</a> this year. Below is my attempt at <a href="https://adventofcode.com/2019/day/4" rel="noreferrer">day 4</a>:</p> <h2>Problem</h2> <h3>Part One</h3> <blockquote> <p>--- Day 4: Secure Container ---</p> <p>You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.</p> <p>However, they do remember a few key facts about the password:</p> <ul> <li>It is a six-digit number.</li> <li>The value is within the range given in your puzzle input.</li> <li>Two adjacent digits are the same (like <code>22</code> in <code>122345</code>).</li> <li>Going from left to right, the digits never decrease; they only ever increase or stay the same (like <code>111123</code> or <code>135679</code>).</li> </ul> <p>Other than the range rule, the following are true:</p> <ul> <li><code>111111</code> meets these criteria (double <code>11</code>, never decreases).</li> <li><code>223450</code> does not meet these criteria (decreasing pair of digits <code>50</code>).</li> <li><code>123789</code> does not meet these criteria (no double).</li> </ul> <p>How many different passwords within the range given in your puzzle input meet these criteria?</p> </blockquote> <p> </p> <h3>Part Two</h3> <blockquote> <p>--- Part Two ---</p> <p>An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.</p> <p>Given this additional criterion, but still ignoring the range rule, the following are now true:</p> <ul> <li><code>112233</code> meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.</li> <li><code>123444</code> no longer meets the criteria (the repeated <code>44</code> is part of a larger group of <code>444</code>).</li> <li><code>111122</code> meets the criteria (even though <code>1</code> is repeated more than twice, it still contains a double <code>22</code>).</li> </ul> <p>How many different passwords within the range given in your puzzle input meet all of the criteria?</p> </blockquote> <hr /> <h2>Solution</h2> <pre class="lang-py prettyprint-override"><code>from itertools import groupby bounds = (265275, 781584) rules = [ # Digits are never decreasing lambda s: all(int(s[i]) &lt;= int(s[i+1]) for i in range(len(s)-1)), # Two adjacent digits are equal. lambda s: any(s[i] == s[i+1] for i in range(len(s)-1)), # Two adjacent digits don't form a larger group. lambda s: any(len(list(v)) == 2 for _, v in groupby(s)) ] def test(num, rules): return all(f(str(num)) for f in rules) def solve(bounds, rules): return sum(1 for i in range(bounds[0], bounds[1]+1) if test(i, rules)) def part_one(): return solve(bounds, rules[:2]) def part_two(): return solve(bounds, rules[::2]) print(part_one()) # 960 print(part_two()) # 626 </code></pre> <hr /> <h2>Notes</h2> <p>I don't consider myself a beginner in Python, however I am not proficient in it either. I guess I would be at the lower ends of intermediate. I am familiar with PEP 8 and have read it in its entirety, thus, any stylistic deviations I make are probably deliberate. Nevertheless, feel free to point them out if you feel a particular choice of mine was sufficiently erroneous. I am concerned with best practices and readability, but also the performance of my code. I am not sure what tradeoff is appropriate, and would appreciate feedback on the tradeoffs I did make.</p> <p>My style tends to over utilise functions. This is partly because I genuinely think separating functionality into functions is a good thing, but is also an artifiact of my development practices. I tend to write the program in a Jupyter notebook (the ability to execute arbitrary code excerpts in semi isolated cells is a very helpful development aid and lends itself naturally to one function per cell (with the added benefit of being able to easily test functions independently)). I would welcome thoughts on this, but unless it is particularly egregious, I am unlikely to change it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:24:20.843", "Id": "457033", "Score": "3", "body": "I just wanted to compliment you on some very clean and easy-to-understand code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:25:02.317", "Id": "457109", "Score": "0", "body": "You got a bug in part2: It returns True for 1223333. I don't understand why you'd drop a rule if the challenge says \"additional detail\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:51:20.040", "Id": "457148", "Score": "1", "body": "Not really. `1223333` is outside the bounds. I dropped rule 2 because it is implicit in rule 3." } ]
[ { "body": "<p>Overall, it looks good to me. Just a couple observations. They aren't necessarily better or more pythonic, but you may see them in peoples code. Use whichever you find more readable:</p>\n\n<p>The first rule turns the digits to ints to compare them, but the ascii for the digits compares the same as the integer digits ('0' &lt; '1' ... &lt; '9'). So the <code>int()</code> isn't needed. Also, a common idiom for comparing adjacent items in a list is to use <code>zip(seq, seq[1:])</code>. The first two rules could be coded as:</p>\n\n<pre><code># Digits are never decreasing\nlambda s: all(a &lt;= b for a,b in zip(s, s[1:])),\n\n# Two adjacent digits are equal.\nlambda s: any(a == b for a,b in zip(s, s[1:])),\n</code></pre>\n\n<p>In a numeric context, True and False are converted to 1 and 0, respectively. So, solve can be coded as:</p>\n\n<pre><code>def solve(bounds, rules):\n return sum(test(i, rules) for i in range(bounds[0], bounds[1]+1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:56:45.907", "Id": "233743", "ParentId": "233741", "Score": "13" } }, { "body": "<p>Overall, I like this. To really nitpick, I don't really like the use of <code>rules[::2]</code>. <code>[::2]</code> conveys that we are picking out every even element of <code>rules</code> as if that was significant. But in this case, it is more like it just happens to be that the first and last rules are what we want to pick out and that happened to match up with choosing all even elements.</p>\n\n<p>I would probably just name the rules as follows. If the visual grouping of the rules is important you could wrap them in a class as static methods.</p>\n\n<pre><code>from itertools import groupby\n\nbounds = (265275, 781584)\n\ndef digits_never_decreasing(s):\n return all(int(s[i]) &lt;= int(s[i+1]) for i in range(len(s)-1))\n\ndef adjacent_digits_equal(s):\n return any(s[i] == s[i+1] for i in range(len(s)-1))\n\ndef adjacent_digits_not_in_larger_group(s):\n return any(len(list(v)) == 2 for _, v in groupby(s))\n\n\ndef test(num, *rules):\n return all(f(str(num)) for f in rules)\n\ndef solve(bounds, *rules):\n return sum(1 for i in range(bounds[0], bounds[1]+1) if test(i, *rules))\n\ndef part_one():\n return solve(bounds, digits_never_decreasing, adjacent_digits_equal)\n\ndef part_two():\n return solve(bounds, digits_never_decreasing, adjacent_digits_not_in_larger_group)\n\n\nprint(part_one()) # 960\nprint(part_two()) # 626\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:53:15.777", "Id": "457149", "Score": "0", "body": "I really like this, and it's probably the most pythonic. I accepted the answer below because it was the most informative, educational for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T00:38:01.073", "Id": "457174", "Score": "0", "body": "This also solves the issue of parameter `rules` shadowing global `rules`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:06:46.023", "Id": "233746", "ParentId": "233741", "Score": "16" } }, { "body": "<p>The algorithm is non-optimal. While this brute force solution solves the task, it is very slow. It takes <strong>2,435s</strong> to solve both parts of the task while my algorithm takes <strong>0,032s</strong>.</p>\n<p>I suggest to construct only suitable numbers (every next digit is greater or equal to previous) from the start, instead of checking all numbers in range. The amount of suitable numbers is small, so it is easy to check them for meeting <strong>part one's</strong> and <strong>part two's</strong> conditions.</p>\n<h3>Algorithm:</h3>\n<p><strong>My input is &quot;372304-847060&quot;</strong>, so <code>start = 372304</code>, <code>end = 847060</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/IS9or.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IS9or.png\" alt=\"enter image description here\" /></a></p>\n<h3>Implementation:</h3>\n<pre><code>#!/usr/bin/python3\n\nfrom collections import Counter\n\ndef find_first_value(number):\n fill_digit = 0\n max_fill_digit_found = False\n new_number = []\n for digit in number:\n digit = int(digit)\n if digit &gt;= fill_digit and not max_fill_digit_found:\n fill_digit = digit\n else:\n max_fill_digit_found = True\n\n new_number.append(fill_digit)\n\n return new_number\n\ndef find_all_passwords(cur_value, end_value):\n length = len(cur_value)\n # Two lists comparison.\n # The comparison uses lexicographical ordering:\n # first the first two items are compared, and if they differ\n # this determines the outcome of the comparison;\n # if they are equal, the next two items are compared, and so on,\n # until either sequence is exhausted.\n while cur_value &lt; end_value:\n idx = length - 1\n for dgt in range(cur_value[idx], 10):\n cur_value[idx] = dgt\n yield cur_value\n \n while cur_value[idx] == 9 and idx &gt; 0:\n idx -= 1\n\n fill_dgt = cur_value[idx] + 1\n for i in range(idx, length):\n cur_value[i] = fill_dgt\n\ndef part_one(first_value, end_value):\n for val in find_all_passwords(first_value, end_value):\n # If all digits in the list are unique: the len(list) == len(set()).\n # Else at least one digit are repeated.\n if len(set(val)) &lt; len(val):\n yield val\n\ndef part_two(first_value, end_value):\n for val in find_all_passwords(first_value, end_value):\n # Counts the occurence of every digit.\n cntr = Counter(val)\n # If the number contains some digit two times.\n if 2 in cntr.values():\n yield val\n\npuzzle_input = &quot;372304-847060&quot;\nstart, end = puzzle_input.split('-')\n\nfirst_value = find_first_value(start)\nend = list(map(int, end))\n\nprint(sum(1 for _ in part_one(first_value.copy(), end)))\nprint(sum(1 for _ in part_two(first_value.copy(), end)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:27:04.833", "Id": "233808", "ParentId": "233741", "Score": "6" } }, { "body": "<p>Your code initially looks well organised, but is quite hard to follow. </p>\n\n<p>To begin, you pass in nearly identical parameters to the two functions <code>part_one</code> and <code>part_two</code> and it is not immediately clear why. Next, using lambda functions as you currently are isn't recommended; as these are anonymous functions they won't have a name which can make debugging harder e.g if you get and error you'll be told it's in <code>&lt;lambda&gt;</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [35]: a = lambda s: any(s[i] == s[i+1] for i in range(len(s)-1))\nIn [36]: def adjacent(s):\n ...: return any(s[i] == s[i+1] for i in range(len(s)-1))\nIn [37]: a\nOut[37]: &lt;function &lt;lambda&gt; at 0x105767cb0&gt;\n\nIn [38]: adjacent\nOut[38]: &lt;function adjacent at 0x105aa29e0&gt;\n</code></pre>\n\n<p>I would advocate the style seen in <a href=\"https://codereview.stackexchange.com/a/233746/138176\">Kent's answer</a>. </p>\n\n<p>Another improvement is noticing that the answer to part two is a subset of values you generated for part one, so you should try to use that instead of having to regenerate and then filter another set of values.</p>\n\n<hr>\n\n<p>A couple of extra things that you may want to consider: </p>\n\n<p>From the Advent of Code about page:</p>\n\n<blockquote>\n <p>every problem has a solution that completes in at most 15 seconds on ten-year-old hardware</p>\n</blockquote>\n\n<p>This means that there is sometimes a trick or a shortcut that you can use to get to a solution faster, and potentially in fewer lines of code. For example, I'll share my solution:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ndef part_1(a, b):\n for i in range(a, b + 1):\n x = list(str(i))\n if x != sorted(x) or len(set(x)) == len(x):\n continue\n yield str(i)\n\ndef part_2(passwords):\n return sum(1 for x in passwords if 2 in Counter(x).values())\n\n\npasswords = list(part_1(152085, 670283))\nprint(len(passwords))\nprint(part_2(passwords))\n</code></pre>\n\n<p>Here, <code>part_1</code> is essentially a wrapper for <code>range</code> that is filtering the values we get. </p>\n\n<ul>\n<li><code>x != sorted(x)</code> checks if the digits are increasing as a sorted string will always be increasing. </li>\n<li><code>len(set(x)) == len(x)</code> tests if the number of unique digits is equal to the total number of digits, if true there cannot be any duplicated values. </li>\n<li>These two rules together also implicitly enforce the rule that some adjacent digits are the same, so we don't need to test for it.</li>\n</ul>\n\n<p><code>part_2</code> uses a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a> (a special kind of dictionary) to easily get the total number of each digit in the string and checking if <code>2</code> is in the values. In my opinion, this is very clear as it reads like a sentence. </p>\n\n<p>Finally, you could easily improve the readability of my code by further abstracting the conditions in <code>part_1</code>, like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def increasing(x):\n return x == \"\".join(sorted(x))\n\ndef duplicates_in(x):\n return len(set(x)) != len(x)\n\ndef part_1(a, b):\n for i in range(a, b + 1):\n i = str(i)\n if not increasing(i) or not duplicates_in(i):\n continue\n yield i\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T00:14:20.923", "Id": "233829", "ParentId": "233741", "Score": "5" } }, { "body": "<p>One note, you can skip nearly all of the checks for part 1 by realizing that the second constraint is (almost) guaranteed by the first within the bounds. If your starting position is <code>37xxxx</code> then only <code>456789</code> doesn't repeat a digit. Thus you can just construct all increasing values from <code>37xxxx</code> to <code>84xxxx</code> and subtract one.</p>\n\n<p><em>DISCLAIMER: It seems as though the inputs vary per person, so this trick isn't valid for everyone</em></p>\n\n<pre><code># With input 372xxx-84xxxx\n# min value 377777, max value 799999\ncount = -1 # skip 456789\n# This loop and/or sum can be collapsed upwards with cleverness\n# that is unnecessary for such small ranges of numbers.\nfor a in range(3, 8):\n for b in range(7 if a == 3 else a, 10):\n for c in range(b, 10):\n for d in range(c, 10):\n for e in range(d, 10):\n for f in range(e, 10):\n count += 1\nprint(count)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T00:55:03.190", "Id": "233831", "ParentId": "233741", "Score": "1" } } ]
{ "AcceptedAnswerId": "233743", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:12:06.220", "Id": "233741", "Score": "14", "Tags": [ "python", "algorithm", "programming-challenge" ], "Title": "Advent of Code 2019: Day 4" }
233741
<p>The function should return a string with balanced parenthesis. The code I wrote is working for all the inputs below. I am using stack data structure. I suppose this should work for all the edge cases. Can this solution be optimized further? </p> <pre><code>import java.util.ArrayList; import java.util.Stack; public class BalanceParenthesis { public static String balanceParenthesis(String input) { Stack&lt;String&gt; st = new Stack&lt;&gt;(); ArrayList&lt;Integer&gt; indicesList = new ArrayList&lt;Integer&gt;(); for (int i = 0; i &lt; input.length(); i++) { if (st.isEmpty()) { if (input.charAt(i) == ')') indicesList.add(i); if (input.charAt(i) == '(') st.push("(" + i); } else { if ((input.charAt(i) == ')') &amp;&amp; st.peek().charAt(0) == '(') st.pop(); if (input.charAt(i) == '(') st.push("(" + i); } } while (!st.isEmpty()) indicesList.add(Integer.parseInt(String.valueOf(st.pop().charAt(1)))); StringBuffer buff = new StringBuffer(); for (int i = 0; i &lt; input.length(); i++) { if (!indicesList.contains(i)) buff.append(input.charAt(i)); } return buff.toString(); } public static void main(String[] args) { System.out.println(balanceParenthesis("q(y)s)")); // q(y)s System.out.println(balanceParenthesis("(((((")); //"" System.out.println(balanceParenthesis(")))")); // "" System.out.println(balanceParenthesis("(()()(")); //()() System.out.println(balanceParenthesis(")())(()()(")); // ()()() System.out.println(balanceParenthesis("((())))")); //((())) } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>You write information to the stack in two places, and both of them look like this:</p>\n\n<pre><code>st.push(\"(\" + i);\n</code></pre>\n\n<p>That means <code>st.peek().charAt(0) == '('</code> is always true, and you can remove it.</p></li>\n<li><p>The only remaining place that reads the values in the stack reads</p>\n\n<pre><code>st.pop().charAt(1)\n</code></pre>\n\n<p>That means it isn’t necessary to add the parenthesis at all when pushing, and the stack can be a stack of <code>Integer</code>s instead of <code>String</code>s.</p>\n\n<pre><code>Stack&lt;Integer&gt; st = new Stack&lt;&gt;();\nArrayList&lt;Integer&gt; indicesList = new ArrayList&lt;Integer&gt;();\n\nfor (int i = 0; i &lt; input.length(); i++) {\n if (st.isEmpty()) {\n if (input.charAt(i) == ')')\n indicesList.add(i);\n if (input.charAt(i) == '(')\n st.push(i);\n } else {\n if (input.charAt(i) == ')')\n st.pop();\n if (input.charAt(i) == '(')\n st.push(i);\n }\n}\n\nwhile (!st.isEmpty())\n indicesList.add(st.pop());\n\nStringBuffer buff = new StringBuffer();\nfor (int i = 0; i &lt; input.length(); i++) {\n if (!indicesList.contains(i))\n buff.append(input.charAt(i));\n}\n\nreturn buff.toString();\n</code></pre>\n\n<p>This is important for correctness, too, because <strong>integers could have been longer than one character</strong>. But now that’s fixed for free. Avoiding trips through data types that don’t really match up is good when possible.</p></li>\n<li><p><code>input.charAt(i)</code> is repeated, but it doesn’t have to be.</p>\n\n<pre><code>for (int i = 0; i &lt; input.length(); i++) {\n char c = input.charAt(i);\n\n if (st.isEmpty()) {\n if (c == ')')\n indicesList.add(i);\n if (c == '(')\n st.push(i);\n } else {\n if (c == ')')\n st.pop();\n if (c == '(')\n st.push(i);\n }\n}\n</code></pre></li>\n<li><p><code>st</code> being empty only matters when the character is <code>')'</code>, and you do the same thing in either case when it’s <code>'('</code>. The conditions are more natural turned inside-out.</p>\n\n<pre><code>if (c == '(') {\n st.push(i);\n} else if (c == ')') {\n if (st.isEmpty())\n indicesList.add(i);\n else\n st.pop();\n}\n</code></pre></li>\n<li><pre><code>for (int i = 0; i &lt; input.length(); i++) {\n if (!indicesList.contains(i))\n buff.append(input.charAt(i));\n}\n</code></pre>\n\n<p>This loop has the potential to be very slow, because it searches <code>indicesList</code> for every character of the input. In total, that takes time proportional to the number of unbalanced parentheses multiplied by the length of the input. One way to avoid that is to replace <code>indicesList</code> with an array of booleans indicating whether the character at the same position should be excluded from the result:</p>\n\n<pre><code>Stack&lt;Integer&gt; st = new Stack&lt;&gt;();\nboolean[] exclude = new boolean[input.length()];\n\nfor (int i = 0; i &lt; input.length(); i++) {\n char c = input.charAt(i);\n\n if (c == '(') {\n st.push(i);\n } else if (c == ')') {\n if (st.isEmpty())\n exclude[i] = true;\n else\n st.pop();\n }\n}\n\nwhile (!st.isEmpty())\n exclude[st.pop().intValue()] = true;\n\nStringBuffer buff = new StringBuffer();\n\nfor (int i = 0; i &lt; input.length(); i++) {\n if (!exclude[i])\n buff.append(input.charAt(i));\n}\n\nreturn buff.toString();\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:49:53.287", "Id": "456997", "Score": "0", "body": "Did you get the words in wrong order here? \"integers could have been longer than one character\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:59:44.643", "Id": "456999", "Score": "0", "body": "@TorbenPutkonen: `\"(\" + 12` gets read back as `1` by `.charAt(1)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:32:26.953", "Id": "233748", "ParentId": "233744", "Score": "4" } }, { "body": "<p>1) Use the <code>java.util.Deque</code> instead of the <code>java.util.Stack</code></p>\n\n<pre><code>A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:\n\n Deque&lt;Integer&gt; stack = new ArrayDeque&lt;Integer&gt;();\n</code></pre>\n\n<p>Source: <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Stack.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/9/docs/api/java/util/Stack.html</a></p>\n\n<p>2) Remove the \"Integer\" from the ArrayList section and use the List interface in the left section.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> List&lt;Integer&gt; indicesList = new ArrayList&lt;&gt;();\n</code></pre>\n\n<p>3) Instead of using the <code>java.lang.String#charAt</code> method, I suggest that you use an array and iterate on each instead.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> char[] charArray = input.toCharArray();\n for (int i = 0; i &lt; charArray.length; i++) {\n char currentChar = charArray[i];\n\n if (st.isEmpty()) {\n if (currentChar == ')') {\n indicesList.add(i);\n }\n if (currentChar == '(') {\n st.push(\"(\" + i);\n }\n } else {\n if ((currentChar == ')') &amp;&amp; st.peek().charAt(0) == '(') {\n st.pop();\n }\n if (currentChar == '(') {\n st.push(\"(\" + i);\n }\n }\n }\n</code></pre>\n\n<p>4) Create methods to check the type of parentheses</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n public static String balanceParenthesis(String input) {\n if (st.isEmpty()) {\n if (isClosingParentheses(input.charAt(i))) {\n indicesList.add(i);\n }\n if (isOpeningParentheses(input.charAt(i))) {\n st.push(\"(\" + i);\n }\n } else {\n if (isClosingParentheses(input.charAt(i)) &amp;&amp; isOpeningParentheses(st.peek().charAt(0))) {\n st.pop();\n }\n if (isOpeningParentheses(input.charAt(i))) {\n st.push(\"(\" + i);\n }\n }\n //[...]\n }\n\n\n private static boolean isOpeningParentheses(char currentChar) {\n return currentChar == '(';\n }\n\n private static boolean isClosingParentheses(char currentChar) {\n return currentChar == ')';\n }\n</code></pre>\n\n<p>5) Instead of using \"if and else\", you can use if-else-if and extract similar logic in methods.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> final boolean isDequeEmpty = st.isEmpty();\n final boolean isClosingParentheses = isClosingParentheses(currentChar);\n\n if (isDequeEmpty &amp;&amp; isClosingParentheses) {\n indicesList.add(i);\n } else if (isDequeEmpty &amp;&amp; isOpeningParentheses(currentChar)) {\n st.push(\"(\" + i);\n } else if (!isDequeEmpty &amp;&amp; isClosingParentheses) {\n st.pop();\n } else if (!isDequeEmpty &amp;&amp; isOpeningParentheses(currentChar)) {\n st.push(\"(\" + i);\n }\n</code></pre>\n\n<p>6) Use the <code>java.lang.StringBuilder</code> instead of the <code>java.lang.StringBuffer</code></p>\n\n<pre><code>As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.\n</code></pre>\n\n<p>Source: <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/StringBuffer.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/9/docs/api/java/lang/StringBuffer.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:04:03.867", "Id": "457087", "Score": "0", "body": "What exactly do you gain by extracting `ch == '('` into a separate method? The function that contains this code is short enough to be understandable on its own. At some point you _do_ have to write the character literals when doing string processing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:06:34.600", "Id": "457090", "Score": "0", "body": "In your suggestions (1) and (2), you don't provide any rationale _why_ your suggestion is better than the original code. Therefore it's difficult to see whether your suggestions make sense or in which other cases they apply. And by the way, to quote text that is not code, you should prefix it with `>` instead of backticks, which avoids the horizontal scrollbars." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:45:19.743", "Id": "457100", "Score": "0", "body": "Hello Rolland,\n\nIn my opinion, when you extract the comparison to a method, it adds visibility and remove the potential error, when reading the expression when there are lots of similar characters near each other. That's why i try to extract characters and string comparison to methods; it adds nothing more than the previous code, in terms of optimization.\n\nFor the second comment, I didn't feel, at that time, the need to add more explanation than the provided link to the JavaDoc. I will try to explain more next time.\n\nThanks for your remarks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:55:14.737", "Id": "233795", "ParentId": "233744", "Score": "0" } }, { "body": "<p>In addition to the other answers, I'm focusing on the <code>main</code> method.</p>\n\n<p>It's great that you have provided example test cases with your code since the words \"balance parentheses\" leave much room for interpretation. By providing examples, you close this gap. Ideally you would add a few comments to the examples, for example why you expect exactly this output and what other outputs would be possible but not desired.</p>\n\n<p>When you want to validate your tests, you currently have to inspect the output from <code>System.out</code> manually. That's error prone, especially for counting lots of parentheses. You can easily automate this by writing the following code:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void testBalanceParentheses(String input, String expectedOutput) {\n String actualOutput = balanceParenthesis(input);\n if (!Objects.equals(actualOutput, expectedOutput)) {\n throw new AssertionError(\n String.format(\n \"Expected \\\"%s\\\" for \\\"%s\\\", but got \\\"%s\\\".\",\n expectedOutput, input, actualOutput));\n }\n}\n\nprivate static void testBalanceParentheses() {\n testBalanceParentheses(\"q(y)s)\", \"q(y)s\");\n testBalanceParentheses(\"(((((\", \"\");\n testBalanceParentheses(\")))\", \"\");\n testBalanceParentheses(\"(()()(\", \"()()\");\n testBalanceParentheses(\")())(()()(\", \"()()()\");\n testBalanceParentheses(\"((())))\", \"((()))\");\n}\n\npublic static void main(String[] args) {\n testBalanceParentheses();\n}\n</code></pre>\n\n<p>This way, you just have to run the program, and if it outputs nothing, everything is fine.</p>\n\n<p>This idea of having automated test cases is so popular that the <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">JUnit project</a> has developed a framework to make testing easier. When you use it, you don't have to write the low-level <code>throw new AssertionError</code> yourself, but can use the higher-level <code>Assert.assertEquals</code> method:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void testBalanceParentheses(String input, String expectedOutput) {\n String actualOutput = balanceParenthesis(input);\n Assert.assertEquals(expectedOutput, actualOutput);\n}\n\n@Test\nvoid testBalanceParentheses() {\n testBalanceParentheses(\"q(y)s)\", \"q(y)s\");\n testBalanceParentheses(\"(((((\", \"\");\n testBalanceParentheses(\")))\", \"\");\n testBalanceParentheses(\"(()()(\", \"()()\");\n testBalanceParentheses(\")())(()()(\", \"()()()\");\n testBalanceParentheses(\"((())))\", \"((()))\");\n}\n</code></pre>\n\n<p>See how the code gets shorter and simpler? That's what JUnit is for.</p>\n\n<p>Finally, here is the test code with the additional comments I would add:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\nvoid testBalanceParentheses() {\n\n // Trailing closing parentheses are omitted.\n testBalanceParentheses(\"q(y)s)\", \"q(y)s\");\n\n // Opening parentheses that don't get closed again are omitted as well.\n testBalanceParentheses(\"(((((\", \"\");\n\n // Unmatched closing parentheses are omitted.\n testBalanceParentheses(\")))\", \"\");\n\n // TODO: Add another test case to demonstrate which of\n // the opening parentheses is omitted.\n // \"a(b(c(d)e(f)g(h\"\n // Do you expect \"ab(c\" or \"a(bc\"?\n testBalanceParentheses(\"(()()(\", \"()()\");\n\n // TODO: Add another test case to demonstrate which of the\n // closing parentheses is omitted, like above.\n testBalanceParentheses(\")())(()()(\", \"()()()\");\n\n // Perfectly balanced nested parentheses are kept.\n testBalanceParentheses(\"((())))\", \"((()))\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:22:41.923", "Id": "233797", "ParentId": "233744", "Score": "0" } } ]
{ "AcceptedAnswerId": "233748", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T04:00:38.813", "Id": "233744", "Score": "3", "Tags": [ "java" ], "Title": "Balance Parenthesis" }
233744
<p>I have written the following program to read from a file (entire input in single line) and check for:</p> <ul> <li>ASCII punctuation characters</li> <li>a final newline</li> </ul> <pre><code>import re file_name=input("Please enter the file name ") with open(file_name, 'r') as fp: context=fp.read() regex = re.compile('[@_!#$%^&amp;*()&lt;&gt;?/\|} {~]') if regex.search(context) is None: print("No special character found") else: print("Special character found") for x in range(0,len(context)-1): if (context[x].isspace())==True: print("spaces found in the file at ", x) break else: pass #print("No space found") for x in range(0, len(context)-1): if context[x]=='\n' or context[x]=='"': print("Yes new line is there at", x) break else: pass #print("No new line ") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:25:02.923", "Id": "456988", "Score": "1", "body": "What is the benefit of getting the **position** of just the **1st** space or newline char IF there could be multiple of such? (that's what your code is doing now) And why should `\\n` and `\"` be equivalents?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:36:00.737", "Id": "456989", "Score": "0", "body": "My code is to find find all new lines, and spaces and special characters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:38:18.747", "Id": "456991", "Score": "0", "body": "@naryana, when you said **all** - that directly contradicts with your current code which `break`s on the 1st occurrence. Your code is not working as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:39:09.527", "Id": "456992", "Score": "0", "body": "Please help me to get it correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:39:57.127", "Id": "456993", "Score": "0", "body": "The point is that direct fixing is **out** of scope on this site - you'd need to post already working code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:41:05.243", "Id": "456994", "Score": "0", "body": "Thanks for your findings, thanks a lot . I will fix the issues that you have identified" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:41:46.517", "Id": "456995", "Score": "0", "body": "Ok, update your code appropriately" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:03:53.593", "Id": "457000", "Score": "0", "body": "Because of break statement its not getting repeated" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T09:28:59.003", "Id": "457015", "Score": "0", "body": "You did not update your code according to your statement \"find **all** new lines, and spaces and special characters\"" } ]
[ { "body": "<p><code>\\|</code> is not a proper escape sequence. To include the backslash in the string, it should be escaped using two backslashes, or you should use a “raw” string for the regular expression, so backslashes do not need to be escaped.</p>\n\n<p><code>for x in range(0, len(context) - 1):</code> does not check the last character of the string, since <code>range(start, end)</code> already does not include <code>end</code>.</p>\n\n<p><code>if (context[x].isspace())==True:</code> does not need the parentheses around <code>context[x].isspace()</code>, nor does it need the <code>== True</code>.</p>\n\n<p>You can use <code>enumerate()</code> to loop over the contents of an iterable and get the index at the same time. Also, a <code>for ... else</code> block can be used to detect if nothing was found. With Python 3.6 or later, f-strings can be used to embed variables directly in strings.</p>\n\n<pre><code>for idx, ch in enumerate(context):\n if ch.isspace():\n print(f\"spaces found in the file at {idx}\")\n break\nelse:\n print(\"no space found\")\n</code></pre>\n\n<p>It is strange to find a quotation mark, and declare that a new line has been found. Are you sure you’ve got your logic correct?</p>\n\n<p>PEP8 Guidelines:</p>\n\n<ul>\n<li>spaces around all operators, like <code>=</code>, <code>==</code>, <code>-</code></li>\n<li>use a space after each comma in argument lists</li>\n<li>blank line after imports</li>\n<li>longer, descriptive variable names (<code>x</code> is too short and not descriptive)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:37:46.517", "Id": "456990", "Score": "0", "body": "Yes. I need to have only text that to in single line. No new lines, no spaces and no special characters to be found." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:24:36.867", "Id": "233753", "ParentId": "233751", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T05:46:07.733", "Id": "233751", "Score": "1", "Tags": [ "python", "io" ], "Title": "Test a single-line file for punctuation and newline" }
233751
<p>I am doing a project to compare the time complexity of 2 string search algorithms. I lost my previous code due to some issues and so have had to rewrite the majority. However, this time around, my KMP algorithm seems to be running a lot slower, and I can never actually get it to run faster than my Boyer-Moore no matter what I input. Here is my code:</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;chrono&gt; using namespace std; //set number of characters for lookup table # define number_chars 256 //type alias for clock typedef chrono::steady_clock clocktime; void boyer_moore(string text, string pattern, int textlength, int patlength) { //start timer clocktime::time_point start = clocktime::now(); //create vector list of all the locations the pattern was found vector&lt;int&gt; indexes; //create array for lookup table int lookup[number_chars]; //initially fill every index of lookup table with -1 for (int i = 0; i &lt; number_chars; i++) { lookup[i] = -1; } //for every character in pattern, set lookup table at index = integer value for character to be the index of the character within the pattern for (int i = 0; i &lt; patlength; i++) { lookup[(int)pattern[i]] = i; } //shift variable for keeping track of location in text int shift = 0; while (shift &lt;= (textlength - patlength)) { int j = patlength - 1; //works through pattern from end to start checking if characters in text match, stops when j&lt;0 or character in text doesn't match character in pattern while (j &gt;= 0 &amp;&amp; pattern[j] == text[shift + j]) { j--; } //if pattern found if (j &lt; 0) { //add location pattern was found to location list indexes.push_back(shift); //if have not reached end of text if (shift + patlength &lt; textlength) { //skip over pattern just found so next character in text lines up with last character of pattern shift += patlength - lookup[text[shift + patlength]]; } //if pattern occurs at end of text add 1 to shift -&gt; next while loop will fail else { shift += 1; } } //if pattern not found else { //checks if current character in text is an ASCII character -&gt; if not it would be negative //(was having some issues previously with non-ASCII characters setting my array to out of bounds so added this condition) if (lookup[text[shift + j]] &gt; -1) { //shifts pattern so unmtaching character in text lines up with last character in pattern shift += max(1, j - lookup[text[shift + j]]); } //if non-ASCII character, then it is not in pattern being searched anyway -&gt; skip to next character else { shift += 1; } } } //end timer clocktime::time_point end = clocktime::now(); //calculate time taken auto time_taken = chrono::duration_cast&lt;chrono::milliseconds&gt;(end - start).count(); //display index locations of pattern cout &lt;&lt; "Index locations of '" &lt;&lt; pattern &lt;&lt; "':" &lt;&lt; endl; for (int in : indexes) { cout &lt;&lt; in &lt;&lt; ", "; } //display time taken cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl &lt;&lt; "Boyer-Moore: time taken: " &lt;&lt; time_taken &lt;&lt; "ms" &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl; } void kmp(string text, string pattern, int textlength, int patlength) { //start time clocktime::time_point start = clocktime::now(); //create vector list of all the locations the pattern was found vector&lt;int&gt; indexes; //creates prefix table //had to use vector as compiler was complaining about patlength not being a constant value, even when I set it it const int vector&lt;int&gt; table(patlength); //keeps track of length of previous longest prefix suffix int k = 0; //filling in prefix table for (int i = 1; i &lt; patlength; i++) { while (k &gt; 0 &amp;&amp; pattern[k] != pattern[i]) { //u k = table[k-1]; } if (pattern[k] == pattern[i]) { //update longest suffix k = k + 1; } table[i] = k; } int textindex = 0; int patindex = 0; while (textindex &lt; textlength) { if (pattern[patindex] == text[textindex]) { textindex++; patindex++; } if (patindex == patlength) { indexes.push_back(textindex-patlength); patindex = table[patindex - 1]; } else if (textindex &lt; textlength &amp;&amp; pattern[patindex] != text[textindex]){ if (patindex != 0) { patindex = table[patindex - 1]; } else { textindex++; } } } //end timer clocktime::time_point end = clocktime::now(); auto time_taken = chrono::duration_cast&lt;chrono::milliseconds&gt;(end - start).count(); cout &lt;&lt; "Index locations of '" &lt;&lt; pattern &lt;&lt; "':" &lt;&lt; endl; for (int in : indexes) { cout &lt;&lt; in &lt;&lt; ", "; } cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl &lt;&lt; "KMP: time taken: " &lt;&lt; time_taken &lt;&lt; "ms" &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl; } //load file method borrowed from lab exercise string load_file() { std::string directory = ""; string text; for (int i = 0; i &lt; 6; i++) { const string &amp; filename = "dna.txt"; //https://www.kaggle.com/ashishsinhaiitr/lord-of-the-rings-text/version/1#01%20-%20The%20Fellowship%20Of%20The%20Ring.txt ifstream f(directory + filename, std::ios_base::binary); if (!f.good()) { directory = "../" + directory; continue; } f.seekg(0, std::ios_base::end); const size_t length = f.tellg(); vector&lt;char&gt; buf(length); f.seekg(0); f.read(buf.data(), length); text.assign(buf.begin(), buf.end()); return text; } } void main() { //loads text file string text = load_file(); bool end = false; while (end == false) { //gets pattern from user cout &lt;&lt; "pattern: "; string pattern; cin &gt;&gt; pattern; int n = text.size(); int m = pattern.size(); //call both string search algorithms boyer_moore(text, pattern, n, m); kmp(text, pattern, n, m); //ask user if they want to end the program cout &lt;&lt; "Close program? (1 = yes, 0 = no): "; bool valid = false; //checks if user provided valid response -&gt; asks for another if not while (valid == false) { int userend; cin &gt;&gt; userend; if ((int)userend == 1) { valid = true; end = true; } else if ((int)userend == 0) { valid = true; } else { "Please enter a valid number: "; } } } } </code></pre> <p>As an example, in my previous results, for the word "the", Boyer-Moore took around 260ms and KMP took around 184ms. Now, Boyer-Moore of course still takes roughly 260ms, however KMP now takes around 330ms. Any pointers in the right direction would be greatly appreciated. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:53:28.197", "Id": "457166", "Score": "0", "body": "Welcome to code review. Your original title could have gotten your question closed. Please try to follow the code review guidelines at https://codereview.stackexchange.com/help/how-to-ask." } ]
[ { "body": "<p>Without a description of the KMP algorithm I can't begin to check where the code might be going wrong.</p>\n\n<h2>Make Sure to Fix all Warnings</h2>\n\n<p>When you are writing and compiling your code you might want to try to get all the warning messages as well as the compiler errors. Currently you have a possible bug in <code>string load_file()</code>, the compiler warning message for this is <code>'load_file': not all control paths return a value</code>. The <code>return text;</code> statement is inside the <code>for</code> loop so if the loop exits after 6 iterations the function doesn't return a value. Another possible bug is that since the <code>return text;</code> statement is in the <code>for</code> loop and it is not nested within an if statement the <code>for</code> loop only performs one iteration.</p>\n\n<p>A second problem that my compiler caught is that the declaration of <code>main()</code> is incorrect. The function <code>main()</code> is supposed to return an integer value to the operating system that indicates the status of the program, therefore the declaration should be:</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n\nint main()\n{\n ...\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p><em>Note if the program fails <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_FAILURE</a> can be returned from <code>main()</code> instead.</em> </p>\n\n<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>Need More Error Checking of User Input</h2>\n\n<p>The code performs error checking in <code>main()</code> for if the user wants to continue or not, but the code does not check other inputs such as checking the input here</p>\n\n<pre><code> std::cin &gt;&gt; pattern;\n</code></pre>\n\n<p>What if the user just hits the enter key, or they enter an invalid patter?</p>\n\n<h2>Complexity</h2>\n\n<p>The functions <code>main()</code>, <code>void boyer_moore(string text, string pattern, int textlength, int patlength)</code> and <code>void kmp(string text, string pattern, int textlength, int patlength)</code> are too complex (do too much). Each of these functions should be simplified by breaking them up into smaller functions that do exactly one thing. There are several reasons for this, one is that it is easier to write, debug, read and maintain smaller functions. A second reason is that some functions can be reused. When I was learning how to design programs in computer science they taught us to keep breaking problems into smaller and smaller pieces until each piece was easy to solve. A third benefit that might prove useful is that functions can be profiled so that you can see where the program is spending the most amount of time.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>Some examples of functions that should exist to simplify the program:</p>\n\n<p>Called from main:</p>\n\n<pre><code>bool executeAgain()\n{\n bool end = false;\n bool valid = false;\n do {\n int userend;\n cin &gt;&gt; userend;\n if ((int)userend == 1) {\n valid = true;\n end = true;\n }\n else if ((int)userend == 0) {\n valid = true;\n }\n else {\n \"Please enter a valid number: \";\n }\n } while (valid == false);\n\n return end;\n}\n</code></pre>\n\n<p>Checking user input on <code>pattern</code>.</p>\n\n<p>Starting the timer and stopping the timer. (you might want to look at <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY code</a> for this as well because this code is repeated in multiple places)</p>\n\n<p>In KMP each one of the loops looks complex enough to be it's own function, that is probably true in <code>boyer_moore</code> as well. By breaking up KMP you might spot the problem yourself. </p>\n\n<h2>Prefer '\\n` Over std::endl</h2>\n\n<p>When you are worried about performance it is better to output a new line rather than std::endl. std::endl flushes the output buffer and that means that it is calling a system function. Lines such as </p>\n\n<pre><code> cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl &lt;&lt; \"KMP: time taken: \" &lt;&lt; time_taken &lt;&lt; \"ms\" &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl;\n</code></pre>\n\n<p>can easily be rewritten as std::cout &lt;&lt; \"\\n\\n\\nKMP: time taken: &lt;&lt; time_taken &lt;&lt; \"ms\\n\\n\\n\"; and it will execute faster.</p>\n\n<h2>Prefer std::array Over C Style Arrays</h2>\n\n<p>C++ has a lot of container classes that are very useful, the code already uses <code>std::vector&lt;TYPE&gt;</code> but there is also <code>std::array&lt;TYPE, COUNT&gt;</code>, the benefits of using this container type is that it works similar to the old C style array, but it also can use iterators to index through the array and you can use a ranged for loop rather than hard coding for loops based on size.</p>\n\n<p>It is also better to use <code>constexpr</code> to define symbolic constants rather than <code>#define</code> which is a C programming construct rather than a C++ programming construct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T00:41:20.663", "Id": "233830", "ParentId": "233754", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:36:03.080", "Id": "233754", "Score": "3", "Tags": [ "c++" ], "Title": "Time Complexity Comparison of KMP string search to Boyer-Moore string search" }
233754
<p>I am writing one logic to iterate numbers first and then additional logic to putting them into particular subset of array. </p> <p>What does this code do: </p> <ol> <li>Code accept first <code>$n</code></li> <li>It creates an array of <code>$n</code> number from <code>1</code> to <code>$n</code></li> <li>Then started converting to subset of <code>$main_array</code> to possible one like <code>['1'] [1,2] [1,2,3] [2] [2,3] [3]</code> etc. <a href="https://www.geeksforgeeks.org/subarraysubstring-vs-subsequence-and-programs-to-generate-them/" rel="nofollow noreferrer">same like this</a> </li> <li>After creating subset i am counting those some subset which satisfy condition</li> <li>Condition is <code>xyz[0]</code> should not come in subset with <code>abc[0]</code> and <code>xyz[i]</code> should not come in subset <code>abc[i]</code>. Example 2 and 3 is coming subset then don't count that subset, same 1 and 4 is coming then don't count.</li> </ol> <p>Here is my nested for loop: </p> <pre><code>$n = 1299; $main_array = range(1,$n); $counter = 0; $count = sizeof($abc); // $abc and $xyz size will same always. $abc = [2,1]; $xyz = [3,4]; for ($i=0; $i &lt;$n; $i++) { for($j = $i;$j &lt; $n; $j++){ $interval_array = array(); for ($k = $i; $k &lt;= $j; $k++){ array_push($interval_array,$main_array[$k]); } $counter++; for ($l=0; $l &lt; $count ; $l++) { //if block here to additional condition using in_array() php function. which do $counter-- if(in_array($abc[$l], $interval_array) &amp;&amp; in_array($xyz[$l], $interval_array)){ $counter--; break; } } } } </code></pre> <p><code>$main_array</code> I have to create on the spot after receiving <code>$n</code> values. </p> <p>Following is cases: </p> <ol> <li>when running <code>$n = 4</code> its run in 4s </li> <li>when running <code>$n = 1200 or 1299 or more than 1000</code> its run in 60s-123s</li> </ol> <p>Expected execution timing is 9s. I reduce from 124s to 65s by removing function calling inside for loop but it's not coming to point.</p> <p>Expectation of code is if I have an array like:</p> <pre><code>$array = [1,2,3]; </code></pre> <p>Then subset need to generate: </p> <pre><code>[1],[1,2],[1,2,3],[2],[2,3],[3] </code></pre> <p>Any help in this? </p>
[]
[ { "body": "<p>I've seen this on SO, but only realised the biggest optimisation today.</p>\n\n<p>The first optimization is to not build the <code>$interval_array</code> array in each iteration. This code starts with the empty array and then in each loop just adds the next number in sequence to this array.</p>\n\n<pre><code>for ($i=0; $i &lt;$n; $i++) {\n // Reset array in outer loop\n $interval_array = array();\n for($j = $i;$j &lt; $n; $j++){\n // Add in new number to interval array as the key\n $interval_array[$main_array[$j]] = 0;\n</code></pre>\n\n<p>So the first time round it will add be <code>[1]</code>, then on the second loop it add the next number in and will be <code>[1,2]</code> etc. (although they are actually <code>[1=&gt;0]</code>, <code>[1=&gt;0, 2=&gt;0]</code> the principle is the same)</p>\n\n<p>The main difference is note that it adds the number as the key of the array and not the value. This allows the main optimization which is when you are checking if you want to exclude particular combinations in...</p>\n\n<pre><code> if(in_array($abc[$l], $interval_array) &amp;&amp; \n in_array($xyz[$l], $interval_array)){ \n</code></pre>\n\n<p>it will look through (up to) the entire array twice to check for the values.</p>\n\n<p>If instead you had the values as the key, you could use <code>isset()</code>...</p>\n\n<pre><code> if(isset($interval_array[$abc[$l]]) &amp;&amp;\n isset($interval_array[$xyz[$l]])) {\n</code></pre>\n\n<p>This is much more efficient at just checking a value exists.</p>\n\n<p>The last thing I've added is that I create an array with all of the numbers you are checking against in (use <code>array_flip()</code> to again make these numbers the keys)...</p>\n\n<pre><code>$interest = array_flip(array_merge($abc, $xyz));\n</code></pre>\n\n<p>This allows me to check if the number is even something I'm interested in before running the more detailed checks...</p>\n\n<pre><code> if ( isset($interest[$main_array[$j]] )) {\n</code></pre>\n\n<p>Put all of this together...</p>\n\n<pre><code>$n = 1299;\n$start = microtime(true);\n$main_array = range(1,$n);\n$counter = 0;\n$abc = [2,1];\n$xyz = [3,4];\n$count = sizeof($abc); // $abc and $xyz size will same always.\n\n// Create a combined array which lists all the numbers interested in\n$interest = array_flip(array_merge($abc, $xyz));\nfor ($i=0; $i &lt;$n; $i++) {\n // Reset array in outer loop\n $interval_array = array();\n for($j = $i;$j &lt; $n; $j++){\n // Add in new number to interval array as the key\n $interval_array[$main_array[$j]] = 0;\n $counter++;\n // Only check for exclusion if interested in the number\n if ( isset($interest[$main_array[$j]] )) {\n for ($l=0; $l &lt; $count ; $l++) {\n // if block here to additional condition using isset()\n if(isset($interval_array[$abc[$l]]) &amp;&amp;\n isset($interval_array[$xyz[$l]])) {\n $counter--;\n // Exit 2 levels of array as all further combinations will be excluded\n break 2;\n }\n }\n }\n }\n}\n\necho $counter.\"=\".(microtime(true)-$start);\n</code></pre>\n\n<p>On my laptop (i7-3632QM, 8GB) the results of running this for 1299 are</p>\n\n<p>original code...</p>\n\n<pre><code>841756=206.25858306885\n</code></pre>\n\n<p>modified code...</p>\n\n<pre><code>841756=0.34013700485229\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:54:05.507", "Id": "459718", "Score": "0", "body": "for 120000 number getting time out while executing. I am trying this case in hackerrank. @nigel-ren" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:42:51.410", "Id": "233785", "ParentId": "233755", "Score": "4" } } ]
{ "AcceptedAnswerId": "233785", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T06:58:21.943", "Id": "233755", "Score": "5", "Tags": [ "php" ], "Title": "its doing multiple nested for loop. How to reduce to 1?" }
233755
<p>I wrote a function which picks a two different random elements from a closed range of ints and returns them as a tuple.</p> <p>I would like to take a your feedback, if the solution is a "Clever", "Best practice" or "non of them"</p> <pre><code>func pickTwoRandomElementsFromRange(_ range: ClosedRange&lt;Int&gt;) -&gt; (Int, Int)? { guard range.count &gt;= 2 else { return nil } let firstElement = range.randomElement() var secondElement = range.randomElement() while firstElement == secondElement { secondElement = range.randomElement() } if let firstElement = firstElement, let secondElement = secondElement { return (firstElement, secondElement) } return nil } </code></pre>
[]
[ { "body": "<h3>Naming</h3>\n\n<p>Swift naming conventions are listed in the <a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"nofollow noreferrer\">API Design Guidelines</a>. With respect to “Omit needless words” and “Strive for Fluent Usage” I would suggest to call the function</p>\n\n<pre><code>func randomPair(from range: ClosedRange&lt;Int&gt;) -&gt; (Int, Int)?\n</code></pre>\n\n<h3>Simplify the code</h3>\n\n<p>Your method is fine, but can be simplified a bit. First, the return values from <code>randomElement()</code> can safely be forced-unwrapped because it is guaranteed at that point that the range is not empty. That makes the final optional binding obsolete:</p>\n\n<pre><code>func randomPair(from range: ClosedRange&lt;Int&gt;) -&gt; (Int, Int)? {\n guard range.count &gt;= 2 else { return nil }\n\n let firstElement = range.randomElement()!\n var secondElement = range.randomElement()!\n\n while firstElement == secondElement {\n secondElement = range.randomElement()!\n }\n return (firstElement, secondElement)\n}\n</code></pre>\n\n<p>Alternatively one can use a repeat-loop, so that the second element is assigned only at one place, that is a matter of personal preference:</p>\n\n<pre><code>func randomPair(from range: ClosedRange&lt;Int&gt;) -&gt; (Int, Int)? {\n guard range.count &gt;= 2 else { return nil }\n\n let firstElement = range.randomElement()!\n var secondElement: Int\n repeat {\n secondElement = range.randomElement()!\n } while firstElement == secondElement\n\n return (firstElement, secondElement)\n}\n</code></pre>\n\n<p>But actually the same can be achieved without a loop, if we pick the second element from a reduced range and adjust it if necessary:</p>\n\n<pre><code>func randomPair(from range: ClosedRange&lt;Int&gt;) -&gt; (Int, Int)? {\n guard range.count &gt;= 2 else { return nil }\n\n let firstElement = range.randomElement()!\n var secondElement = range.dropLast().randomElement()!\n if secondElement &gt;= firstElement {\n secondElement += 1\n }\n\n return (firstElement, secondElement)\n}\n</code></pre>\n\n<h3>Generalizations</h3>\n\n<p>Now we have a function to get a random pair from a closed range. But what about open ranges? What about ranges of other types? In fact it is not difficult to implement the same algorithm for arbitrary (random access) collections. The only difference is that we pick random indices first:</p>\n\n<pre><code>func randomPair&lt;C&gt;(from collection: C) -&gt; (C.Element, C.Element)? where C: RandomAccessCollection {\n guard collection.count &gt;= 2 else { return nil }\n\n let firstIndex = collection.indices.randomElement()!\n var secondIndex = collection.indices.dropLast().randomElement()!\n\n if secondIndex &gt;= firstIndex {\n collection.formIndex(after: &amp;secondIndex)\n }\n\n return (collection[firstIndex], collection[secondIndex])\n}\n</code></pre>\n\n<p>This covers closed ranges, open ranges, arrays etc:</p>\n\n<pre><code>randomPair(from: 0...10)\nrandomPair(from: 0..&lt;10)\nrandomPair(from: [\"a\", \"b\", \"c\", \"d\"])\n</code></pre>\n\n<p>Alternatively one can implement this as an extension method for <code>RandomAccessCollection</code> so that it closely resembles the existing <code>randomElement()</code> method:</p>\n\n<pre><code>extension RandomAccessCollection {\n func randomPair() -&gt; (Element, Element)? {\n guard count &gt;= 2 else { return nil }\n\n let firstIndex = indices.randomElement()!\n var secondIndex = indices.dropLast().randomElement()!\n if secondIndex &gt;= firstIndex {\n formIndex(after: &amp;secondIndex)\n }\n return (self[firstIndex], self[secondIndex])\n }\n}\n\n(0...10).randomPair()\n(0..&lt;10).randomPair()\n[\"a\", \"b\", \"c\", \"d\"].randomPair()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T10:55:03.963", "Id": "233774", "ParentId": "233767", "Score": "3" } }, { "body": "<p>I think Martin’s answer (+1) checks most of the boxes.</p>\n\n<p>First, that having been said, I wonder whether you’ve considered using this within non-countable ranges. For example, would you ever want to use it to generate a pair of floating point values (e.g. two angles whose values are between zero and 2π)? Is that part of what you might want to do? If so, a different pattern would be called for.</p>\n\n<p>Second, I might advise against tuple return type. As soon as you start using a function designed to return two values within a range, someone is going to want to then return three values from the range. A tuple is just too constraining. I’d be inclined to use a set or an array, instead. And even if you wanted to never return more than two values, I’d still ask whether a <code>struct</code> might make more sense, where the functional intent of these two values is more clear (e.g. ordered values, unordered? etc.).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:26:04.137", "Id": "234003", "ParentId": "233767", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T08:27:15.243", "Id": "233767", "Score": "3", "Tags": [ "random", "swift" ], "Title": "Pick a two different random elements from a given closed range" }
233767
<p>I am trying to implement a basic <a href="https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern" rel="nofollow noreferrer">circuit breaker design</a> for my internal API calls. I would appreciate some criticism and feedback about my code. I am also planning to implement an interface off of the class once I am happy with it. As mentioned this circuit breaker design will be used for internal gRPC calls between my microservices. This was written in .NET Core 3.0.</p> <p>I look forward to your feedback!</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Timers; namespace CircuitBreaker { public class CircuitBreaker { private Action _currentAction; private int _failureCount = 0; private readonly int _threshold = 0; private readonly System.Timers.Timer _timer; private CircuitState State { get; set; } public enum CircuitState { Closed, Open, HalfOpen } public CircuitBreaker(int threshold, int timeOut) { State = CircuitState.Closed; _threshold = threshold; _timer = new Timer(timeOut); _timer.Elapsed += TimerElapsed; } public void ExecuteAction(Action action) { _currentAction = action; try { action(); } catch (Exception ex) { if (ex.InnerException == null) throw; if (State == CircuitState.HalfOpen) Trip(); else if (_failureCount &lt; _threshold) { _failureCount++; Invoke(); } else if(_failureCount &gt;= _threshold) Trip(); } if(State == CircuitState.HalfOpen) Reset(); if (_failureCount &gt; 0) _failureCount = 0; } public void Trip() { if (State != CircuitState.Open) ChangeState(CircuitState.Open); _timer.Start(); } public void Reset() { ChangeState(CircuitState.Closed); _timer.Stop(); } private void ChangeState(CircuitState callerCircuitState) { State = callerCircuitState; } private void Invoke() { ExecuteAction(_currentAction); } private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e) { if (State == CircuitState.Open) { ChangeState(CircuitState.HalfOpen); _timer.Stop(); Invoke(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:40:25.327", "Id": "457099", "Score": "0", "body": "Have you checked out `Polly` on Nuget? if not, check it out, as it has already Circuit Breaker https://github.com/App-vNext/Polly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:14:06.343", "Id": "457197", "Score": "1", "body": "I had a look at Polly, but would really like my own implementation to be reviewed. :)" } ]
[ { "body": "<p>Welcome to Code Review. Not too bad but I would suggest a few things.</p>\n\n<p><code>_failureCount</code> is only used in <code>ExecuteAction</code> so I would only define it locally to <code>ExecuteAction</code> and renamed it simply <code>failureCount</code>.</p>\n\n<p>You may want to expose threshold publicly as a property since different instances could have differing thresholds. Suggest:</p>\n\n<pre><code>public int Threshold { get; }\n</code></pre>\n\n<p>Consider having a <code>ToString()</code> override.</p>\n\n<p><code>CircuitState</code> enum is okay where its at, but if it were me, I usually define it external to the class. </p>\n\n<p>You may consider having the <code>State</code> be gettable publicly. Suggest:</p>\n\n<pre><code>public CircuitState State { get; private set; }\n</code></pre>\n\n<p>I see no reason for <code>Invoke()</code>. Just call <code>ExecuteAction(_currentAction)</code> directly.</p>\n\n<p>The constructor has a <code>timeout</code> parameter. I would encourage clarity in the name with <code>millisecondsTimeout</code>.</p>\n\n<p>And finally, the biggest issue I see is that you really should get into the practice of use <code>{ }</code> with <code>if</code>. I know C++ was okay with this, and C# allows it, but here at CR we strongly discourage it because it could lead to nefarious hard-to-find bugs. There are lots of places where you would change this; here is but one example:</p>\n\n<pre><code>if (State != CircuitState.Open)\n{\n ChangeState(CircuitState.Open);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T18:47:24.033", "Id": "457293", "Score": "1", "body": "You can't just move _failureCount to be a local variable. It needs to be in the class scope so it can count the number of failures over a set of ExecuteAction calls, otherwise it will never be greater than 1 due to the recursive (through Invoke) nature of ExectueAction.\n\nYou could, instead, move it to be a parameter of ExecuteAction with a default value of 0 and then pass it in the call that replaces Invoke if you want it to not be in the class scope." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:03:13.583", "Id": "233881", "ParentId": "233768", "Score": "2" } } ]
{ "AcceptedAnswerId": "233881", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T08:51:30.923", "Id": "233768", "Score": "4", "Tags": [ "c#", "design-patterns" ], "Title": "Simple circuit breaker implementation" }
233768
<p>I wrote this method and I would like to refactor it so it is easier to understand and looks cleaner. However, I don't know how or where to start. If you could give it your best shot and explain your approach to how you did it, it would be very helpful to me. The function reduces the size of elements until the parent container reaches a certain height (in this case 25 or less).</p> <pre><code>function _AdjustHeightOwlDots() { let dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height(); if (!dotRowHeight || dotRowHeight === 25 || dotRowHeight === 0) { return; } this._waitFor(`#${get(this, 'elementId')} div.owl-dots &gt; button &gt; span`).then(() =&gt; { if (dotRowHeight &amp;&amp; dotRowHeight &gt; 25) { for (let index = 0; index &lt; 10; index += 1) { // default size of dot is 10x10px // first the margin because it looks better document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots &gt; button &gt; span`).forEach((el) =&gt; { const elCopy = el; const elStyle = elCopy.currentStyle || window.getComputedStyle(elCopy); if (parseFloat(elStyle.margin, 10) &gt; 1) { elCopy.style.margin = `${parseFloat(elStyle.margin, 10) - 1}px`; } }); dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height(); if (dotRowHeight &gt; 25) { document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots &gt; button &gt; span`).forEach((el) =&gt; { const elCopy = el; if (el.offsetHeight &gt; 1) { elCopy.style.height = `${el.offsetHeight - 1}px`; elCopy.style.width = `${el.offsetHeight}px`; } }); } const el = document.querySelector(`#${get(this, 'elementId')} div.owl-dots &gt; button &gt; span`); const elStyle = el.currentStyle || window.getComputedStyle(el); if (el.offsetHeight === 1 &amp;&amp; parseFloat(elStyle.margin, 10) &lt;= 1) { // cant get smaller break; } dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height(); if (dotRowHeight &lt;= 25) { break; } } } }) .catch((/* e */) =&gt; { // }); }, </code></pre> <p>Edit: Follow up: <a href="https://codereview.stackexchange.com/q/233848/214731">Find size for elements to fit in certain width</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:02:32.740", "Id": "457194", "Score": "1", "body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>It looks difficult to decypher indeed. Let's try it though. Some little bits which came to my mind at first glance:</p>\n\n<ul>\n<li>I'd recommend using 4 spaces of indentation</li>\n<li>maybe it's personnal taste but I would try not mixing jquery and vanilla js</li>\n<li><p>as I understood, <code>this</code> keyword always refers to the same object, doesn't it? in that case maybe you could declare the selectors at the top of the function?</p>\n\n<pre><code>const thisElementId = get(this, 'elementId');\nconst selectorOwlDots = `#${thisElementId} .owl-carousel .owl-dots`;\nconst selectorButtonSpans = `#${thisElementId} div.owl-dots &gt; button &gt; span`;\n</code></pre></li>\n<li><p>declarations of <code>const elCopy = el;</code> are useless, just refer to <code>el</code> and rename it to something more meaningful</p></li>\n<li><p>the handler of <code>_waitFor</code> should be declared as a function:</p>\n\n<pre><code>this._waitFor( selectorButtonSpans ).then( changeSizes ).catch( handleError );\n\nfunction changeSizes() {\n ...\n}\n\nfunction handleError( err ) {\n ...\n}\n</code></pre></li>\n<li><p>you can also simplify the initial exit condition a bit</p>\n\n<pre><code>let dotRowHeight = $(selectorOwlDots).height() || 25;\nif ( dotRowHeight &lt;= 25 ) {\n return;\n}\n</code></pre></li>\n<li>you have two <em>initial</em> checks on <code>dotRowHeight</code> - I think you could reduce them to just one ( one is the one I simplified, the other is inside the <code>_waitFor</code> handler )</li>\n</ul>\n\n<p>That should make the code a bit more readable <strong><em>BUT</em></strong> I think this code is doing the wrong thing altogether. The problem is - you are changing the size of elements in a loop until some condition is met. This is a bad practice - I've seen people ending up with infinite loops when doing such things. What I think you should do instead is:</p>\n\n<ul>\n<li>read all the sizes you need</li>\n<li>calculate sizes to apply to elements</li>\n<li>apply sizes</li>\n<li>if anything breaks - you do not have an infinite loop of elements jumping up and down on your page</li>\n</ul>\n\n<p>Always try to minimize the number of interactions between your script and the UI.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:15:10.417", "Id": "457031", "Score": "0", "body": "Hey thanks a lot for the answer. I will implement your feedback. In case of the `const elCopy = el`, I use a linter and it recommends to do it like this. The rule is called `no-param-reassign`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:35:16.197", "Id": "457201", "Score": "0", "body": "Follow up here : https://codereview.stackexchange.com/q/233848/214731" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:35:49.383", "Id": "233778", "ParentId": "233770", "Score": "2" } } ]
{ "AcceptedAnswerId": "233778", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T09:42:23.737", "Id": "233770", "Score": "4", "Tags": [ "javascript", "html", "dom" ], "Title": "Change size of elements until parent reaches certain height" }
233770
<p>I have been using this code for a while. I got it from a tutorial 5 years back. Now I'm wondering if it still is secure, or if it's time to find a new one? Maybe it has never been secure enough.</p> <p><strong>LOGIN</strong></p> <pre><code>&lt;?php //Connect to database require("include/config.php"); //Empty Variable $submitted_username = ''; //Check if something is posted if(!empty($_POST)){ //Check if user exists $query = "SELECT * FROM usrs WHERE usr_email = :usr_email"; $query_params = array(':usr_email' =&gt; $_POST['usr_email']); try{ $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex){ die("Failed to run query: " . $ex-&gt;getMessage()); } //Fetch result $row = $stmt-&gt;fetch(); //Reset var $login_ok = false; //If usr exists, check password if($row){ //Check if password matches $check_password = hash('sha256', $_POST['usr_password'] . $row['usr_salt']); for($round = 0; $round &lt; 65536; $round++){ $check_password = hash('sha256', $check_password . $row['usr_salt']); } if($check_password === $row['usr_password']){ $login_ok = true; } } //LOGIN OK if($login_ok){ //UNSET VARS unset($row['usr_salt']); unset($row['usr_password']); //LOG USR LOGIN DATA $dateTime = date('Y-m-d H:i:s'); //Create array $usr_data = array( ':usr_id' =&gt; $row['id'], ':usr_name' =&gt; $row['usr_fname']. " " . $row['usr_lname'], ':dateTime' =&gt; $dateTime, ':ip' =&gt; $_SERVER['REMOTE_ADDR'] ); //CREATE SESSION $_SESSION['usr'] = $row; //REDIRECT TO STARTPAGE header("Location: start.php"); } else{ echo "&lt;script type='text/javascript'&gt;alert('Fel uppgifter..');&lt;/script&gt;"; $submitted_username = htmlentities($_POST['usr_email'], ENT_QUOTES, 'UTF-8'); } } ?&gt; </code></pre> <p><strong>CONFIG</strong></p> <pre><code>$options = array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8'); try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); } catch(PDOException $ex){ die("Failed to connect to the database: " . $ex-&gt;getMessage());} $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //SET HEADER header('Content-Type: text/html; charset=utf-8'); //START SESSION if(!isset($_SESSION)){ session_start([ 'cookie_lifetime' =&gt; 86400, ]); } //SET TIMEZONE date_default_timezone_set('Europe/Stockholm'); ?&gt; </code></pre> <p><strong>CHECK IF LOGGED IN</strong></p> <pre><code>&lt;?php //CHECK IF USR IS LOGGED IN if(empty($_SESSION['user'])){ echo "&lt;script&gt;window.location = '/index.php'&lt;/script&gt;"; die("Redirecting to index.php"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:44:12.793", "Id": "457022", "Score": "0", "body": "Would you mind explaining why you call the `hash` function 65537 times?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:07:15.353", "Id": "457029", "Score": "1", "body": "@slepic The specific number has likely come from \\$2^{16} = 65536\\$. The purpose is to make the password hashing slower and therefore harder to brute force it. See Roland Illig's answer for an explanation why that might be a good, but not the best possible idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:43:30.703", "Id": "457035", "Score": "0", "body": "@AlexV Hmm i see... But wouldnt it be better to limit the rate of requests on the \"post login\" endpoint to léts say 1 request per second per IP? Regular users probably never do two login attempts within a second And So they dont need to notice the slowdown. While the 1 in million visitors that Is a hacker still can't Brute Force it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:45:41.257", "Id": "457036", "Score": "1", "body": "Anyway if I post a very long random password. The hash function May Crash your webserver. It Is wise to limit the length of the password before passing it to a hashing algorithm..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:08:13.780", "Id": "457069", "Score": "0", "body": "@AlexV What do you mean? Sure, if the attacker attacks db, then no rate limit on webserver side will have influence. But the same is true for doing 65k hashes in the php process.... What's your point?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:33:49.253", "Id": "457074", "Score": "0", "body": "@slepic This is not something one should discuss in the comments. Maybe have a look at [this site](https://crackstation.net/hashing-security.htm), the [specification of PBKDF2](https://tools.ietf.org/html/rfc2898#section-4.2), or [this extensive answer on Information Security SE](https://security.stackexchange.com/a/31846) to learn more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:46:12.790", "Id": "457078", "Score": "0", "body": "@AlexV The RFC you linked says: \"Obsoleted by: 8018\". Maybe you should update your library of citations. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:50:53.307", "Id": "457081", "Score": "0", "body": "@RolandIllig Thanks for the hint. I have skipped the header and went straight to the index looking for \"Iteration Count\" ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:56:21.010", "Id": "457083", "Score": "0", "body": "@AlexV I dont think we understand each other. Definitely I dont understand you. The links make no sense to me as a response to my comment.... Maybe if there Is some Tiny related bit, but im not gonna read entire spec for that, sry..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:29:52.137", "Id": "457125", "Score": "1", "body": "@slepic, to help you understand, the reason why those links from AlexV helps is, they cover PBKDF2 and other key-stretching algorithms, which are the current standard in password storage. Re-hashing the password 65536 times is a \"poor man's PBKDF2\" (this is a decent implementation: it puts the salt in the right place). The goal _isn't_ to slow down how long it takes to log in, though that is a side effect. **The goal is, if someone gets the key-stretched passwords, it will take them significantly longer to do an offline attack** and there is no possibility of a rainbow table." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T06:11:40.880", "Id": "457185", "Score": "0", "body": "@Ghedipunk problém here Is that AlexV deleted the only comment I was actually referring to (guess why). The rest makes no sense." } ]
[ { "body": "<p>There's a timing attack. To see whether a user has registered or not, I can try to login. If it fails fast, the user is not registered. If it takes time, the user is registered. To fix this information disclosure, calculate some dummy hash even if the user cannot be found in the database.</p>\n\n<p>The SQL part is fine.</p>\n\n<p>The <code>$submitted_username</code> calls <code>htmlentities</code> too early. The only correct time to call <code>htmlentities</code> is exactly at the point where you embed a text into an HTML snippet. That doesn't happen in your code, though. To fix this, rename the variable from <code>submitted_username</code> to <code>submitted_username_html</code>, to prevent it from being used in any other context. For example, code that reads <code>db_insert($submitted_username_html)</code> looks wrong enough to warrant a thorough code review.</p>\n\n<p>Your code could benefit from being split into a few well-named functions. After doing that, the main code might read like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$logged_in_user = log_in($_POST);\nif ($logged_in_user === FALSE) {\n // …\n} else {\n // …\n}\n</code></pre>\n\n<p>When you extract all the detailed code into a function, you can use early returns for all the error cases. And when you step through the code using a debugger, you can easily skip over all the details of the login process, if you are not interested in it.</p>\n\n<p>In the config part, you should prefix all variable names with <code>db_</code>, to avoid confusing the <code>username</code> with the <code>submitted_username</code>. Or group them into an object called <code>db_config</code>. Then you can access it as <code>$db_config['username']</code>. There, the identifier <code>username</code> is appropriate since it is qualified by the word <code>db_config</code>, which makes it unambiguous.</p>\n\n<p>The SHA-256 algorithm you use for hashing is <a href=\"https://dusted.codes/sha-256-is-not-a-secure-password-hashing-algorithm\" rel=\"noreferrer\">not secure enough anymore</a> since specialized hardware can compute it too fast, even with 65536 iterations. PHP has a built-in <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"noreferrer\">set of password hashing algorithms</a>. Just use that instead of iterating on your own. Migrating from your custom password hashing to the PHP default will cost a bit of time and work, but it's worth the effort. And since you are not the first to do that, there's already plenty of documentation on it. Probably. Hopefully.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:03:48.650", "Id": "457195", "Score": "0", "body": "Just wonder if the timing attack is significant enough to be detectable over network delays? I can see how it can be mitigated, but just like to understand the underlying need for these things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:24:30.477", "Id": "457208", "Score": "0", "body": "Yes, it is. Assuming that a single hashing operation takes a microsecond, 65536 of them takes 65 milliseconds. And even if it we're just a tenth of that time, that's still easily detectable. Maybe you have to perform several measurements to get confident, but still yes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:24:53.307", "Id": "233776", "ParentId": "233772", "Score": "6" } }, { "body": "<p>I can see two issues related to security (but both do not pose an immediate threat being rather a potential issue):</p>\n\n<ul>\n<li>the insufficient hashing algorithm. Nowadays computers are FAST. Means they could calculate billions <em>ordinary</em> hashes per second. And, in case your database gets compromised, it would be rather easy to get raw passwords from it. A secure password hash must be <em>slow</em>. And PHP has one, implemented in the password_hash function. So instead of your own hash you must use a built-in function</li>\n<li>I bet you never paid much attention to the error reporting part of your code, as your application seldom throws an error. Yet, when it happens, it's a complete disaster. An error message could contain a lot of sensitive information about your system. Not likely that it could be used directly to hack into your site, but it can help a hacker a lot. Besides, it just makes no sense to send an error message right away - a site user wouldn't make any sense of it. You chould forget about die() in your scripts. The best thing you can do is to leave the error message alone. </li>\n</ul>\n\n<p>The only other note I can make, there is a lot of rather useless conditions or the unused code. I rewrote your code based on the review above:</p>\n\n<pre><code>&lt;?php \n//Connect to database\nrequire(\"include/config.php\");\n\n//Check if something is posted\nif($_POST){ \n\n //Check if user exists\n $query = \"SELECT * FROM usrs WHERE usr_email = :usr_email\";\n $stmt = $db-&gt;prepare($query); \n $stmt-&gt;execute([':usr_email' =&gt; $_POST['usr_email']]); \n //Fetch result\n $row = $stmt-&gt;fetch(); \n\n //If usr exists, check password\n if($row &amp;&amp; password_verify($_POST['usr_password'], $row['usr_password'])\n {\n unset($row['usr_password']);\n\n //CREATE SESSION \n $_SESSION['usr'] = $row;\n\n //REDIRECT TO STARTPAGE\n header(\"Location: start.php\");\n exit();\n } else { \n echo \"&lt;script type='text/javascript'&gt;alert('Fel uppgifter..');&lt;/script&gt;\"; \n } \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:53:58.187", "Id": "457082", "Score": "0", "body": "The $_POST variable should be checked for presence of those keys before accessing them. Simple checking if post is empty or not is not enough (well, to be formally complete... Its probably enough for the script to work...)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:58:34.413", "Id": "457084", "Score": "0", "body": "@slepic that are you going to do in keys are undefined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:00:32.187", "Id": "457085", "Score": "0", "body": "Redirect to hp maybe or back to login page. Idk. Its not my project..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:04:36.583", "Id": "457088", "Score": "0", "body": "OH And not just presence of keys. But also correct data types of the values under those keys (strings in OP's case)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:07:34.483", "Id": "457092", "Score": "0", "body": "@slepic everything sent via HTTP POST is a string. And in case the key is not set, there will be a PHP error. Given your app do care for PHP errors, there will be a \"redirect\" to the error page. Looks enough to me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:17:32.693", "Id": "457094", "Score": "0", "body": "Nope. Everything sent via HTTP POST is a string or (nested) array of strings. And does it really look like this guy (OP) cares about a common error handler? I don't think so. Anyway I talk about general best practice, not the specific case in question. I remember one interview question where code was provided and find a security hole was the question. Everything looked fine as long as one assumed the post variable cannot be anything else than a string. The moment they sent array, the code logged in user with incorrect password or something like that... better safe than sorry..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:30:19.387", "Id": "457096", "Score": "0", "body": "And btw anytime your code reaches a common error handler. It doesnt mean it is ok. It means the code needs some fixing... The common error handler is just the last piece of chain, The ultimate place responsible for letting you know something went wrong. It is not the correct end of your program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:19:02.090", "Id": "457107", "Score": "0", "body": "Ok, it needs to be fixed. What kind of fix? Either propose a fix or don't push someone down the road you don't know yourself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T06:34:04.083", "Id": "457187", "Score": "0", "body": "I already proposed the fix. Check for the keys presence and the values being strings. Otherwise redirect or maybe do nothing like it is done when $_POST is empty. You dont check your array keys if you want. I just hope OP is reading this and that he can make sense to the desire that only string variables are passed to functions accepting strings (like password_verify does)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:26:55.603", "Id": "457189", "Score": "0", "body": "\"redirect or do nothing\" is anything but a fix. All right I can think of a reasonable action - a 400 HTTP status. But that's good only for a live site. A typo in the field name would make you bang your head on the wall trying to get why nothing works. So on a dev server you'd want the actual error message, in order to fix the error - that's what error messages are actually for. So to have such a distinction I'll have to throw an exception of a certain kind. Now I'd have to introduce exceptions, custom exceptions and an extended custom error handler, totaling in much more code than the OP has." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:42:15.913", "Id": "457191", "Score": "0", "body": "Hmm and so because of dev environment, you let it make errors on production? Learn to use debugger instead of banging your head against the wall. And you don't have to introduce any exceptions anyway. Can't you just accept that `if (!empty($_POST))` is just a lazy way of saying `if (isset($_POST['usr_password'], $_POST['usr_email']) && \\is_string($_POST['usr_password']) && \\is_string($_POST['usr_email']))`. Meaning \"Is there all the expected post data?\"instead of \"Is there any post data?\". Whatever is done in either branch is irrelevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:50:27.497", "Id": "457192", "Score": "0", "body": "It *is* relevant. Internet is full of such rants, \"you must do something but I don't care what exactly\". Unlike those I prefer my advise to be reasonable, plausible and complete. Now let's agree to disagree. While you prefer an open-ended suggestion which the OP is bound to implement by themselves, I prefer a complete solution that works. And no, debugger is useless if you wrote a code to intentionally silence the errors messages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:18:26.847", "Id": "457198", "Score": "0", "body": "I haven't silenced any errors. I have prevented them. By all means inform the client that `usr_password` and/or `usr_email` fields are required (and to be strings), whichever is missing (or has wrong value). Your solution is not reasonable, it is ignorant. It is not complete, it is erroneous. You made no difference between your backend code errors and client errors. You let the client error convert to php code errors, instead of detecting client errors and handling them reasonably and never letting any client error cause an error on the php language level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:24:48.833", "Id": "457199", "Score": "0", "body": "You silenced apossible undefined variable error with isset. It's a very common mistake, 99% php users are doing that. It's a mistake nevertheless. We already agreed that your \"reasonable\" \"what you put inside if() doesn't matter\" is no more reasonable than mine \"do not add an if() if you don't know what to put inside\". never letting any client error cause an error on the php language level is a thing but I cannot think of any solution that fits for this simple example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:41:52.040", "Id": "457202", "Score": "0", "body": "I added my own answer to show you that it can be easily communicated to the client. Anyway I don't see your problem with isset. It doesnt hide undefined variable. It is the place where you check for it and then do something or something else. Thats called the handling of the situation, not ignoring it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:42:19.273", "Id": "457203", "Score": "0", "body": "Thanks, I already upvoted it" } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:35:50.287", "Id": "233781", "ParentId": "233772", "Score": "3" } }, { "body": "<p>I object that all the required post fields should be checked for presence and expected type and report the missing fields to the client as opposed to letting it convert to php errors. </p>\n\n<p>As a simple solution we might report to client using js alert as it is done in another case already.</p>\n\n<pre><code>&lt;?php \n//Connect to database\nrequire(\"include/config.php\");\n\n//Check if something is posted\nif(isset($_POST['usr_password'], $_POST['usr_email'])\n &amp;&amp; \\is_string($_POST['usr_password'])\n &amp;&amp; \\is_string($_POST['usr_email'])\n &amp;&amp; \\strlen($_POST['usr_password']) &lt; 1000){ \n\n //Check if user exists\n $query = \"SELECT * FROM usrs WHERE usr_email = :usr_email\";\n $stmt = $db-&gt;prepare($query); \n $stmt-&gt;execute([':usr_email' =&gt; $_POST['usr_email']]); \n //Fetch result\n $row = $stmt-&gt;fetch(); \n\n //If usr exists, check password\n if($row &amp;&amp; password_verify($_POST['usr_password'], $row['usr_password'])\n {\n unset($row['usr_password']);\n\n //CREATE SESSION \n $_SESSION['usr'] = $row;\n\n //REDIRECT TO STARTPAGE\n header(\"Location: start.php\");\n exit();\n } else { \n echo \"&lt;script type='text/javascript'&gt;alert('Fel uppgifter..');&lt;/script&gt;\"; \n } \n} else if (!empty($_POST)) {\n echo \"&lt;script type='text/javascript'&gt;alert('usr_email and usr_password are required and password must be less than 1000 chars');&lt;/script&gt;\"; \n}\n</code></pre>\n\n<p>It could be a different message for each case, but for illustration I believe this should be enough.</p>\n\n<p>Further I have added check for password length to prevent hashing very long strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:32:03.507", "Id": "457277", "Score": "0", "body": "If you're going to check the plaintext password length, you might as well follow a standard while doing it ([NIST 800-63B sec 5.1.1.2](https://pages.nist.gov/800-63-3/sp800-63b.html#sec5) says the minimum maximum should be 64 characters), or at least set the limit to match the constraints of your key stretching algorithm -- With `password_hash()` set at current defaults, this is 72 characters. Despite your claims in comments to the question, even a naive implementation of PBKDF2 is not going to DOS a site when given an overly large plaintext; only the first round will be affected..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:35:42.453", "Id": "457278", "Score": "0", "body": "... The web server's other resources are going to pass failsafe thresholds (maximum upload size, maximum memory size, etc.) long before a key stretching algorithm can be used to make a CPU unresponsive for extended periods... and if you are attacking a key stretching algorithm using a DDOS attack, the site _should_ (see the NIST standards, linked above) have other rate limiting factors that will keep the authentication system from being leveraged to magnify a DDOS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:40:37.063", "Id": "457279", "Score": "0", "body": "(Relevant section in NIST 800-63B for rate limiting is section 5.2.2, by the way.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T20:31:11.397", "Id": "458491", "Score": "0", "body": "Shouldn’t variable cleansing be done somewhere other than program flow? I see the reason for this if scripting procedurally; but oh my I would hate to have to sift through these `if()` statements because they are in effect validating input in addition to directing program flow. You can’t look at that four line if() and immediately grasp everything it’s doing; and if you have to make a change to the variables being submitted, your program flow is invalidated. (I don’t have a better solution to propose; still struggling with it myself)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-22T06:50:11.070", "Id": "458539", "Score": "0", "body": "@TimMorton in real world you probably dont put all the conditions into one if. You have a separáte one for each of them And some specific message May be passed to client in each case. This all May be moved to a validátor class. I just tried to keep it simple And Focus on my main thought, that you should make sure that only expected things make it to places of your code where they wont crash your program or invoke any other unexpected behaviour." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T11:07:04.680", "Id": "466545", "Score": "0", "body": "Is this a good script?: https://phppot.com/php/secure-remember-me-for-login-using-php-session-and-cookies/" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:39:33.217", "Id": "233849", "ParentId": "233772", "Score": "1" } }, { "body": "<h3>Unused variable, single-use variable</h3>\n<p>In this section:</p>\n<blockquote>\n<pre><code>//LOG USR LOGIN DATA\n</code></pre>\n</blockquote>\n<pre><code>$dateTime = date('Y-m-d H:i:s');\n//Create array\n$usr_data = array(\n ':usr_id' =&gt; $row['id'],\n ':usr_name' =&gt; $row['usr_fname']. &quot; &quot; . $row['usr_lname'],\n ':dateTime' =&gt; $dateTime,\n ':ip' =&gt; $_SERVER['REMOTE_ADDR']\n);\n</code></pre>\n<p>The variable <code>$dateTime</code> is only used once, so there is not much need to store the value in a variable. The value can be used when creating <code>$usr_data</code> without storing it in the variable. Also, <code>$usr_data</code> doesn't appear to be used in this code.</p>\n<h3>Redirect with <code>header()</code> instead of Javascript</h3>\n<p>The last block of code uses a JavaScript redirect:</p>\n<blockquote>\n<pre><code>//CHECK IF USR IS LOGGED IN\n</code></pre>\n</blockquote>\n<pre><code>if(empty($_SESSION['user'])){\n echo &quot;&lt;script&gt;window.location = '/index.php'&lt;/script&gt;&quot;;\n die(&quot;Redirecting to index.php&quot;); \n}\n</code></pre>\n<p>It would be simpler just to redirect using <a href=\"https://www.php.net/manual/en/function.header.php\" rel=\"nofollow noreferrer\"><code>header('Location: /index.php')</code></a> as the other code does, unless the user was supposed to see the redirecting message for a set amount of time (e.g. 2 seconds), however it is possible the user might have JavaScript disabled and thus the redirect would not happen.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:03:58.140", "Id": "233991", "ParentId": "233772", "Score": "0" } } ]
{ "AcceptedAnswerId": "233776", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T10:49:15.300", "Id": "233772", "Score": "4", "Tags": [ "javascript", "php", "pdo" ], "Title": "Simple login script with sha256 hashing" }
233772
<p>I've created a library, <a href="https://github.com/TomHart/laravel-route-from-model" rel="nofollow noreferrer">TomHart/laravel-route-from-model</a>, and looking to get a review on it. As well as the usual code review, I'm also looking for feedback from a users point of view, if you were to use the library, is there anything extra you wish it did, anything different etc.</p> <p>The key class is:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace TomHart\Routing; use Illuminate\Database\Eloquent\Model; use Illuminate\Routing\Router; use Illuminate\Routing\UrlGenerator; use Symfony\Component\Routing\Exception\RouteNotFoundException; class RouteBuilder { /** * Get the router instance. * * @return Router */ private function getRouter(): Router { return app('router'); } /** * Get the UrlGenerator. * * @return UrlGenerator */ private function getUrlGenerator(): UrlGenerator { return app('url'); } /** * This allows a route to be dynamically built just from a Model instance. * Imagine a route called "test": * '/test/{name}/{id}' * Calling: * routeFromModel('test', Site::find(8)); * will successfully build the route, as "name" and "id" are both attributes on the Site model. * * Further more, once using routeFromModel, the route can be changed. Without changing the call: * routeFromModel('test', Site::find(8)); * You can change the route to be: * '/test/{name}/{id}/{parent-&gt;relationship-&gt;value}/{slug}/{otherParent-&gt;value}' * And the route will successfully change, as all the extra parts can be extracted from the Model. * Relationships can be called and/or chained with "-&gt;" (Imagine Model is a Order): * {customer-&gt;address-&gt;postcode} * Would get the postcode of the customer who owns the order. * * @param string $routeName The route you want to build * @param Model $model The model to pull the data from * @param mixed[] $data Data to build into the route when it doesn't exist on the model * * @return string The built URL. */ public function routeFromModel(string $routeName, Model $model, array $data = []) { $router = $this-&gt;getRouter(); $urlGen = $this-&gt;getUrlGenerator(); $route = $router-&gt;getRoutes()-&gt;getByName($routeName); if (!$route) { throw new RouteNotFoundException("Route $routeName not found"); } $params = $route-&gt;parameterNames(); foreach ($params as $name) { if (isset($data[$name])) { continue; } $root = $model; // Split the name on -&gt; so we can set URL parts from relationships. $exploded = collect(explode('-&gt;', $name)); // Remove the last one, this is the attribute we actually want to get. $last = $exploded-&gt;pop(); // Change the $root to be whatever relationship in necessary. foreach ($exploded as $part) { $root = $root-&gt;$part; } // Get the value. $data[$name] = $root-&gt;$last; } return rtrim($urlGen-&gt;route($routeName, $data), '?'); } } </code></pre>
[]
[ { "body": "<h1>Laravel coupling</h1>\n\n<p>What a shame that you decided to tie this to laravel. You can decouple the entire library from laravel framework and only provide a bundle for laravel.</p>\n\n<p><code>routeFromModel</code> accepts <code>Model</code>, but it can actually work for any object.</p>\n\n<pre><code>$route = $router-&gt;getRoutes()-&gt;getByName($routeName);\nif (!$route) {\n throw new RouteNotFoundException(\"Route $routeName not found\");\n}\n$params = $route-&gt;parameterNames();\n</code></pre>\n\n<p>This means you really don't need the router, you just need something that gives you an \"array of prameter names\" based on a \"name\".</p>\n\n<pre><code>return rtrim($urlGen-&gt;route($routeName, $data), '?');\n</code></pre>\n\n<p>Returning just the data here would make it more flexible.</p>\n\n<h1>IoC</h1>\n\n<p>You are pulling the RouteBuilder from DI container, why not have the container inject those deps. The way it is now, it could just be a static class with only static methods...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:44:21.907", "Id": "457023", "Score": "0", "body": "Ahh interesting! I never thought of it as anything but Laravel, but yeah that makes sense. I'll try and decouple it as an exercise, see what can be done, thanks :)!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:39:28.560", "Id": "457134", "Score": "0", "body": "I did as you recommended, pulled the core logic into it's own [repo](https://github.com/TomHart/array-from-object), and made use of that in the laravel specific library." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:29:28.913", "Id": "233777", "ParentId": "233775", "Score": "1" } } ]
{ "AcceptedAnswerId": "233777", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T11:12:39.883", "Id": "233775", "Score": "1", "Tags": [ "php", "library", "laravel" ], "Title": "Laravel build a route from a model" }
233775
<p>I am following <a href="https://www.cis.upenn.edu/~cis194/spring13/lectures.html" rel="nofollow noreferrer">CIS 194: Introduction to Haskell (Spring 2013)</a> online to teach myself Haskell. Following is my response to first exercise of <a href="https://www.cis.upenn.edu/~cis194/spring13/hw/03-rec-poly.pdf" rel="nofollow noreferrer">Homework 3</a>. Since I don't have anyone to show my code, I am posting here to get a little feedback. In which ways I could improve this, without getting too much into advanced topics of Haskell?</p> <pre><code>{- Exercise 1 Hopscotch Your first task is to write a function skips :: [a] -&gt; [[a]] The output of skips is a list of lists. The first list in the output should be the same as the input list. The second list in the output should contain every second element from the input list. . . and the nth list in the output should contain every nth element from the input list. For example: skips "ABCD" == ["ABCD", "BD", "C", "D"] skips "hello!" == ["hello!", "el!", "l!", "l", "o", "!"] skips [1] == [[1]] skips [True,False] == [[True,False], [False]] skips [] == [] Note that the output should be the same length as the input. -} takeEvery :: Integer -&gt; [a] -&gt; [a] takeEvery n xs = let zipped = zip [1..] xs in map (\x -&gt; snd x ) . filter (\(x,_) -&gt; x `mod` n == 0) $ zipped skips :: [a] -&gt; [[a]] skips x = map (\(x,y) -&gt; takeEvery x y) $ take (length x) (zip [1..] $ repeat x) </code></pre>
[]
[ { "body": "<p>Give fewer names, such as by inlining what's only used once.</p>\n\n<pre><code>takeEvery :: Integer -&gt; [a] -&gt; [a]\ntakeEvery n = map snd . filter (\\(x,_) -&gt; x `mod` n == 0) . zip [1..]\n\nskips :: [a] -&gt; [[a]]\nskips x = zipWith takeEvery [1..length x] $ repeat x\n-- or skips x = map (`takeEvery` x) [1..length x]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T13:32:29.813", "Id": "457046", "Score": "0", "body": "Second solution looks very elegant +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:45:24.090", "Id": "233783", "ParentId": "233780", "Score": "2" } } ]
{ "AcceptedAnswerId": "233783", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T12:04:16.443", "Id": "233780", "Score": "3", "Tags": [ "haskell" ], "Title": "CIS 194: Homework 3" }
233780
<p>I'd like to improve this operator code if I can. I don't know enough Raku to write idiomatically (or any other way for that matter), but suggestions along those lines would be good also.</p> <pre><code>use v6d; sub circumfix:&lt;α ω&gt;( ( $a, $b, $c ) ) { if ( $a.WHAT ~~ (Int) ) { so ( $a &gt;= $b &amp; $a &lt;= $c ); } else { my @b; for $a { @b.push( ( $_ &gt;= $b &amp; $_ &lt;= $c ).so ) }; so (False) ∈ @b; } }; if (α 5, 0, 10 ω) { "Pass".say; } else { "Fail".say; } if (α ( 5, 7, 11 ), 0, 10 ω) { "Pass".say; } else { "Fail".say; } </code></pre> <p>This does a range check on a variable or variables, between/bookended by <code>$b</code> (lower) and <code>$c</code> (upper). I wonder about using some sort of signature check paired with multi as a cleaner approach?</p>
[]
[ { "body": "<p>Regarding this code:</p>\n\n<pre><code>my @b;\nfor $a { @b.push( ( $_ &gt;= $b &amp; $_ &lt;= $c ).so ) };\nso (False) ∈ @b;\n</code></pre>\n\n<p>I'm sure that Raku has some form of the <a href=\"https://docs.raku.org/routine/any\" rel=\"nofollow noreferrer\"><code>any</code> operator</a> that would make this code a one-liner. Having a three-liner is definitely not idiomatic Raku. :)</p>\n\n<p>Did you intentionally use the <code>&amp;</code> operator instead of <code>&amp;&amp;</code>? I'd think that <code>&amp;&amp;</code> is more efficient, but that may only be my knowledge from other programming languages. I don't have any experience with Raku. From what I read about <a href=\"https://docs.raku.org/type/Junction\" rel=\"nofollow noreferrer\">junctions</a>, there should be an easier way to express this.</p>\n\n<p>Your code is hard to read since you use the meaningless variable names <code>a</code>, <code>b</code> and <code>c</code>. It would have been better to call two of them <code>min</code> and <code>max</code>. The third can then go by any other name.</p>\n\n<p>I would have expected the operator to be <code>α $min $x $max ω</code>, but that's not what you chose. In that case, I would have probably named the operator <code>in_range</code> and made it an infix operator in the form <code>$x in_range ($min .. $max)</code>, if that's possible at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:12:07.283", "Id": "457105", "Score": "0", "body": "Definitely food for thought! I looked at junction but foud the docs to opaque to understand. The variable name re-ordering hadn't occurred to me, but likewise a good idea. Not at all sure what you mean by the first comment? I'd still need to convert the value(s) to True and False and then check for first false effectively doing an evaluation on any of them…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:16:59.660", "Id": "457140", "Score": "1", "body": "I think that `$a >= $b && $b <= $c` is more efficient because if the first part evaluates to false, the second part `$b <= $c` does not have to be evaluated at all. The `&` operator, on the other hand, evaluates both sides, always. At least that's what most of the C-based languages do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T03:17:33.230", "Id": "457176", "Score": "0", "body": "Agreed and incorporated along with parameter order and naming as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:53:01.693", "Id": "457248", "Score": "0", "body": "Tentative one-liner: `for $i { return (False) unless ( $_ >= $min && $_ <= $max ). };`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:23:08.540", "Id": "457254", "Score": "0", "body": "Shorter tentative one-liner: `for $i { return unless ( $_ >= $min && $_ <= $max ).so };`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:44:15.783", "Id": "233798", "ParentId": "233794", "Score": "3" } }, { "body": "<p>There is quite a lot that you can do to make this idiomatic. I'll also go a bit overboard and show some ways to fully polish it (emphasis on way overboard for most projects).</p>\n\n<p>You mention potentially wanting to do <code>multi</code>. That's certainly possible here:</p>\n\n<pre><code>multi sub circumfix:&lt;α ω&gt;( ( $a where Positional, $b, $c ) ) { ... };\nmulti sub circumfix:&lt;α ω&gt;( ( $a where Int, $b, $c ) ) { ... };\n</code></pre>\n\n<p>But ultimately it's unnecessary. As the other answer points out, Raku has a junction types built in. They can be made by using the routines (or operators) <code>all</code> (<code>&amp;</code>), <code>any</code> (<code>|)</code>, <code>one</code> (<code>^</code>) and <code>none</code> — the routines are available as both subs and methods. In your case, we can take advantage of the fact that junctions can be made on a single item <em>or</em> a list, so that regardless whether <code>$a</code> is a list of <code>Int</code> or just a single <code>Int</code>, we can make it into a junction. That right there can reduce your code to:</p>\n\n<pre><code>sub circumfix:&lt;α ω&gt;( ( $a, $b, $c ) ) {\n so ( $a.any &gt;= $b &amp; $a.any &lt;= $c );\n};\n</code></pre>\n\n<p>Although we're going to remove it entirely, it should be noted that <code>&amp;</code> is a junction. This is slightly less efficient than using <code>&amp;&amp;</code> which just checks whether both sides are true and evaluates to a <code>Bool</code>. But we won't need to do that at all. Raku allows for chained operators, and the comparison operators are defined as such. This means that we can simplify things even further to:</p>\n\n<pre><code>sub circumfix:&lt;α ω&gt;( ( $a, $b, $c ) ) {\n so $b ≤ $a.any ≤ $c;\n};\n</code></pre>\n\n<p><code>so</code> has very loose operator precedence, so we don't need parentheses here. The final two considerations are purely stylistic, but help for code maintaince. The names <code>$a</code>, <code>$b</code>, and <code>$c</code> aren't descriptive. You'd definitely want to use something better. Also, it's fairly common, though not universal, to give extra emphasis to the fact that we're not mutating the values by using sigil-less variables. Personally, I also like to use whitespace to indicate the tighter grouping when using deconstruction, but YMMV. Lastly, semicolons aren't needed when they're the final expression of a block, or when a block terminates the line, so we can remove the semicolons.</p>\n\n<pre><code>sub circumfix:&lt;α ω&gt;( (\\val,\\min,\\max) ) {\n so min ≤ val.any ≤ max\n}\n</code></pre>\n\n<p>In this case, using min/max/val without sigils maybe is a bit riskier as they are also routines, but it seems to workout okay.</p>\n\n<p>If we want to go above and beyond for safety's sake, we can check the values in the signature. I'm assuming based on your original that you wanted to limit things to <code>Int</code> values so let's make it explicit, and specify our return value:</p>\n\n<pre><code>sub circumfix:&lt;α ω&gt;( (\\val where .all ~~ Int, \\min where Int, \\max where Int) --&gt; Bool) {\n so min ≤ val.any ≤ max\n}\n</code></pre>\n\n<p>At this point, the signature is getting a bit unruly, and so I like to spread it across multiple lines. Particularly if you have several deconstructed arguments, this lets identation also show structure a bit more clearly (but in this case, it's less necessary of course):</p>\n\n<pre><code>sub circumfix:&lt;α ω&gt; ( \n (\n \\val where .all ~~ Int, \n \\min where Int, \n \\max where Int\n )\n --&gt; Bool\n) {\n so min ≤ val.any ≤ max\n}\n</code></pre>\n\n<p>And don't forget that Raku's POD syntax means we can also add in documentation that could help users or automatically create documentation:</p>\n\n<pre><code>#| Determine if a value or values are between the given values (inclusive)\nsub circumfix:&lt;α ω&gt; ( \n (\n \\val where .all ~~ Int, #= The Int value or values to be tested\n \\min where Int, #= The lowest acceptable value\n \\max where Int #= The highest acceptable value\n )\n --&gt; Bool\n) {\n so min ≤ val.any ≤ max\n}\n</code></pre>\n\n<p>IDEs like Comma are already able to pull some of this information to make coding easier. Using it on signatures is really only supported for generating help feedback automatically on command line usage, but it's only a matter of time before such things will be integrated into IDEs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T19:20:14.293", "Id": "236504", "ParentId": "233794", "Score": "4" } } ]
{ "AcceptedAnswerId": "233798", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:49:51.003", "Id": "233794", "Score": "5", "Tags": [ "overloading", "raku" ], "Title": "Range check operator" }
233794
<p>I've wrote a little program that encrypts text by using the caesar-cipher. Also it contains a little GUI, created by using swing. Here's the full code:</p> <pre class="lang-java prettyprint-override"><code> import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import java.awt.Dimension; public class caesar { public static void main(String[] args) { String field, text; field = JOptionPane.showInputDialog("Please enter text:"); field = field.replaceAll("[^a-zA-Z]+", ""); field = field.toUpperCase(); int shift; String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:"); shift = Integer.parseInt(shift_String); String d = JOptionPane.showInputDialog("Encrypt (1) or decrypt (2):"); int decision = Integer.parseInt(d); String out; if(decision==1) { out = encrypt(field, shift); JTextArea msg = new JTextArea(out); msg.setLineWrap(true); msg.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(msg); scrollPane.setPreferredSize(new Dimension(300,300)); JOptionPane.showMessageDialog(null, scrollPane); } if(decision==2) { out = decrypt(field, shift); JTextArea msg = new JTextArea(out); msg.setLineWrap(true); msg.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(msg); scrollPane.setPreferredSize(new Dimension(300,300)); JOptionPane.showMessageDialog(null, scrollPane); } } //Encryption public static String encrypt(String text, int n) { int x = 0; int y = 0; String out = ""; //Empty string for result. while (x &lt; text.length()) { if (text.charAt(x) &gt; 64 &amp;&amp; text.charAt(x) &lt; 91) { if (text.charAt(x) + n &gt; 90) { y = 26; } out = out + (char) (text.charAt(x) + n - y); } else { out = out + text.charAt(x); } x++; y = 0; } return out; } //Decryption public static String decrypt(String text, int n) { int x = 0; int y = 0; String out = ""; //Empty string for result. while (x &lt; text.length()) { if (text.charAt(x) &gt; 64 &amp;&amp; text.charAt(x) &lt; 91) { if (text.charAt(x)-n &lt; 65) { y = 26; } out = out + (char) (text.charAt(x) - n + y); } else { out = out + text.charAt(x); } x++; y = 0; } return out; } } </code></pre> <p>My question now is: How to improve this code? </p> <p>I mean, it does what it is supposed to do, but it's not really great code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:44:52.163", "Id": "457136", "Score": "4", "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.](https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c/1765#1765) Feel free to post a follow-up question if the code has changed significantly enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:09:08.123", "Id": "457138", "Score": "0", "body": "Oh, I am sorry, thanks for changing it for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:18:21.897", "Id": "457141", "Score": "0", "body": "Thanks for the hint. You can find the follow up question at: https://codereview.stackexchange.com/questions/233811/follow-up-caesar-cipher-java" } ]
[ { "body": "<p>In my opinion, the main problem with your code is the duplication, here is my advices.</p>\n\n<p>1) Put the ui code out of the conditions.</p>\n\n<p>The only issue there, if the choice is invalid, you can either show a default string, or throw an exception.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> if (decision == 1) {\n out = encrypt(field, shift);\n } else if (decision == 2) {\n out = decrypt(field, shift);\n } else {\n out = \"Invalid choice!\";\n }\n\n JTextArea msg = new JTextArea(out);\n msg.setLineWrap(true);\n msg.setWrapStyleWord(true);\n JScrollPane scrollPane = new JScrollPane(msg);\n scrollPane.setPreferredSize(new Dimension(300, 300));\n JOptionPane.showMessageDialog(null, scrollPane);\n\n</code></pre>\n\n<p><em>Or</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> if (decision == 1) {\n out = encrypt(field, shift);\n } else if (decision == 2) {\n out = decrypt(field, shift);\n } else {\n throw new IllegalStateException(\"Invalid choice!\")\n }\n\n JTextArea msg = new JTextArea(out);\n msg.setLineWrap(true);\n msg.setWrapStyleWord(true);\n JScrollPane scrollPane = new JScrollPane(msg);\n scrollPane.setPreferredSize(new Dimension(300, 300));\n JOptionPane.showMessageDialog(null, scrollPane);\n\n</code></pre>\n\n<p>2) In the encrypt &amp; decrypt, to create the string containing the result, i suggest that you use <code>java.lang.StringBuilder</code> instead of concatening the String; you will gain some performance.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static String decrypt(String text, int n) {\n int x = 0;\n int y = 0;\n StringBuilder out = new StringBuilder(); //Empty string for result.\n while (x &lt; text.length()) {\n if (text.charAt(x) &gt; 64 &amp;&amp; text.charAt(x) &lt; 91) {\n if (text.charAt(x) - n &lt; 65) {\n y = 26;\n }\n out.append(text.charAt(x) - n + y);\n } else {\n out.append(text.charAt(x));\n }\n x++;\n y = 0;\n }\n return out.toString();\n }\n</code></pre>\n\n<p>3) In the encrypt &amp; decrypt, extract the <code>text.charAt(x)</code> in a variable, to remove the duplicates.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static String decrypt(String text, int n) {\n int x = 0;\n int y = 0;\n StringBuilder out = new StringBuilder(); //Empty string for result.\n while (x &lt; text.length()) {\n final char currentChar = text.charAt(x);\n\n if (currentChar &gt; 64 &amp;&amp; currentChar &lt; 91) {\n if (currentChar - n &lt; 65) {\n y = 26;\n }\n out.append(currentChar - n + y);\n } else {\n out.append(currentChar);\n }\n x++;\n y = 0;\n }\n return out.toString();\n }\n</code></pre>\n\n<p>4) The encrypt and decrypt methods are pretty similar, you can probably merge them if you want.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //Encryption\n public static String encrypt(String text, int n) {\n return operation(text, n, true);\n }\n\n //Decryption\n public static String decrypt(String text, int n) {\n return operation(text, n, false);\n }\n\n public static String operation(String text, int n, boolean isEncryption) {\n int x = 0;\n int y = 0;\n StringBuilder out = new StringBuilder(); //Empty string for result.\n while (x &lt; text.length()) {\n final char currentChar = text.charAt(x);\n\n if (currentChar &gt; 64 &amp;&amp; currentChar &lt; 91) {\n if (isEncryption ? (currentChar + n &gt; 90) : (currentChar - n &lt; 65)) {\n y = 26;\n }\n out.append(isEncryption ? (currentChar + n - y) : (currentChar - n + y));\n } else {\n out.append(currentChar);\n }\n x++;\n y = 0;\n }\n return out.toString();\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:04:18.150", "Id": "457115", "Score": "0", "body": "Thank you very much. That really helps. Do you have an idea how to merge the both methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:14:59.927", "Id": "457116", "Score": "0", "body": "Sorry, I forgot the code snippet in my answer, I updated it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:37:16.103", "Id": "457131", "Score": "0", "body": "Ah, thanks, that helped!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:54:51.537", "Id": "233805", "ParentId": "233803", "Score": "6" } }, { "body": "<p>something in addition:</p>\n\n<ul>\n<li>stick with code style guides. (e.g. I prefer: <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/javaguide.html</a> .Something got in my eye: <code>public class caesar</code>, <code>shift_String</code>)</li>\n<li>validate users input and notify if something is wrong (it would more user friendly and safe)</li>\n<li>assign 'magic' numbers to a constants (in encrypt/decrypt methods, will add more readability to the code)</li>\n<li>avoid code duplication (encrypt/decrypt and decision bodies)</li>\n</ul>\n\n<p>an example of how main could look like:</p>\n\n<pre><code>public static void main(String[] args) {\n String inputText = JOptionPane.showInputDialog(\"Please enter text:\");\n String normalizedInput = normalizeText(inputText);\n\n int shiftBy = getIntFromInput(\"Please enter shift to the right:\");\n int option = getIntFromInput(\"Encrypt (1) or decrypt (2):\"); // todo for options i'd recommend to use Enum\n\n // todo arg validation example\n String resultMessage;\n switch (option) {\n case 1:\n resultMessage = encrypt(normalizedInput, shiftBy);\n break;\n case 2:\n resultMessage = decrypt(normalizedInput, shiftBy);\n break;\n default:\n resultMessage = \"Unsupported option: \" + option;\n }\n showDialogWithMessage(resultMessage);\n}\n\nprivate static String normalizeText(String inputText) {\n return inputText\n .replaceAll(\"[^a-zA-Z]+\", \"\")\n .toUpperCase();\n}\n\nprivate static int getIntFromInput(String message) {\n return Integer.parseInt(JOptionPane.showInputDialog(message));\n}\n\nprivate static void showDialogWithMessage(String message) {\n JTextArea msg = new JTextArea(message);\n msg.setLineWrap(true);\n msg.setWrapStyleWord(true);\n JScrollPane scrollPane = new JScrollPane(msg);\n scrollPane.setPreferredSize(new Dimension(300, 300));\n JOptionPane.showMessageDialog(null, scrollPane);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:35:14.827", "Id": "233816", "ParentId": "233803", "Score": "4" } } ]
{ "AcceptedAnswerId": "233805", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T17:15:42.900", "Id": "233803", "Score": "8", "Tags": [ "java", "caesar-cipher" ], "Title": "Java implementation of the caesar-cipher" }
233803
<p>So, I have a project that has a lot of methods that look alike. In the below method as you can see it just fetches a bunch of rows from database and maps it to a model class. </p> <p>In this case <code>ParkingSlipDetails</code> class. There are several such methods in the project that do the exact same thing only with a different set of data and a different model class. There is no complicated business logic here. Just pure fetching data and mapping it to a model.</p> <p><strong>Something like this:</strong></p> <pre><code> public CustomReturn &lt; List &lt; ParkingSlipDetails &gt;&gt; GetAllParkingSlips(int offset, int fetch) { SqlConnection sqlConnection = null; try { List &lt; ParkingSlipDetails &gt; ParkingSlipDetailsList = new List &lt; ParkingSlipDetails &gt; (); sqlConnection = (SqlConnection) sqlHelper.CreateConnection(); //sqlHelper is a nugget and not in my control sqlConnection.Open(); SqlCommand cmd = new SqlCommand(Constants.GetAllParkingSlips, sqlConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("@CreatedBy", SqlDbType.NVarChar).Value = gepservice.GetUserContext().UserId; cmd.Parameters.Add("@OffsetRows", SqlDbType.NVarChar).Value = offset; cmd.Parameters.Add("@FetchRows", SqlDbType.NVarChar).Value = fetch; var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd); var sqlDr = (SqlDataReader) refCountdr.InnerReader; if (sqlDr != null) { while (sqlDr.Read()) { ParkingSlipDetails ParkingSlipDetails = new ParkingSlipDetails(); ParkingSlipDetails.Id = Convert.ToInt32(sqlDr[FileUploadConstants.Id]); ParkingSlipDetails.FileName = Convert.ToString(sqlDr[FileUploadConstants.FileName]); ParkingSlipDetails.FileUri = Convert.ToString(sqlDr[FileUploadConstants.FileURI]); ParkingSlipDetails.PONumber = Convert.ToString(sqlDr[FileUploadConstants.DocumentNumber]); ParkingSlipDetails.UploadDate = Convert.IsDBNull(sqlDr[FileUploadConstants.UploadDate]) ? DateTime.UtcNow: Convert.ToDateTime(sqlDr[FileUploadConstants.UploadDate]); ParkingSlipDetails.FileStatus = (Status)(Convert.ToInt16(sqlDr[FileUploadConstants.FileStatus])); ParkingSlipDetails.ReceiptNumber = Convert.ToString(sqlDr[FileUploadConstants.RecieptNumber].ToString()); ParkingSlipDetails.TotalRows = Convert.ToInt32(sqlDr[FileUploadConstants.TotalRows]); ParkingSlipDetails.CreatedBy = gepservice.GetUserContext().UserId; ParkingSlipDetailsList.Add(ParkingSlipDetails); } } return new CustomReturn &lt; List &lt; ParkingSlipDetails &gt;&gt; (ParkingSlipDetailsList); } catch(Exception ex) { LogError("ManageParkingSlipDataAccess", "GetAllParkingSlips", "Error", ex); return null } finally { if (sqlConnection != null) sqlConnection.Close(); } } </code></pre> <p><strong>I think there is a lot of scope for refactoring here since there is a lot of places where I would repeat :</strong></p> <pre><code>sqlConnection = (SqlConnection)sqlHelper.CreateConnection(); sqlConnection.Open(); </code></pre> <p><strong>and</strong> </p> <pre><code>var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd); var sqlDr = (SqlDataReader) refCountdr.InnerReader; if (sqlDr != null) { while (sqlDr.Read()) { } } </code></pre> <p><strong>And I also think the looping is repetitive for each method. Each such method has a loop that maps object to <code>cmd.Parameters</code></strong></p> <p>How do I separate the looping and mapping? Should I create an extension method on <code>ParkingSlipDetails</code> Class that takes <code>SqlDataReader</code> and returns an instance of <code>ParkingSlipDetails</code>? Even then I will be repeating reader creation and lopping in each model class.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:15:19.130", "Id": "457117", "Score": "0", "body": "Why is this not a valid question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:23:34.287", "Id": "457119", "Score": "0", "body": "Tell us more about what the code is exactly supposed to do please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:26:31.277", "Id": "457120", "Score": "0", "body": "Is this your real code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:27:30.233", "Id": "457121", "Score": "0", "body": "@πάνταῥεῖ Updated my question. Please take a look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:27:57.493", "Id": "457123", "Score": "0", "body": "@Heslacher Very close to real code. Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:29:17.247", "Id": "457124", "Score": "1", "body": "Because we only deal with real code. See the [help] to read why" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:30:25.250", "Id": "457126", "Score": "0", "body": "@Heslacher I just renamed the model class to hide name of my organization. Other than that, its identical to my real code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:34:21.657", "Id": "457128", "Score": "0", "body": "I honestly do not understand why this question has been downvoted. Isn't this site about code review and refactoring? It's my first day here so please bear with me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:35:43.307", "Id": "457130", "Score": "0", "body": "Then its ok. Hope you will get some good answers. Just be patient because it can take some time to write a review. Btw you shoul change your title to what your code is doing. Stating what you want to achieve just applies to too many questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:38:00.137", "Id": "457132", "Score": "0", "body": "@Heslacher edited the title. Though I am not sure if this one is better. I am open to suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:11:05.627", "Id": "457139", "Score": "0", "body": "Welcome to Code Review! I've edited the title to reflect what the code actually does rather than phrasing it as a question. Unlike many of our sister sites, that's what works best here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:40:59.837", "Id": "457156", "Score": "1", "body": "I think that the best refactoring would be using some simple ORM in your case. I would advise Dapper. You will have twice less code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:52:58.177", "Id": "457218", "Score": "0", "body": "@Disappointed I agree 100%. But my organization is totally against ORM. ¯\\_(ツ)_/¯" } ]
[ { "body": "<p>To quote Mark Seemann from the following article <a href=\"https://blog.ploeh.dk/2019/11/18/small-methods-are-easy-to-troubleshoot/\" rel=\"nofollow noreferrer\">Small methods are easy to troubleshoot</a></p>\n\n<blockquote>\n <p>Write small methods. How small? Small enough that any unhandled exception is easy to troubleshoot.</p>\n</blockquote>\n\n<p>Break the function up into smaller more manageable chunks that focus on a single concern as much as possible. </p>\n\n<p>Yes, the net effect of this is a lot of additional functions. They are however easier to read and maintain.</p>\n\n<p>Another benefit of the many small methods it that it would help identify areas that can be generalized into reusable services that help reduce repeated code, allowing it <em>(the code)</em> to be more DRY (Don't Repeat Yourself)</p>\n\n<p>Lets start with getting the connection</p>\n\n<pre><code>private SqlConnection createConnection() {\n var connection = (SqlConnection) sqlHelper.CreateConnection(); //sqlHelper is a nugget and not in my\n connection.Open();\n return connection;\n}\n</code></pre>\n\n<p>This can now be wrapped in a <code>using</code> block that will dispose of the connection once out of scope</p>\n\n<pre><code>using(SqlConnection connection = createConnection()) {\n\n //...\n}\n</code></pre>\n\n<p>While there is nothing wrong with creating the command manually, I personal prefer to let the connection do it rather than newing one. Again wrapping in a <code>using</code> block, and populating.</p>\n\n<pre><code>//...\n\nusing(SqlCommand command = connection.CreateCommand()) {\n command.CommandText = Constants.GetAllParkingSlips;\n command.CommandType = System.Data.CommandType.StoredProcedure;\n command.Parameters.Add(\"@CreatedBy\", SqlDbType.NVarChar).Value = gepservice.GetUserContext().UserId;\n command.Parameters.Add(\"@OffsetRows\", SqlDbType.NVarChar).Value = offset;\n command.Parameters.Add(\"@FetchRows\", SqlDbType.NVarChar).Value = fetch;\n\n //...\n}\n</code></pre>\n\n<p>That could have also been refactored into its own method, but in my opinion it would have ended up with too many arguments. </p>\n\n<p>This could be fixed with an aggregated value object.</p>\n\n<pre><code>public class ParkingSlipQuery {\n public int FetchRows { get; set; }\n public int OffsetRows { get; set; }\n public string CreatedBy { get; set; }\n}\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>private SqlCommand createCommand(SqlConnection connection, ParkingSlipQuery query) {\n SqlCommand command = connection.CreateCommand();\n command.CommandText = Constants.GetAllParkingSlips;\n command.CommandType = System.Data.CommandType.StoredProcedure;\n command.Parameters.Add(\"@CreatedBy\", SqlDbType.NVarChar).Value = query.CreatedBy;\n command.Parameters.Add(\"@OffsetRows\", SqlDbType.NVarChar).Value = query.OffsetRows;\n command.Parameters.Add(\"@FetchRows\", SqlDbType.NVarChar).Value = query.FetchRows;\n return command;\n}\n</code></pre>\n\n<p>and implemented</p>\n\n<pre><code>var query = new ParkingSlipQuery {\n CreatedBy = gepservice.GetUserContext().UserId,\n OffsetRows = offset,\n FetchRows = fetch\n};\nusing(SqlCommand command = createCommand(connection, query)) {\n //...\n}\n</code></pre>\n\n<p>The execution of the command and subsequent reader result however can be moved</p>\n\n<pre><code>private SqlDataReader executeReader(SqlCommand command) {\n var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd);\n return (SqlDataReader) refCountdr.InnerReader;\n}\n</code></pre>\n\n<p>As you have realized by now, you should know what is coming next about building the model to populate the collection.</p>\n\n<pre><code>private ParkingSlipDetails getDetails(SqlDataReader reader) {\n ParkingSlipDetails details = new ParkingSlipDetails();\n details.Id = Convert.ToInt32(reader[FileUploadConstants.Id]);\n details.FileName = Convert.ToString(reader[FileUploadConstants.FileName]);\n details.FileUri = Convert.ToString(reader[FileUploadConstants.FileURI]);\n details.PONumber = Convert.ToString(reader[FileUploadConstants.DocumentNumber]);\n details.UploadDate = Convert.IsDBNull(reader[FileUploadConstants.UploadDate]) ? DateTime.UtcNow: Convert.ToDateTime(reader[FileUploadConstants.UploadDate]);\n details.FileStatus = (Status)(Convert.ToInt16(reader[FileUploadConstants.FileStatus]));\n details.ReceiptNumber = Convert.ToString(reader[FileUploadConstants.RecieptNumber].ToString());\n details.TotalRows = Convert.ToInt32(reader[FileUploadConstants.TotalRows]);\n details.CreatedBy = gepservice.GetUserContext().UserId;\n\n return details;\n}\n\nprivate List&lt;ParkingSlipDetails&gt; getDetailsList(SqlDataReader reader, string userId) {\n List&lt;ParkingSlipDetails&gt; detailsList = new List&lt;ParkingSlipDetails&gt;();\n if (reader != null) {\n while (reader.Read()) {\n ParkingSlipDetails details = getDetails(reader);\n details.CreatedBy = userId;\n detailsList.Add(details);\n }\n }\n return detailsList;\n}\n</code></pre>\n\n<p>Finally, to avoid null reference errors, the method should try to avoid return <code>null</code>. An empty collection is safer to check than a null collection.</p>\n\n<p>This results in refactor looking like</p>\n\n<pre><code>public CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt; GetAllParkingSlips(int offset, int fetch) {\n List&lt;ParkingSlipDetails&gt; detailsList = new List&lt;ParkingSlipDetails&gt;();\n try {\n using(SqlConnection connection = createConnection()) {\n string userId = gepservice.GetUserContext().UserId;\n var query = new ParkingSlipQuery {\n CreatedBy = userId,\n OffsetRows = offset,\n FetchRows = fetch\n };\n using(SqlCommand command = createCommand(collection, query)) {\n using(SqlDataReader reader = executeReader(command)) {\n detailsList = getDetailsList(reader, userId);\n }\n }\n }\n } catch(Exception ex) {\n LogError(\"ManageParkingSlipDataAccess\", \"GetAllParkingSlips\", \"Error\", ex);\n detailsList = new List&lt;ParkingSlipDetails&gt;();\n }\n return new CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt;(detailsList);\n}\n</code></pre>\n\n<p>The <code>using</code> block will handle the closing and disposal of the connect and the other disposable members.</p>\n\n<p>If following explicit dependency principle, it could be refactored further down by delegating the argument values to the caller.</p>\n\n<pre><code>public CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt; GetAllParkingSlips(ParkingSlipQuery query) {\n List&lt;ParkingSlipDetails&gt; detailsList = new List&lt;ParkingSlipDetails&gt;();\n try {\n using(SqlConnection connection = createConnection()) { \n using(SqlCommand command = createCommand(collection, query)) {\n using(SqlDataReader reader = executeReader(command)) {\n detailsList = getDetailsList(reader, query.CreatedBy);\n }\n }\n }\n } catch(Exception ex) {\n LogError(\"ManageParkingSlipDataAccess\", \"GetAllParkingSlips\", \"Error\", ex);\n detailsList = new List&lt;ParkingSlipDetails&gt;();\n }\n return new CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt;(detailsList);\n}\n</code></pre>\n\n<p>with the following support methods</p>\n\n<pre><code>private SqlConnection createConnection() {\n var connection = (SqlConnection) sqlHelper.CreateConnection(); //sqlHelper is a nugget and not in my\n connection.Open();\n return connection;\n}\n\nprivate SqlCommand createCommand(SqlConnection connection, ParkingSlipQuery query) {\n SqlCommand command = connection.CreateCommand();\n command.CommandText = Constants.GetAllParkingSlips;\n command.CommandType = System.Data.CommandType.StoredProcedure;\n command.Parameters.Add(\"@CreatedBy\", SqlDbType.NVarChar).Value = query.CreatedBy;\n command.Parameters.Add(\"@OffsetRows\", SqlDbType.NVarChar).Value = query.OffsetRows;\n command.Parameters.Add(\"@FetchRows\", SqlDbType.NVarChar).Value = query.FetchRows;\n return command;\n}\n\nprivate SqlDataReader executeReader(SqlCommand command) {\n var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd);\n return (SqlDataReader) refCountdr.InnerReader;\n}\n\nprivate List&lt;ParkingSlipDetails&gt; getDetailsList(SqlDataReader reader, string userId) {\n List&lt;ParkingSlipDetails&gt; detailsList = new List&lt;ParkingSlipDetails&gt;();\n if (reader != null) {\n while (reader.Read()) {\n ParkingSlipDetails details = getDetails(reader);\n details.CreatedBy = userId;\n detailsList.Add(details);\n }\n }\n return detailsList;\n}\n\nprivate ParkingSlipDetails getDetails(SqlDataReader reader) {\n ParkingSlipDetails details = new ParkingSlipDetails();\n\n details.Id = Convert.ToInt32(reader[FileUploadConstants.Id]);\n details.FileName = Convert.ToString(reader[FileUploadConstants.FileName]);\n details.FileUri = Convert.ToString(reader[FileUploadConstants.FileURI]);\n details.PONumber = Convert.ToString(reader[FileUploadConstants.DocumentNumber]);\n details.UploadDate = Convert.IsDBNull(reader[FileUploadConstants.UploadDate]) ? DateTime.UtcNow: Convert.ToDateTime(reader[FileUploadConstants.UploadDate]);\n details.FileStatus = (Status)(Convert.ToInt16(reader[FileUploadConstants.FileStatus]));\n details.ReceiptNumber = Convert.ToString(reader[FileUploadConstants.RecieptNumber].ToString());\n details.TotalRows = Convert.ToInt32(reader[FileUploadConstants.TotalRows]);\n\n return details;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:00:23.700", "Id": "457222", "Score": "0", "body": "This looks better. I was wondering if ` while (reader.Read()) {` could be moved to `getDetails` method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:03:19.137", "Id": "457224", "Score": "0", "body": "It would require another method. I'll edit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:08:52.543", "Id": "457225", "Score": "0", "body": "If I understood this correctly. I will have to create a query class for every model class that needs to be filled from database. That will be a lot of classes right? Is it a general practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:10:48.983", "Id": "457226", "Score": "0", "body": "@SamuraiJack this was just an example specific to this function. A general or base type could be used as needed. That is why I mentioned some trepidation about going that route in my answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:42:35.480", "Id": "233819", "ParentId": "233806", "Score": "3" } }, { "body": "<p>I think this is where LINQ to Sql would come in handy. A simple method like this:</p>\n\n<pre><code>public List&lt;T&gt; getObjects&lt;T&gt;(IDbConnection connection,string tableName,params string[] columnNames)\n{\n string query = $@\"SELECT {String.Join(\",\", columnNames)} FROM {tableName}\";\n using (var dc = new DataContext(connection))\n {\n return dc.ExecuteQuery&lt;T&gt;(query).ToList();\n }\n\n}\n</code></pre>\n\n<p>would simplify things greatly. For instance using a simple class:</p>\n\n<pre><code>public class Company\n{\n public string CustomerID { get; set; }\n public string CompanyName { get; set; }\n public string Address { get; set; }\n}\n</code></pre>\n\n<p>you could get a list from the Northwinds database like this:</p>\n\n<pre><code>OleDbConnection conn = new OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWind.mdb\");\nvar companyList = getObjects&lt;Company&gt;(conn,\"Customers\",\"CustomerID\",\"CompanyName\",\"Address\");\n</code></pre>\n\n<p>This requires that your properties be properly typed and that the names match the column names you need(they can be case insensitive though). If conversions are needed you can leverage the <code>set</code>ter for that.</p>\n\n<p>Depending on what you need to do with the data, you might find it easier to create a <code>DataTable</code> instead of a <code>List</code>. This will automatically get the names and the types properly set, while still allowing you to iterate over the data and access any data item you need.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:56:01.407", "Id": "457219", "Score": "0", "body": "Cant ensure that property name will always be same as column name :/\nAlso, I am stuck with ADO.NET. I can use linq but not linq to sql." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:55:17.583", "Id": "457300", "Score": "0", "body": "Why can't you use `LINQToSQL`? It is [part of `ADO.net`](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/ado-net-and-linq-to-sql).I would suggest going the DataTable route. Each row is basically like an instance of a class, with the columns as individual properties. You can also use a DataGrid to display the data. This will extend to any set of data without setting up individual classes for each set." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T05:46:59.633", "Id": "233842", "ParentId": "233806", "Score": "3" } }, { "body": "<p>If LINQ-to-SQL and other ORMs are not possible to use in your organization. I would suggest to create a fixable solution that makes things easier for you for future updates. For instance, you could create a new class to handle SQL operations. This class will be a thin layer on top of the existing layer. Then, use it to design new methods that will reduce code redundancy, and recall them from the current ones. Then over the time, you'll see that this new handler will replace the current work, which will make your life easier. </p>\n\n<p><code>DataTable</code> also another approach, but it depends on the server IO and how much data it's going to be processed, which consumes more memory.</p>\n\n<p>for your question, you can do something like this : </p>\n\n<pre><code>public IEnumerable&lt;IDataRecord&gt; Reader(string query, SqlParameter[] parameters = null, CommandType commandType = CommandType.StoredProcedure)\n{\n var globalConnection = (SqlConnection) sqlHelper.CreateConnection(); //sqlHelper is a nugget and not in my control\n\n using(var connection = new SqlConnection(globalConnection.ConnectionString)) // just create this scope, in case you don't want to the global connection to be disposed.\n using (var cmd = new SqlCommand(query, connection) { CommandType = commandType })\n {\n // if there is parameters add them\n if (parameters != null)\n {\n for (int x = 0; x &lt; parameters.Length; x++)\n {\n cmd.Parameters.Add(parameters[x]);\n }\n }\n\n connection.Open();\n\n using (SqlDataReader reader = cmd.ExecuteReader())\n {\n if (reader.HasRows)\n {\n foreach (var row in reader)\n {\n yield return (DbDataRecord)(IDataRecord)row;\n }\n }\n }\n\n } // only this connection will be disposed\n}\n</code></pre>\n\n<p>and then use it like this : </p>\n\n<pre><code>public CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt; GetAllParkingSlips(int offset, int fetch)\n{\n try\n {\n var ParkingSlipDetailsList = new List&lt;ParkingSlipDetails&gt;();\n\n\n SqlParameter[] parameters = new SqlParameter[]\n {\n new SqlParameter{ ParameterName = \"@CreatedBy\", SqlDbType = SqlDbType.NVarChar, Value = gepservice.GetUserContext().UserId},\n new SqlParameter{ ParameterName = \"@OffsetRows\", SqlDbType = SqlDbType.NVarChar, Value = offset},\n new SqlParameter{ ParameterName = \"@FetchRows\", SqlDbType = SqlDbType.NVarChar, Value = fetch}\n };\n\n\n\n var reader = Reader(Constants.GetAllParkingSlips, parameters);\n\n foreach(var row in reader)\n {\n\n var pSlips = new ParkingSlipDetails();\n\n for(int x =0; x &lt; pSlips.GetType().GetProperties().Length; x++)\n {\n var column_name = row.GetName(x);\n var column_type = row.GetFieldType(x);\n var column_value = row.GetValue(x);\n\n // for columns that don't have identical naming with the model's properties \n if(column_name.Equals(FileUploadConstants.FileURI, StringComparison.OrdinalIgnoreCase))\n {\n column_name = \"FileUri\";\n }\n else if(column_name.Equals(FileUploadConstants.DocumentNumber, StringComparison.OrdinalIgnoreCase))\n {\n column_name = \"PONumber\";\n }\n else if(column_name.Equals(FileUploadConstants.RecieptNumber, StringComparison.OrdinalIgnoreCase))\n {\n column_name = \"ReceiptNumber\";\n }\n else if(column_name.Equals(FileUploadConstants.UploadDate, StringComparison.OrdinalIgnoreCase))\n {\n column_value = Convert.IsDBNull(sqlDr[FileUploadConstants.UploadDate]) ? DateTime.UtcNow: Convert.ToDateTime(sqlDr[FileUploadConstants.UploadDate]);\n } \n else if(column_name.Equals(\"CreatedBy\", StringComparison.OrdinalIgnoreCase))\n {\n column_value = gepservice.GetUserContext().UserId; \n }\n\n // Use refelection to set the values &amp; use Convert.ChangeType() to convert the data reader value to the property's datatype. \n pSlips.GetType().GetProperty(column_name).SetValue(pSlips, Convert.ChangeType(column_value, column_type), null); \n\n\n }\n\n\n ParkingSlipDetailsList.Add(pSlips);\n }\n\n\n return new CustomReturn&lt;List&lt;ParkingSlipDetails&gt;&gt; (ParkingSlipDetailsList);\n }\n catch(Exception ex)\n {\n LogError(\"ManageParkingSlipDataAccess\", \"GetAllParkingSlips\", \"Error\", ex);\n return null;\n }\n finally\n {\n // there is no connection in this scope, since it's already disposed within Reader() method.\n\n //if (sqlConnection != null)\n //sqlConnection.Close();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T04:39:04.470", "Id": "233898", "ParentId": "233806", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:04:19.693", "Id": "233806", "Score": "4", "Tags": [ "c#", ".net", "repository", "ado.net" ], "Title": "Method that fetches rows from database and maps it to a Model class with SqlDataReader" }
233806
<p>I'm currently learning python and created a simple music quiz. the rules of the game are as follows:</p> <p>The user has two chances to guess the name of the song If the user guesses the answer correctly the first time, they score 3 points. If the user guesses the answer correctly the second time they score 1 point.The game repeats.The game ends when a player guesses the song name incorrectly the second time.</p> <p>I developed the following but the I wasn't very pleased with the update leaderboard function as the indexing of the 2d list was confusing to code. is there an easier way to do the same thing? </p> <p>start_quiz returns two variables and is there a way to sort of 'unpack' what's returned? </p> <pre><code># 21:23 5th dec 2019 from Resources.songs import songs from Resources.users import users import random import pickle def main(): username = login() print('hello', username, 'welcome to the music quiz') guessed_wrong_twice = False result = None while not guessed_wrong_twice: result = start_quiz() guessed_wrong_twice = result[1] score = result[0] print('you scored', score) leaderboard = leaderboard_updating(username, int(result[0])) print('The leaderboard:\n', leaderboard) main() def login(): logged_in = False entered_username = None while not logged_in: entered_username = input("please enter username: ") if entered_username in users: entered_password = input('please enter password: ') if entered_password == users[entered_username]: logged_in = True else: print("password or username incorrect try again") logged_in = False return entered_username def start_quiz(): score = 0 guessed_wrong_twice = False song_chosen = choosing_song() print('artists name is', song_chosen[1]) first_letter = song_chosen[0][0] guess = input("the song begins with" + first_letter) if guess.lower == song_chosen[0]: score += 3 else: guess = input("the song begins with " + first_letter) if guess.lower == song_chosen[0]: score += 1 elif guess != song_chosen[0]: guessed_wrong_twice = True return score, guessed_wrong_twice def choosing_song(): song_chooser = random.randint(1, 3) song_artist = songs[song_chooser][1] song_name = songs[song_chooser][0] return song_name, song_artist # index 0 of each 'sub list' is the users name index 1 is their highest score def leaderboard_updating(username, score=0): leaderboard = pickle.load(open("leaderboard.pickle", "rb")) index_row_list = [leaderboard.index(row) for row in leaderboard if username in row] index_row = int(index_row_list[0]) if leaderboard[index_row][1] &lt; score: leaderboard[index_row][1] = score leaderboard = sorted(leaderboard, key=lambda x: x[1]) pickle.dump(leaderboard, open("leaderboard.pickle", "wb")) return leaderboard </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:24:05.623", "Id": "457142", "Score": "0", "body": "The code in the question doesn't work, as detailed in my CW disposable answer below." } ]
[ { "body": "<p><sup><strong>Note</strong>: Not an answer, an <a href=\"https://codereview.meta.stackexchange.com/a/6977\">extended comment</a>.</sup></p>\n\n<p>There's no way your code can work the way you intend it to.</p>\n\n<ol>\n<li><p>Your leader board doesn't work when the user isn't already in the leader board.</p>\n\n<p>The second line will <code>IndexError</code> in these cases:</p>\n\n<blockquote>\n<pre><code>index_row_list = [leaderboard.index(row) for row in leaderboard if username in row]\nindex_row = int(index_row_list[0])\n</code></pre>\n</blockquote></li>\n<li><p>You can never score more than 3 points on the leader board.</p>\n\n<blockquote>\n<pre><code>while not guessed_wrong_twice:\n result = start_quiz()\n guessed_wrong_twice = result[1]\nscore = result[0]\n</code></pre>\n</blockquote></li>\n<li><p>You can never enter a correct song.</p>\n\n<blockquote>\n<pre><code>if guess.lower == song_chosen[0]:\n</code></pre>\n</blockquote>\n\n<p>Looks innocent enough, but it's never true. Unless <code>song_chosen[0]</code> is <code>str.lower</code>. In which case it's always true.</p>\n\n<pre><code>&gt;&gt;&gt; 'abc'.lower == 'abc'\nFalse\n</code></pre></li>\n</ol>\n\n<p>Now 1 &amp; 2 are pretty minor, so if your code only contained them I'd just answer. But 3 means it's impossible for your code to work.</p>\n\n<p>Given that <code>start_quiz</code> was the last function I reviewed I have a half written review for you. Please fix the above problems for it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:32:12.950", "Id": "457144", "Score": "0", "body": "with number 3 would `guess == songchosen[0]: ` be correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:33:05.177", "Id": "457145", "Score": "0", "body": "@Krishna Yes and no. It would work, but obviously `\"Foo\" != \"foo\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:38:46.610", "Id": "457146", "Score": "0", "body": "so I would have to convert `song chosen[0]` to lowercase as well as `guess` before the if statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:40:12.830", "Id": "457147", "Score": "1", "body": "@Krishna Before / in doesn't really matter. But yes if you wish to be pedantic about 'correctness' you would have to do that. Which is why I say the answer is yes and no." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:23:43.573", "Id": "233813", "ParentId": "233809", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:27:39.760", "Id": "233809", "Score": "0", "Tags": [ "python", "python-3.x", "quiz", "music" ], "Title": "simple python music quiz" }
233809
<p>As the title suggests, I'm a complete beginner in Haskell. I've just made my way through the "Input and Output" section of <em>Learn You A Haskell For Greater Good</em> and I thought it would be good to try my hand at a simple project like a "Guess The Word" game in Haskell.</p> <p>The idea behind the game is to guess all the letters of a randomly selected word. If you guess all the letters, you win.</p> <p>Without further ado, the complete program is below. I'm looking for feedback regarding program structure (particularly in separating I/O from pure functions), any inefficiencies I could look out for, any potential bugs, and any Haskell idioms and general best practices I could incorporate.</p> <pre><code>import Data.Char import Data.Maybe import System.Random data Difficulty = Easy | Medium | Hard deriving (Read, Show, Eq) createDifficulty :: String -&gt; Maybe Difficulty createDifficulty s = lookup s [ ("e", Easy), ("m", Medium), ("h", Hard), ("", Easy) ] isDifficulty :: String -&gt; Bool isDifficulty = isJust . createDifficulty randomNumber :: Int -&gt; Int -&gt; IO (Int) randomNumber begin end = do gen &lt;- getStdGen return $ head $ randomRs (begin, end) gen -- Please don't provide review about these tables. They're just meant to be demonstrative of the general idea I'm going for. fetchWords :: Difficulty -&gt; [String] fetchWords Easy = ["foo", "bar"] fetchWords Medium = ["abc", "def"] fetchWords Hard = ["foobar", "whoami"] generateSecret :: Difficulty -&gt; IO (String) generateSecret difficulty = do let table = fetchWords difficulty num &lt;- randomNumber 0 (length table) return (table !! num) replaceChar :: Int -&gt; String -&gt; Char -&gt; String replaceChar n s c = pre ++ [c] ++ tail post where (pre, post) = splitAt n s compareSecret :: String -&gt; String -&gt; Int -&gt; Char -&gt; String compareSecret secret guess pos c = if secret !! pos == c then replaceChar pos guess c else guess isInt :: String -&gt; Bool isInt = all isDigit isChar :: String -&gt; Bool isChar [] = False isChar (c:cs) = isAlpha c &amp;&amp; null cs promptUntil :: (String -&gt; Bool) -&gt; String -&gt; (String -&gt; IO ()) -&gt; IO (String) promptUntil pred prompt failure = do putStr (prompt ++ "\n&gt; ") input &lt;- getLine if pred input then return input else do failure input promptUntil pred prompt failure loop :: String -&gt; String -&gt; IO () loop secret guess = do putStrLn guess input1 &lt;- promptUntil isInt "Enter position:" (\input -&gt; putStrLn $ input ++ " is not a number.") input2 &lt;- promptUntil isChar "Enter character:" (\input -&gt; putStrLn $ input ++ " is not a character.") let pos = read input1 :: Int let c = head input2 let result = compareSecret secret guess pos c if result /= secret then loop secret result else return () main = do putStrLn "\n Welcome to Guess The Word!\n" difficultyString &lt;- promptUntil isDifficulty "Enter difficulty level [e/m/h] or leave empty for easy difficulty: " (\input -&gt; putStrLn $ input ++ " is not a valid difficulty.") let difficulty = fromMaybe (Easy) (createDifficulty difficultyString) putStrLn $ show difficulty ++ " difficulty selected." secret &lt;- generateSecret difficulty loop secret $ replicate (length secret) '-' putStrLn secret putStrLn "You win!" </code></pre>
[]
[ { "body": "<p>Overall the code looks really nice. I like the separation with a separate <code>Difficulty</code> type instead of doing the parsing directly in <code>fetchWords</code>.</p>\n<h2>Bugs</h2>\n<p>I have found three bugs:</p>\n<h3>Crash on invalid user input</h3>\n<p>If a user enters a number that is larger than the number of characters in the string, the program will crash. This is because you use the partial<sup>1</sup> function <code>(!!)</code> without verifying its precondition that for <code>xs !! i</code>, <code>i &gt;= 0</code> and <code>i &lt; length xs</code>. This could also be solved if you used a <a href=\"https://hackage.haskell.org/package/safe-0.3.18/docs/Safe.html#v:atMay\" rel=\"nofollow noreferrer\">non-partial version</a> of the function which returns a <code>Maybe</code> value so you can display a better error to the user and ask them to retry.</p>\n<h3>Random crash every 3:rd execution</h3>\n<p>There is also an off-by-one error in <code>generateSecret</code>, since <code>randomRs</code> generates an inclusive range and <code>length xs</code> is not a valid index for <code>xs</code>. This will cause the program to crash randomly on average once every <code>length (fetchWords difficulty) + 1</code> times you play.</p>\n<h3>Only one random number</h3>\n<p>Speaking of randomness: the <code>randomNumber</code> function calls <a href=\"https://hackage.haskell.org/package/random-1.1/docs/System-Random.html#v:getStdGen\" rel=\"nofollow noreferrer\"><code>getStdGen</code></a>, which\ndoesn't update the RNG state, it just fetches it. This means that all random numbers will be the same. To make it update the state, you can either use <a href=\"https://hackage.haskell.org/package/random-1.1/docs/System-Random.html#v:randomRIO\" rel=\"nofollow noreferrer\"><code>randomRIO</code></a> which will update the global RNG state automatically, or use <a href=\"https://hackage.haskell.org/package/random-1.1/docs/System-Random.html#v:newStdGen\" rel=\"nofollow noreferrer\"><code>newStdGen</code></a> which will split the RNG state to allow you to generate random numbers from pure code. In this code you don't notice it though, since you only generate a single number.</p>\n<p>The <code>randomNumber</code> function can be fixed by simplifying it to</p>\n<pre class=\"lang-hs prettyprint-override\"><code>randomNumber :: Int -&gt; Int -&gt; IO Int\nrandomNumber begin end = randomRIO (begin, end)\n</code></pre>\n<h2>Idiomatic code</h2>\n<h3>Partial functions</h3>\n<p>You use partial functions in a couple of places. Many of them can be avoided by using the principle <a href=\"https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/\" rel=\"nofollow noreferrer\">&quot;Parse, don't validate&quot;</a>. In this case, all the &quot;<code>isX</code>&quot; functions can be replaced with <code>getX</code> functions that try to parse the data and <code>Maybe</code> returns a parsed value. The <code>createDifficulty</code> function is already such a function. This guarantees that the validation actually matches the code that uses it.</p>\n<p>Here's an example of how it could be done. I have only included the relevant functions here. The index is validated, but there is no easy way to tell which list it is a valid index for unless you use some advanced trickery<sup>2</sup>.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>import Text.Read (readMaybe)\n\nnewtype ValidIndex = ValidIndex Int\n\ncreateDifficulty :: String -&gt; Maybe Difficulty\ncreateDifficulty s = lookup s [\n (&quot;e&quot;, Easy),\n (&quot;m&quot;, Medium),\n (&quot;h&quot;, Hard),\n (&quot;&quot;, Easy)\n ]\n\ngetInt :: String -&gt; Maybe Int\ngetInt = readMaybe\n\nisValidIndex :: [a] -&gt; Int -&gt; Bool\nisValidIndex list idx = idx &gt;= 0 &amp;&amp; idx &lt; length list\n\ngetValidIndex :: [a] -&gt; String -&gt; Maybe ValidIndex\ngetValidIndex list str = do\n idx &lt;- getInt\n guard $ isValidIndex list idx\n return $ ValidIndex idx\n\ngetChar :: String -&gt; Maybe Char\ngetChar [c] | isAlpha c = Just c\ngetChar [] = Nothing\n\npromptUntil :: (String -&gt; Maybe a) -&gt; String -&gt; String -&gt; IO a\npromptUntil parser prompt failureMessage = do\n putStr (prompt ++ &quot;\\n&gt; &quot;)\n input &lt;- getLine\n case parser input of\n Just result -&gt; return result\n Nothing -&gt; do\n putStrLn $ input ++ failureMessage\n promptUntil parser prompt failure\n\nloop :: String -&gt; String -&gt; IO ()\nloop secret guess = do\n\n putStrLn guess\n\n pos &lt;- promptUntil (getValidIndex secret) &quot;Enter position:&quot; &quot; is not a valid index.&quot;\n c &lt;- promptUntil getChar &quot;Enter character:&quot; &quot; is not a character.&quot;\n\n let result = compareSecret secret guess pos c\n if result /= secret then\n loop secret result\n else\n return ()\n\nmain = do\n putStrLn &quot;\\n Welcome to Guess The Word!\\n&quot;\n\n difficulty &lt;- promptUntil createDifficulty &quot;Enter difficulty level [e/m/h] or leave empty for easy difficulty: &quot;\n &quot; is not a valid difficulty.&quot;\n\n putStrLn $ show difficulty ++ &quot; difficulty selected.&quot;\n\n secret &lt;- generateSecret difficulty\n\n loop secret $ replicate (length secret) '-'\n\n putStrLn secret\n putStrLn &quot;You win!&quot;\n\n-- These functions are still partial, but we have checked their preconditions.\nreplaceChar :: ValidIndex -&gt; String -&gt; Char -&gt; String\nreplaceChar (ValidIndex n) s c = pre ++ [c] ++ tail post\n where (pre, post) = splitAt n s\n\ncompareSecret :: String -&gt; String -&gt; ValidIndex -&gt; Char -&gt; String\ncompareSecret secret guess pos@(ValidIndex i) c =\n if secret !! i == c then\n replaceChar pos guess c\n else\n guess\n</code></pre>\n<h3>Separating business logic from generic combinators</h3>\n<p>There are some cases where you can separate the code that is specific\nto your application from generic code that could be used anywhere.</p>\n<p>For example, the <code>generateSecret</code> function can be split into a <code>pickOne</code> function:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>pickOne :: [a] -&gt; IO a\npickOne [] = error &quot;pickOne: Empty list&quot;\npickOne xs = do\n num &lt;- randomRIO (0, length xs - 1)\n return $ xs !! num\n\ngenerateSecret :: Difficulty -&gt; IO (String)\ngenerateSecret = pickOne . fetchWords\n\n</code></pre>\n<p>As you can see, the function is still partial, but since the word list is hard coded, we can probably assume that there is at least one word for each difficulty.</p>\n<h3>Explicit import lists</h3>\n<p>The recommended way of handling imports is to either use a qualified import like this:</p>\n<pre><code>import qualified Data.Char as Char\n\nexample = Char.isDigit '2'\n</code></pre>\n<p>or use an explicit import list like this</p>\n<pre><code>import Data.Char (isDigit)\n\nexample = isDigit '2'\n</code></pre>\n<p>This makes it easier for readers to see where functions come from.</p>\n<h2>Performance</h2>\n<p>Since all strings and lists are really short in this example, performance will not really be an issue. However, if the strings or lists were a lot longer, there are a few things to note. All functions that work with an index into a list are <code>O(n)</code> (instead of the <code>O(1)</code> they would be if we were working with a mutable array).</p>\n<p>Haskell has support for <a href=\"https://hackage.haskell.org/package/vector-0.12.0.2/docs/Data-Vector-Mutable.html\" rel=\"nofollow noreferrer\">mutable vectors</a>, but then you lose the purity that is so nice about Haskell. If you want to keep purity, you can use a <a href=\"https://hackage.haskell.org/package/containers-0.6.2.1/docs/Data-Map.html\" rel=\"nofollow noreferrer\"><code>Data.Map</code></a>, which has <code>O(n*log n)</code> complexity, but at the cost of a <code>O(n*log n)</code> memory cost. You could also use <code>Data.Text</code>, which still has <code>O(n)</code> complexity, but has a much more compact representation and is faster overall.</p>\n<p>Anyways, as I said, this is not really relevant for this program since <code>n</code> (the length of the lists/strings) is really small and will probably never be large.</p>\n<hr />\n<ol>\n<li>A partial function is any function that can crash</li>\n<li>For example using <a href=\"https://ucsd-progsys.github.io/liquidhaskell-blog/\" rel=\"nofollow noreferrer\">Liquid Haskell</a> or by using some fancy type-level trickery where the length of the list is in its type</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:43:11.767", "Id": "457883", "Score": "0", "body": "Thank you so much for this in depth review; this was exactly what I was looking for! I'm going to read and study some of the material in the links you've provided -- especially the \"parse don't validate\" link." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:23:52.290", "Id": "233825", "ParentId": "233810", "Score": "3" } } ]
{ "AcceptedAnswerId": "233825", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T18:32:33.883", "Id": "233810", "Score": "5", "Tags": [ "haskell" ], "Title": "Beginner's Implementation of Guess The Word" }
233810
<p>I now processed the suggestions you can find <a href="https://codereview.stackexchange.com/questions/233803/java-implementation-of-the-caesar-cipher?noredirect=1#comment457136_233803">here</a>. I've deleted some duplications and corrected some other minor mistakes.</p> <p>Here's the code:</p> <pre class="lang-java prettyprint-override"><code> import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import java.awt.Dimension; public class caesar { public static void main(String[] args) { String field, text; field = JOptionPane.showInputDialog("Please enter text:"); field = field.replaceAll("[^a-zA-Z]+", ""); field = field.toUpperCase(); int shift; String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:"); shift = Integer.parseInt(shift_String); String d = JOptionPane.showInputDialog("Encrypt (1) or decrypt (2):"); int decision = Integer.parseInt(d); String out = ""; if(decision == 1) { boolean test = true; out = operation(field, shift, test); } else if(decision == 2) { boolean test = false; out = operation(field, shift, test); } else if(decision != 1 &amp;&amp; decision != 2) { out = "Invalid choice!"; } JTextArea msg = new JTextArea(out); msg.setLineWrap(true); msg.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(msg); scrollPane.setPreferredSize(new Dimension(300,300)); JOptionPane.showMessageDialog(null, scrollPane); } //Encryption public static String operation(String text, int n, boolean test) { int x = 0; int y = 0; int z = 1; if(!test) { z = -1; } StringBuilder out = new StringBuilder(); //Empty string for result. while (x &lt; text.length()) { final char currentChar = text.charAt(x); if (currentChar &gt; 64 &amp;&amp; currentChar &lt; 91) { if (currentChar + n &gt; 90) { y = 26; } out.append((char)(currentChar + (n*z) - (y*z))); } else { out.append(currentChar); } x++; y = 0; } return out.toString(); } } </code></pre> <p>Are there anymore suggestions to improve the code?</p>
[]
[ { "body": "<h2>Naming</h2>\n\n<p>Give your class a more meaningful name, that begins with a capital letter -as all classes should in Java-, e.g. <code>CaesarCipher</code>.</p>\n\n<p>The <code>operation()</code> method's name doesn't tell us anything about what it actually does. If it weren't for the <code>//Encryption</code> comment, there would be no indication that this class does something even related to encryption/decryption.</p>\n\n<p>The variable <code>shift_String</code> uses snake_case while all the other ones use camelCase; pick one and stick to it (and since this is Java, I'd recommend camelCase as it is the accepted standard). </p>\n\n<p>More generally, try using names that actually describe what the variable/method/class represents or does (what is <code>d</code>? what about <code>test</code>?). You could for example declare one String, say <code>userInput</code>, and reuse it whenever you want to store the user's input, that way you don't need to declare two variables where one has the same name as the other appended with <code>String</code> everytime.</p>\n\n<p>Also, shortened names like <code>out</code> or <code>d</code> don't really have any benefit over slightly longer, clearer ones, other than making the very first time you type the name a tiny bit shorter. Giving them more meaningful names will make the code easier to read later, and you shouldn't be worried about typing a few more characters each time; let your IDE do its job!</p>\n\n<h2><code>final</code> keyword</h2>\n\n<p>This recommendation is more based on my own opinions, but I think it's justified here since you've made use of it yourself.</p>\n\n<p>Mark all method arguments as <code>final</code>; this will prevent you from accidentally reassigning them (which you really shouldn't do anyways).</p>\n\n<p>Make all your instance &amp; local variables <code>final</code> when appropriate; this simply indicates that once they are assigned a value, that value should not and will not change in the future. It may seem like you're simply adding more unnecessary fluff to an already very verbose language, but I personally think it helps writing clearer code as well as making it easier to debug. </p>\n\n<p>If you want to read more about Java's use of the <code>final</code> keyword, I recommend this answer : <a href=\"https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java\">https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java</a>.</p>\n\n<h2>Code Optimization &amp; Reusability</h2>\n\n<p>The <code>text</code> variable is declared but never used.</p>\n\n<p>Redundant checks in <code>main()</code> :</p>\n\n<pre><code>if(decision == 1) {\n boolean test = true;\n out = operation(field, shift, test);\n}\nelse if(decision == 2) {\n boolean test = false;\n out = operation(field, shift, test);\n}\nelse if(decision != 1 &amp;&amp; decision != 2) {\n out = \"Invalid choice!\";\n}\n</code></pre>\n\n<p>Your last <code>else if</code> could be replaced by a simple <code>else</code>, since the only way you'll get there is if <code>decision</code> is neither equal to 1 nor to 2. In this same snippet, you could also get rid of the <code>test</code> variable altogether, or maybe declare it before those conditionals and place the <code>out = operation(field, shift, test);</code> at the end. Additionnaly, what does <code>test</code> mean? What is it testing for?</p>\n\n<p>You may want to implement another cipher later; if that's the case, then creating a simple <code>Cipher</code> interface might be worthwhile. You should also make <code>caesar</code> a separate class from <code>main()</code> and decouple it from all the user interface stuff, that way you can use it whenever you want, wherever you want. The interface might look something like this :</p>\n\n<pre><code>public interface Cipher {\n public String encrypt(final String text);\n\n public String decrypt(final String cipherText);\n}\n</code></pre>\n\n<p>Use an <code>enum</code> to represent the two choices given to the user. This might be overkill for this case as you'd only have two possible values (<code>ENCRYPT</code> and <code>DECRYPT</code>, for example), but it would certainly make the code even more readable.</p>\n\n<p>There's more that could be said, about user input validation, or using magic numbers in <code>operation()</code>, and more, but I'll leave it to other users.</p>\n\n<h2>Exception Handling &amp; User Input</h2>\n\n<p>What happens if the user decides to type \"oiuahffduht$$$\" when you ask them for the shift value? Your program breaks and the user has to manually start it again! <em>Always assume the worst from the user</em>. Ideally, you'd want to handle such cases in your code via exception handling. If you're not familiar with the concept, you can take a look at this link which covers all the basics of EH in Java : <a href=\"https://stackify.com/specify-handle-exceptions-java/\" rel=\"nofollow noreferrer\">https://stackify.com/specify-handle-exceptions-java/</a>.</p>\n\n<p>So what can we do here? If you look at the Java documentation for <code>Integer.parseInt()</code> -or check its signature from your favorite IDE, you'll see that it can throw a <code>NumberFormatException</code>, so let's catch it. Keeping the same logic and syntax as your original code, it might look something like this :</p>\n\n<pre><code>String shift_String = JOptionPane.showInputDialog(\"Please enter shift to the right:\");\n\ntry {\n shift = Integer.parseInt(shift_String);\n}\ncatch (NumberFormatException e) {\n // Handle the exception\n}\n</code></pre>\n\n<p>There's lots of different ways you can handle the exception; you could simply show the user the contents of the exception or the stack trace, you could end the program... Personally, I think the best way to handle this case would be to show a new dialog that says something along the lines of <em>\"Error, you must enter a number\"</em>, then show that previous input box and asks for the same thing again. That way the user won't have to close/reopen the program and they'll know what went wrong.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>In your <code>operation()</code> method, you use a bunch of \"magic numbers\" (64, 90, 26...). So what's a magic number? It's basically a hardcoded value (not necessarily a 'number') that is present in your code without any explanation of why it's there or what it means.</p>\n\n<p>Imagine if someone who's not familiar with ASCII were to read your code (though maybe they shouldn't be writing code in the first place). They might think you're using some crazy voodo magic to turn numbers into letters, who knows? So give these numbers names! </p>\n\n<p>Or, maybe try a different approach entirely, where you would store all the possible characters in a String, then make use of the wonderful modulo operator like so : </p>\n\n<pre><code>private static final String ALPHABET = \"abcdefghijklmnopqrstuvwxyz\";\n\npublic static String encrypt(final String text, final int shift) {\n final String lowerCaseText = text.toLowerCase();\n String cipherText = \"\";\n\n for (int i = 0; i &lt; lowerCaseText.length(); i++) {\n final int charPosition = ALPHABET.indexOf(lowerCaseText.charAt(i));\n final int newCharPosition = (shift + charPosition) % 26;\n final char newChar = ALPHABET.charAt(newCharPosition);\n\n cipherText += newChar;\n }\n\n return cipherText;\n }\n</code></pre>\n\n<p>Now you don't even have to deal with those annoying numbers anymore!</p>\n\n<p>By the way, I haven't tested this, and I don't claim it to be more efficient or readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:14:45.937", "Id": "457206", "Score": "0", "body": "Could you maybe clarify what your ideas are in the last paragraph?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:23:02.980", "Id": "457269", "Score": "1", "body": "@chrysaetos99 I've just edited my answer to add more details about the two topics I mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:44:51.787", "Id": "457284", "Score": "1", "body": "That clarifies it for me. Thank you very much." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:41:36.977", "Id": "233818", "ParentId": "233811", "Score": "5" } } ]
{ "AcceptedAnswerId": "233818", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:15:21.383", "Id": "233811", "Score": "3", "Tags": [ "java", "caesar-cipher" ], "Title": "follow-up - caesar-cipher - java" }
233811
<p>I am trying to solve a codewar challenge (<a href="https://www.codewars.com/kata/reverse-polish-notation-calculator/train/python" rel="noreferrer">link</a>):</p> <blockquote> <p>Your job is to create a calculator which evaluates expressions in Reverse Polish notation.</p> <p>For example expression <code>5 1 2 + 4 * + 3 -</code> (which is equivalent to <code>5 + ((1 + 2) * 4) - 3</code> in normal notation) should evaluate to 14.</p> <p>For your convenience, the input is formatted such that a space is provided between every token.</p> <p>Empty expression should evaluate to 0.</p> <p>Valid operations are <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>.</p> <p>You may assume that there won't be exceptional situations (like stack underflow or division by zero).</p> </blockquote> <p>I have 2 problems, the first is that the code looks awful and I don't know how to improve it tbh, I also want this code to be able to compute multiple digit numbers and i feel like i need to start from scratch if I want to add that.</p> <p>Note : This is my first time writing a question so if there's anything wrong with it please tell me and I'll change it.</p> <pre><code>def calc(expr): stack = [] for i in range(len(expr)): if expr[i].isdigit(): stack.append(expr[i]) if expr[i-1] == '.': stack.pop() if expr[i] == '.': stack.pop() stack.append(expr[i-1] + expr[i] + expr[i+1]) if expr[i] == '+': stack.append(float(stack[-2]) + float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '-': stack.append(float(stack[-2]) - float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '*': stack.append(float(stack[-2]) * float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '/': stack.append(float(stack[-2]) / float(stack[-1])) for i in range(2): del stack[-2] if stack == []: return 0 else: return float(stack[0]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:54:17.740", "Id": "457162", "Score": "4", "body": "Welcome to Code Review. Your question is fine: there's a link to the relevant task, a short introduction, a piece of code that is ready to be pasted into an IDE, that's almost all one can ask. As a bonus, you could add a few example expressions next time, that's a thing that is often missing in questions. Other than that, well done. :)" } ]
[ { "body": "<p>The challenge says the items in the expression are already separated by spaces. So, use <code>str.split()</code> to parse the expression.</p>\n\n<p>The if statements are mutually exclusive, so use <code>if</code> ... <code>elif</code> ... </p>\n\n<p>When evaluating an RPN expression, one generally pop's the arg off the stack, applies an operation, and then pushes the result.</p>\n\n<pre><code>def calc(expr):\n stack = []\n\n for token in expr.split():\n\n if token[0].isdigit():\n if '.' in token:\n stack.append(float(token))\n else:\n stack.append(int(token))\n\n elif token == '+':\n right_arg = stack.pop()\n left_arg = stack.pop()\n\n stack.append(left_arg + right_arg)\n\n elif token == '-':\n right_arg = stack.pop()\n left_arg = stack.pop()\n\n stack.append(left_arg - right_arg)\n\n ... same for '*' and '/' ...\n\n if stack == []:\n return 0\n else:\n return stack.pop()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:11:34.387", "Id": "233815", "ParentId": "233814", "Score": "5" } }, { "body": "<p>The initial approach is full of redundant <code>if</code> conditions for capturing float numbers and duplicated set of statements (<code>stack.append</code>, <code>for</code> loop, <code>del</code> ...) for all 4 arithmetic operations.</p>\n\n<p>The whole idea is achievable with a single traversal facilitated by <a href=\"https://docs.python.org/3/library/operator.html\" rel=\"noreferrer\"><code>operator</code></a> (provides convenient equivalents of mathematical operations) and <a href=\"https://docs.python.org/3/library/ast.html?highlight=ast#ast.literal_eval\" rel=\"noreferrer\"><code>ast.literal_eval</code></a> feature (to evaluate both <code>int</code> and <code>float</code> types):</p>\n\n<pre><code>import operator\nfrom ast import literal_eval\n\nmath_operators = {'+': operator.add, '-': operator.sub, \n '*': operator.mul, '/': operator.truediv}\n\n\ndef calc(expr):\n tokens = expr.split()\n res = []\n for t in tokens:\n if t in math_operators:\n res[-2:] = [math_operators[t](res[-2], res[-1])]\n else:\n res.append(literal_eval(t))\n\n return res[0] if res else 0\n</code></pre>\n\n<hr>\n\n<p>Test cases:</p>\n\n<pre><code>exp = '5 1 2 + 4 * + 3 -'\nprint(calc(exp)) # 14\n\nexp = '5.5 10.6 -'\nprint(calc(exp)) # -5.1\n\nexp = ''\nprint(calc(exp)) # 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:48:46.377", "Id": "457216", "Score": "0", "body": "Just to make sure I understand both solutions, you could have `stack.append(math_operators[t](stack.pop(), stack.pop()) if t in math_operators else literal_eval(t))` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:03:11.900", "Id": "457223", "Score": "0", "body": "Ah, no, the order is wrong for subtraction and division then" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:10:48.560", "Id": "457233", "Score": "0", "body": "`stack.append(math_operators[t](stack.pop(-2), stack.pop()) if t in math_operators else literal_eval(t))` learned something new :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:58:44.607", "Id": "233823", "ParentId": "233814", "Score": "11" } }, { "body": "<p><em>(Update: as stated in the comment, the codewars task explicitly demands that an empty expression is to return 0. This makes my following remarks invalid for this particular task. In all other situations they still apply.)</em></p>\n\n<p>There's one thing that you should do in the last lines of your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if stack == []:\n return 0\n else:\n return float(stack[0])\n</code></pre>\n\n<p>The task explicitly says that you may assume the input is error-free and that your program may do whatever it wants on erroneous input. You currently ignore the error and silently return a wrong result (<code>0</code>). You should not do that.</p>\n\n<p>Instead you should just write:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> return stack[0]\n</code></pre>\n\n<p>The stack is assumed to only contain floats. Therefore it is not necessary to convert the float to a float again. If you want to check it explicitly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> assert stack[0] == float(stack[0])\n return stack[0]\n</code></pre>\n\n<p>Trying to return <em>the result</em> from an empty stack should result in an exception. That way you know for sure that there was something wrong. That's much better than continuing the calculation with a wrong result.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T05:44:29.443", "Id": "457183", "Score": "3", "body": "The problem explicitly states an empty expression should return 0, so the OP is not ignoring an error and silently returning a wrong result. It is in fact doing the right thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T22:43:34.053", "Id": "457309", "Score": "0", "body": "Several hours later I noticed that the task says _an empty expression_ instead of _an empty result_. Therefore it might still be better to handle the special case of an empty expression at the top (together with a helpful comment), and to throw an exception at the bottom." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:00:04.473", "Id": "233824", "ParentId": "233814", "Score": "2" } }, { "body": "<p>A simple solution using <a href=\"https://docs.python.org/3/library/functions.html#eval\" rel=\"nofollow noreferrer\">eval()</a>.</p>\n\n<p>As others have done, use the result as a stack and pop the numbers if the token is an operator. The <code>eval</code> converts from string to numbers, handling floats as well.</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>def calc(expr):\n res = []\n for t in expr.split():\n if t in '+-*/':\n t = str(res.pop(-2)) + t + str(res.pop())\n res.append(eval(t))\n return res[0] if res else 0\n\nexp = '5 1 2 + 4 * + 3 -'\nprint(calc(exp)) # 14\n</code></pre>\n\n<p><a href=\"https://tio.run/##VU9NC8IwDL33VwQ8tHVs7suL4C8ZO4ytw8LoQhtFf31NdSq@QyDvJe8l@KDL6poYJzPDOCyjMnf0@iSA4U2AM3T9q5lXDwTWQRooAi6W1DaXYOe3KrN8f5A/PoHYJZBX7FfgiiqvtYaM6eyP1vq7lagB0bhJmduwKNo0b@jqXZK7sk@Z6USzBAOlEHwYB8kjVFCzdQt7rg3kUqC3jtTnPQ4H2EHVxvgE\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:57:23.020", "Id": "233864", "ParentId": "233814", "Score": "1" } } ]
{ "AcceptedAnswerId": "233823", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T19:43:55.367", "Id": "233814", "Score": "12", "Tags": [ "python", "python-3.x", "programming-challenge", "calculator" ], "Title": "Reverse Polish Notation (RPN) Calculator" }
233814
<p>I programmed a Neural Network in python. Feedback every kind is appreciated. I tried to use some vectorization but it turned out to become quite a mess. Because you can't append to numpy arrays I sometimes needed to use numpy arrays in list and sometime I could use just numpy arrays.</p> <p>Is there a way to make It look cleaner?</p> <pre class="lang-py prettyprint-override"><code>""" Author: Lupos Purpose: Practising coding NN Date: 17.11.2019 Description: test NN """ from typing import List, Dict # used for typehints import numpy as np # used for forward pass, weight init, ect. # logging import logging # used to log errors and info's in a file from datetime import date # used to get a name for the log file import os # used for creating a folder import pandas as pd import seaborn as sns import matplotlib.pyplot as plt class NeuralNetwork: def __init__(self, x: List[float], y: List[float], nn_architecture: List[Dict], alpha: float, seed: int, custom_weights_data: List = [], custom_weights: bool = False) -&gt; None: """ Constructor of the class Neural Network. Parameters ---------- x : List[float] Input data on which the Neural Network should get trained on y : List[float] Target/corresponding values for the input data. nn_architecture : List[Dict] Describes the architecture of the Neural Network. alpha : float The learning rate. seed: int Seed for numpy.For creating random values. For creating reproducible results. Returns ------- None """ self.level_of_debugging = logging.INFO self.logger: object = self.init_logging(self.level_of_debugging) # initializing of logging # Dimension checks self.check_input_output_dimension(x, y, nn_architecture) np.random.seed(seed) # set seed for reproducibility self.input: List = self.add_bias(x) self.y: List = y self.output_model: float = np.zeros(y.shape) self.alpha: float = alpha self.layer_cache = {} # later used for derivatives self.error_term_cache = [] self.nn_architecture: List[Dict] = nn_architecture self.weights: List = [] # np.array([]) self.init_weights(custom_weights, custom_weights_data) # initializing of weights self.w_d: List = [] # gardient in perspective to the weight self.curr_layer: List = [] self.weight_change_cache: List = [] self.logger.info("__init__ executed") # for visuliozing self.x_train_loss_history = [] self.y_train_loss_history = [] self.bias_weight_tmp = [] def add_bias(self, x) -&gt; List[float]: x = np.array([np.insert(x, 0, 1)]) return x def check_input_output_dimension(self, x, y, nn_architecture): """ Gets executed from the constructor "__init__". Is used to check if the dimensions of input and output values correspond to the neuron size in the input and output layer. Parameters ---------- x Input values y Output Values nn_architecture : List[Dict] Architecture of the neural network. Returns ------- None """ assert len(x[0]) == nn_architecture[0][ "layer_size"], 'Check the number of input Neurons and "X".' # check if the first element in "x" has the right shape assert len(y[0]) == nn_architecture[-1][ "layer_size"], 'Check the number of output Neurons and "Y".' # check if the first element in "y" has the right shape assert len(x) == len(y), "Check that X and Y have the corresponding values." # mean square root def loss(self, y: List[float], y_hat: List[float]) -&gt; List[float]: return np.sum(1 / 2 * (y - y_hat) ** 2) def loss_derivative(self, y: List[float], y_hat: List[float]) -&gt; List[float]: y = np.array([y]).T return np.array(-(y - y_hat)) def sigmoid(self, x: List[float]) -&gt; List[float]: return 1 / (1 + np.exp(-x)) def sigmoid_derivative(self, x: List[float]) -&gt; List[float]: return self.sigmoid(x) * (1 - self.sigmoid(x)) def relu(self, x: List[float]) -&gt; List[float]: return np.maximum(0, x) def relu_derivative(self, x: List[float]) -&gt; List[float]: x[x &lt;= 0] = 0 x[x &gt; 0] = 1 return x def linear(self, x: List[float]) -&gt; List[float]: return x def activation_derivative(self, layer: Dict, curr_layer: List[float]) -&gt; List[float]: if layer["activation_function"] == "linear": return np.array(self.linear(curr_layer)) elif layer["activation_function"] == "relu": return np.array(self.relu_derivative(curr_layer)) elif layer["activation_function"] == "sigmoid": return np.array(self.sigmoid_derivative(curr_layer)) else: raise Exception("Activation function not supported!") def communication(self, curr_epoch: int, curr_trainingsdata: int, data: List[float], target: List[float], how_often: int = 10) -&gt; None: """ Gets executed from the method "train". Communicates information about the current status of training progress. Parameters ---------- i : int A paramter that gets hand over. Current Iteration in a foor loop. how_often: int Is used to determine the frequently of updates from the training progress. Returns ------- None """ if curr_epoch % how_often == 0: print("For iteration/trainings-example: #" + str(curr_epoch) + "/#"+ str(curr_trainingsdata)) print("Input: " + str(data)) print("Actual Output: " + str(target)) print("Predicted Output: " + str(self.output_model)) print("Loss: " + str(self.loss(y=target, y_hat=self.output_model))) print("Value of last weight change: " + str(self.weight_change_cache[-1])) print("\n") def init_logging(self, level_of_debugging: str) -&gt; object: """ Gets executed from the constructor "__init__". Initializes the logger. Parameters ---------- level_of_debugging: {"logging.DEBUG", "logging.INFO", "logging.CRITICAL", "logging.WARNING", "logging.ERROR"} Which error get logged. Returns ------- Object return a logger object which is used to log errors. """ # creating a directory for "logs" if the directory doesnt exist path = os.getcwd() name = "logs" full_path = path + "\\" + name try: if not os.path.isdir(full_path): os.mkdir(full_path) except OSError: print("ERROR: Couldn't create a log folder.") # create and configure logger today = date.today() # get current date today_eu = today.strftime("%d-%m-%Y") # european date format LOG_FORMAT: str = "%(levelname)s - %(asctime)s - %(message)s" # logging format logging.basicConfig(filename=full_path + "\\" + today_eu + ".log", level=level_of_debugging, format=LOG_FORMAT) logger = logging.getLogger() # Test logger logger.info("------------------------------------------------") logger.info("Start of the program") logger.info("------------------------------------------------") return logger # TODO: "init_weights" is work in progress. # TODO: "init_weights" init bias. def init_weights(self, custom_weights: bool, custom_weights_data: List) -&gt; List[float]: """ Gets executed from the constructor "__init__". Initializes the weight in the whole Neural Network. Returns ------- List Weights of the Neural Network. """ self.logger.info("init_weights executed") for idx in range(0, len(self.nn_architecture) - 1): # "len() - 1" because the output layer doesn't has weights if not custom_weights: # "self.nn_architecture[idx]["layer_size"] + 1" "+ 1" because we also have a bias term weights_temp = 2 * np.random.rand(self.nn_architecture[idx + 1]["layer_size"], self.nn_architecture[idx]["layer_size"] + 1) - 1 self.weights.append(weights_temp) if custom_weights: self.weights = custom_weights_data return self.weights def activate_neuron(self, x: List[float], layer: Dict) -&gt; List[float]: """ Gets executed from the method "forward" and "full_forward". Activates the neurons in the current layer with the specified activation function. Parameters ---------- x: List[float] This are the values which get activated. layer: Dict A Dictionary with different attributes about the current layer. Returns ------- List Outputs a List with activated values/neurons. """ if layer["activation_function"] == "relu": temp_acti = self.relu(x) # add bias to cache when not output layer if not layer["layer_type"] == "output_layer": tmp_temp_acti_for_chache = self.add_bias(temp_acti) else: tmp_temp_acti_for_chache = temp_acti.T # the name of the key of the dict is the index of current layer idx_name = self.nn_architecture.index(layer) self.layer_cache.update({"a" + str(idx_name): tmp_temp_acti_for_chache}) return temp_acti elif layer["activation_function"] == "sigmoid": temp_acti = self.sigmoid(x) # add bias to cache when not output layer if not layer["layer_type"] == "output_layer": tmp_temp_acti_for_chache = self.add_bias(temp_acti) else: tmp_temp_acti_for_chache = temp_acti.T # the name of the key of the dict is the index of current layer idx_name = self.nn_architecture.index(layer) self.layer_cache.update({"a" + str(idx_name): tmp_temp_acti_for_chache}) return temp_acti else: raise Exception("Activation function not supported!") def forward(self, weight: List[float], x: List[float], layer: Dict, idx: int) -&gt; List[float]: """ Gets executed from the method "full_forward". This method make´s one forward propagation step. Parameters ---------- weight : List[float] The weights of each associated Neurons in a List. x : List[float] The Input from the current layer which gets multiplicated with the weights and summed up. layer : Dict A Dictionary with different attributes about the current layer. Returns ------- List List with values from the output of the one step forward propagation. """ curr_layer = np.dot(weight, x.T) # add bias to cache when not output layer if not layer["layer_type"] == "output_layer": tmp_curr_layer_for_chache = self.add_bias(curr_layer) else: tmp_curr_layer_for_chache = curr_layer.T # the name of the key of the dict is the index of current layer idx_name = self.nn_architecture.index(layer) tmp_dict = {"z" + str(idx_name): tmp_curr_layer_for_chache} self.layer_cache.update(tmp_dict) # append the "z" value | not activated value curr_layer = self.activate_neuron(curr_layer, layer) return curr_layer # TODO: "full_forward" is work in progress def full_forward(self, data): """ Gets executed from the method "forward_backprop". Makes the full forward propagation through the whole Architecture of the Neural Network. Returns ------- List List with the values of the output Layer. """ self.logger.info("full_forward executed") self.layer_cache = {} # delete cache used from previous iteration for idx in range(0, len(self.nn_architecture) - 1): self.logger.debug("Current-index (full_forward methode): " + str(idx)) if self.nn_architecture[idx]["layer_type"] == "input_layer": self.layer_cache.update({"z0": data}) self.layer_cache.update({"a0": data}) self.curr_layer = self.forward(self.weights[idx], data, self.nn_architecture[idx + 1], idx=idx) # "idx + 1" to fix issue regarding activation function else: self.curr_layer = self.add_bias(self.curr_layer) self.curr_layer = self.forward(self.weights[idx], self.curr_layer, self.nn_architecture[idx + 1], idx=idx) self.output_model = self.curr_layer # TODO: "backprop" is work in progress def backprop(self, target: List[float]) -&gt; None: # application of the chain rule to find derivative """ Gets executed from the method "forward_backprop". This method handels the backpropagation of the Neural Network. Returns ------- None """ self.weight_change_cache = [] self.error_term_cache = [] self.logger.info("Backprop executed") for idx, layer in reversed(list(enumerate(nn_architecture))): # reversed because we go backwards if not layer["layer_type"] == "input_layer": # if we are in the input layer # calculating the error term if layer["layer_type"] == "output_layer": temp_idx = "z" + str(idx) d_a = self.activation_derivative(layer, self.layer_cache[temp_idx]) d_J = self.loss_derivative(y=target, y_hat=self.output_model) error_term = np.array([np.multiply(d_a.flatten(), d_J.flatten())]) self.error_term_cache.append(error_term) tmp_matrix_weight = np.asarray(self.weights[idx - 1]) tmp_bias_weight_t = np.array(tmp_matrix_weight.T[0]) self.bias_weight_tmp.append([tmp_bias_weight_t]) else: temp_idx = "z" + str(idx) layer_cache_tmp_drop_bias = np.delete(self.layer_cache[temp_idx], 0, 1) d_a = self.activation_derivative(layer, layer_cache_tmp_drop_bias) d_J = 0 for item in reversed(self.error_term_cache): tmp_matrix_weight = np.asarray(self.weights[idx - 1]) self.bias_weight_tmp.append([tmp_matrix_weight.T[0]]) weights_tmp_drop_bias = np.delete(self.weights[idx], 0, 1) d_J = d_J + np.dot(weights_tmp_drop_bias.T, item.T) error_term = d_a.T * d_J error_term = error_term.T self.error_term_cache.append(error_term) err_temp = error_term.T temp_idx = "a" + str(idx - 1) cache_tmp = self.layer_cache[temp_idx] cache_tmp = np.delete(cache_tmp, 0, 1) # delete bias weight_change = err_temp * cache_tmp self.weight_change_cache.append(weight_change) # update weights for idx in range(0, len(self.weight_change_cache)): # reversed because we go backwards curr_weight = self.weights[-idx - 1] curr_weight = np.delete(curr_weight, 0, 1) # delete bias weight_change_tmp = self.weight_change_cache[idx] total_weight_change = self.alpha * weight_change_tmp # updating weight curr_weight = curr_weight - total_weight_change self.weights[-idx - 1] = curr_weight # update bias if layer["layer_type"] == "output_layer": for i in range(0, len(self.bias_weight_tmp)): tmp_weight_bias = np.asarray(self.bias_weight_tmp[i]) tmp_error_term_bias = np.asarray(self.error_term_cache[i]) self.bias_weight_tmp[i] = tmp_weight_bias - (self.alpha * tmp_error_term_bias) # insert bias in weights for i in range(0, len(self.weights)): self.weights[i] = np.insert(self.weights[i], obj=0, values=self.bias_weight_tmp[i], axis=1) # insert the weights for the biases # TODO: "train" is work in progress def train(self, how_often, epochs=20) -&gt; None: """ Execute this method to start training your neural network. Parameters ---------- how_often : int gets handed over to communication. Is used to determine the frequently of updates from the training progress. epochs : int determines the epochs of training. Returns ------- None """ self.logger.info("Train-method executed") for curr_epoch in range(epochs): for idx, trainings_data in enumerate(x): trainings_data_with_bias = self.add_bias(trainings_data) self.full_forward(trainings_data_with_bias) self.backprop(self.y[idx]) self.communication(curr_epoch, idx, target=self.y[idx], data=trainings_data, how_often=how_often) self.x_train_loss_history.append(curr_epoch) self.y_train_loss_history.append(self.loss(y[idx], self.output_model)) def predict(self): """ Used for predicting with the neural network """ print("Predicting") print("--------------------") running = True while(running): pred_data = [] for i in range(0, self.nn_architecture[0]["layer_size"]): tmp_input = input("Enter " + str(i) + " value: ") pred_data.append(tmp_input) self.full_forward(np.asarray([pred_data], dtype=float)) print("Predicted Output: ", self.output_model) print(" ") running = input('Enter "exit" if you want to exit. Else press "enter".') if running == "exit" or running == "Exit": running = False else: running = True def visulize(self): data = {"x": self.x_train_loss_history, "train": self.y_train_loss_history} data = pd.DataFrame(data, columns=["x", "train"]) sns.set_style("darkgrid") plt.figure(figsize=(12, 6)) sns.lineplot(x="x", y="train", data=data, label="train", color="orange") plt.xlabel("Time In Epochs") plt.ylabel("Loss") plt.title("Loss over Time") plt.show() if __name__ == "__main__": # data for nn and target x = np.array([[1, 0]], dtype=float) y = np.array([[0, 1]], dtype=float) # nn_architecture is WITH input-layer and output-layer nn_architecture = [{"layer_type": "input_layer", "layer_size": 2, "activation_function": "none"}, {"layer_type": "hidden_layer", "layer_size": 2, "activation_function": "sigmoid"}, {"layer_type": "output_layer", "layer_size": 2, "activation_function": "sigmoid"}] weights_data = [np.array([[2, 0.15, 0.2], [2, 0.25, 0.3]], dtype=float), np.array([[4, 0.4, 0.45], [4, 0.5, 0.55]], dtype=float)] weights_data = weights_data #, custom_weights=True, custom_weights_data=weights_data NeuralNetwork_Inst = NeuralNetwork(x, y, nn_architecture, 0.1, 5) NeuralNetwork_Inst.train(how_often=100, epochs=500) NeuralNetwork_Inst.visulize() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:39:47.283", "Id": "457425", "Score": "1", "body": "Just FIY, check out `numpy.hstack` and `numpy.vstack`, you can append numpy arrays :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:40:35.747", "Id": "457535", "Score": "0", "body": "@IEatBagels oh, I didn't know that thanks." } ]
[ { "body": "<p>A few points that stood out to me from a cursory glance:</p>\n\n<ul>\n<li><code>level_of_debugging</code> doesn't seem to serve any purpose as an attribute. The <code>__init__</code> function doesn't accept an argument to set it. The only other function which uses it, <code>init_logging</code>, takes it as an argument anyway. I think it should either\n\n<ul>\n<li>be configurable via <code>__init__</code>, and <code>init_logging</code> should then use <code>self.level_of_debugging</code> instead of accepting an argument,</li>\n<li>or removed entirely and <code>init_logging</code> be simply called with <code>logging.INFO</code> directly.</li>\n</ul></li>\n<li><p>Instead of using <code>path + \"\\\\\" + name</code> and the like, fiddling with path separators manually, use <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path\" rel=\"nofollow noreferrer\"><code>pathlib.Path</code></a>:</p>\n\n<pre><code>path = pathlib.Path.cwd()\nname = \"logs\"\nfull_path = path / name\n</code></pre>\n\n<p>Even though it uses a Unix-like <code>/</code> for joining the paths, it will work fine on both Windows and POSIX systems. Similarly, use <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_dir\" rel=\"nofollow noreferrer\"><code>pathlib.Path.is_dir()</code></a> and <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\" rel=\"nofollow noreferrer\"><code>pathlib.Path.mkdir()</code></a>.</p></li>\n<li><p>If an activation function is not supported, a more appropriate action might to raise a <code>TypeError</code> or <a href=\"https://docs.python.org/3/library/exceptions.html#NotImplementedError\" rel=\"nofollow noreferrer\"><code>NotImplementedError</code></a> instead of a generic <code>Exception</code>. From the explanation of <a href=\"https://docs.python.org/3/library/exceptions.html#TypeError\" rel=\"nofollow noreferrer\"><code>TypeError</code></a>:</p>\n\n<blockquote>\n <p>This exception may be raised by user code to indicate that an\n attempted operation on an object is not supported, and is not meant to\n be. If an object is meant to support a given operation but has not yet\n provided an implementation, <code>NotImplementedError</code> is the proper\n exception to raise.</p>\n</blockquote>\n\n<p>It's not a perfect fit, but it's a better fit than a generic <code>Exception</code>. More experienced Pythonistas can suggest better options.</p></li>\n<li><p><a href=\"https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings\" rel=\"nofollow noreferrer\">f-strings</a> can, IMHO, give more readable code in the long run. Instead of lines like the following where you jump in and out of strings:</p>\n\n<pre><code>print(\"For iteration/trainings-example: #\" + str(curr_epoch) + \"/#\"+ str(curr_trainingsdata))\nprint(\"Input: \" + str(data))\nprint(\"Actual Output: \" + str(target))\nprint(\"Predicted Output: \" + str(self.output_model))\nprint(\"Loss: \" + str(self.loss(y=target, y_hat=self.output_model)))\nprint(\"Value of last weight change: \" + str(self.weight_change_cache[-1]))\nprint(\"\\n\")\n</code></pre>\n\n<p>You can have a cleaner form:</p>\n\n<pre><code>print(f\"For iteration/trainings-example: #{curr_epoch)/#{curr_trainingsdata}\")\nprint(f\"Input: {data}\")\nprint(f\"Actual Output: {target}\")\nprint(f\"Predicted Output: {self.output_model}\")\nprint(f\"Loss: {self.loss(y=target, y_hat=self.output_model)}\")\nprint(f\"Value of last weight change: {self.weight_change_cache[-1]}\")\nprint(\"\\n\")\n</code></pre>\n\n<p>Or, with <code>sep</code> to use a single <code>print()</code>, which is mostly a matter of taste (I think):</p>\n\n<pre><code>print(\n f\"For iteration/trainings-example: #{curr_epoch)/#{curr_trainingsdata}\",\n f\"Input: {data}\",\n f\"Actual Output: {target}\",\n f\"Predicted Output: {self.output_model}\",\n f\"Loss: {self.loss(y=target, y_hat=self.output_model)}\",\n f\"Value of last weight change: {self.weight_change_cache[-1]}\",\n \"\\n\",\n sep=\"\\n\"\n)\n</code></pre>\n\n<p>This last version is much more readable than the repeated prints and manual concatenation of strings.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T18:27:14.063", "Id": "457292", "Score": "0", "body": "Okay, thank you very much for your feedback. I didn't know about the `pathlib.Path` libary and I also didn't know about the `NotImplementedError`. I'll fix these issues and the others too. Again thank you very much :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:49:13.153", "Id": "457324", "Score": "1", "body": "@Lupos you're welcome, but I think you shouldn't have accepted the answer so soon (others might skip the question then). There are a few other places where improvements can be made, for example, using [f-strings](https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings) instead of `\"foo\" + str(bar)`, typos (`visulize` instead of `visualize`), etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:54:27.460", "Id": "457555", "Score": "0", "body": "and what is the advantage of `f-strings`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:42:43.763", "Id": "457569", "Score": "1", "body": "@Lupos I edited the answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T05:21:51.703", "Id": "233840", "ParentId": "233817", "Score": "4" } }, { "body": "<h1>Separation of concerns</h1>\n\n<p>The <code>NeuralNetwork</code> class is quite complex at the moment, since it implements network handling (training, ...), logging and even visualization. The good news is, that there are already separate methods for them. My recommendation here would be to go one step further and move all the non-essential stuff (logging setup, visualization) out of the class. That will make the class much easier to maintain (and also to review). It will also very likely lead to greater flexibility, e.g. since the logging would not be hidden from the user.</p>\n\n<h1>Internal functions</h1>\n\n<p>There are quite a few internal/helper methods in the class that are only supposed to be used by the class itself, e.g. in <code>__init__</code>. As per the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 style guide</a>, their names should <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"nofollow noreferrer\">start with a single underscore</a> (e.g. <code>def _check_input_output_dimension(...)</code> to mark them as \"for internal use only\" (there is no real <code>private</code> in Python). Following this convention makes it easier to tell the public and internal methods apart.</p>\n\n<h1>Activation and derivatives</h1>\n\n<p>All the activation functions and their derivatives are stateless, i.e. they don't really need to be instance methods. Consider removing them from the class and provide them as callbacks when describing the network structure. For example:</p>\n\n<pre><code># they could also live in your library, maybe with a bit of documentation\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return sigmoid(x) * (1 - sigmoid(x))\n\n# later or in an other file:\n\nnn_architecture = [\n {\n \"layer_type\": \"input_layer\",\n \"layer_size\": 2,\n \"activation_function\": None\n }, \n {\n \"layer_type\": \"hidden_layer\",\n \"layer_size\": 2,\n \"activation_function\": {\n \"function\": sigmoid,\n \"derivative\": sigmoid_derivative\n }\n }, \n {\n \"layer_type\": \"output_layer\",\n \"layer_size\": 2,\n \"activation_function\": {\n \"function\": sigmoid,\n \"derivative\": sigmoid_derivative\n }\n }\n]\n</code></pre>\n\n<p>That will remove a lot of complexity from your implementation of various methods (e.g. <code>activation_derivative</code> and <code>activate_neuron</code>) and also makes it more extensible and flexible, since it's now up to the user to define new activation functions (and their derivative). Best practice implementations of the most common activation functions could still be part of your library, and you can even implement a helper function that does something like the following:</p>\n\n<pre><code>def get_activation(name):\n if name == \"sigmoid\":\n return {\"function\": sigmoid, \"derivative\": sigmoid_derivative}\n elif name == \"linear\":\n return {\"function\": linear, \"derivative\": linear_derivative}\n elif ...:\n ...\n # at the last line\n except ValueError(f\"No known activation function for name '{name}'\")\n</code></pre>\n\n<p>or a dict</p>\n\n<pre><code># a missing name would lead to a KeyError here, that maybe should be handled\n# when used somewhere.\n# also possible: implement get_activation from above using this dict,\n# catch and transform the KeyError there\nACTIVATION = {\n \"sigmoid\": {\"function\": sigmoid, \"derivative\": sigmoid_derivative},\n \"linear\": {\"function\": linear, \"derivative\": linear_derivative},\n ...\n}\n</code></pre>\n\n<p>This can also be hidden in your network, that if the user enters a string as it is now, the network class uses either of the two methods above and tries to determine which functions to use, while still providing the possibility to provide custom functions as well.</p>\n\n<h1>Type annotations and documentation</h1>\n\n<p>From what I can see, there are a few cases where the type annotations don't seem to fit. E.g.</p>\n\n<blockquote>\n<pre><code>def relu_derivative(self, x: List[float]) -&gt; List[float]:\n x[x &lt;= 0] = 0\n x[x &gt; 0] = 1\n return x\n</code></pre>\n</blockquote>\n\n<p>This won't work with <code>List[float]</code>, but is tailored to numpy arrays. I'd try to annotate the with <code>np.ndarray</code>, but the numpy developers don't seem to have settled on a best practice in that regard yet (see <a href=\"https://github.com/numpy/numpy/issues/7370\" rel=\"nofollow noreferrer\">this GitHub issue</a>). I don't use type annotations all to much, so maybe I'm wrong here. But they are not binding, so there is not a lot that can go wrong in that regard apart from confusing other programmers and some tools like <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a> ;-)</p>\n\n<p>Since you are otherwise following the <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">numpydoc</a> convention, a quick note on that regard: most numpy functions that can work both with Python types (<code>list</code>s, <code>tuple</code>s, ...) and numpy arrays, define the input/output type to be <code>array_like</code> (see <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.html\" rel=\"nofollow noreferrer\"><code>np.sin</code></a> for example).</p>\n\n<h1>Logging</h1>\n\n<p>Logging is a great functionality to have at hand, but there can be vastly different needs. My recommendation in that regard would be not to impose any kind of details on the user. There is simply no need to force a European date format on somebody from somewhere else or force them to have their log written to a file, especially if they can neither control the name nor the location the log file is written to. Simply allow the user to pass an (optional) logger when building the network, and work with that. What happens if no logger is provided is up to you. Either setting up a simple console logger or no logging at all are sensible defaults in my opinion.</p>\n\n<h1>Tool support</h1>\n\n<p>It was already mentioned in a comment on the other answer, that there are quite a few typos in comments and method names (e.g. <code>visulize</code> → <code>visualize</code>). There are tools like <a href=\"https://github.com/codespell-project/codespell\" rel=\"nofollow noreferrer\">codespell</a> or language plugins for the IDE of your choice (e.g. <a href=\"https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker\" rel=\"nofollow noreferrer\">Code Spell Checker</a> for VS Code) that can help you in that regard.</p>\n\n<p>There are also a lot of other tools in the Python ecosystem that can help you to keep a consistent code style and the like. A non-exhaustive list can be found at <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">this answer</a> here on Code Review Meta.</p>\n\n<hr>\n\n<p>That's it for now. I would strongly recommend to implement at least some of these changes before bringing the class up for another round of review. Including them will make it much easier to judge the implementation of the core algorithms itself, since I'd reckon they are a lot easier to follow then.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:42:02.447", "Id": "457536", "Score": "0", "body": "thanks you very much for your feedback. I'll implement your recommendations :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:16:29.387", "Id": "457542", "Score": "0", "body": "How do I decide what to include in my class and what to \"outsource\"? e.g should I leave `check_input_output_dimension()` in or out and why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:52:04.120", "Id": "457554", "Score": "0", "body": "And about the function with `_` should I name all private function with `_` or only `helper` function's? e.g. should I name `forward()`,`full_forward`, `train()` with `_` or just helper functions like `add_bias()` with `_`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:57:31.763", "Id": "457557", "Score": "0", "body": "Or should I name every function with `_` which is a function the user is not supossed to run?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:29:52.177", "Id": "457566", "Score": "1", "body": "*\"[S]hould I name every function with _ which is a function the user is not supossed to run?\"* That's the idea. Most IDEs and documentation generation tools respect this convention as well, which greatly helps to reduce the amount of possible methods shown on autocomplete or in the API doc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:48:29.643", "Id": "233924", "ParentId": "233817", "Score": "4" } } ]
{ "AcceptedAnswerId": "233924", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T20:37:16.977", "Id": "233817", "Score": "6", "Tags": [ "python", "python-3.x", "numpy", "neural-network" ], "Title": "A Neural Network" }
233817
<p>I have a password validation class that takes values from our database and depending on their values, checks if the password is valid. If it is not, I built an error message containing everything that is wrong with the entered password.</p> <p>I want it to be easy to change when I add a validation attribute in the database.</p> <pre><code>Imports System.ComponentModel.DataAnnotations Imports System.Globalization ''' &lt;summary&gt; ''' A custom ValidationAttribute for Internal Login password. ''' &lt;/summary&gt; Friend Class CustomPasswordValidatorAttribute Inherits ValidationAttribute Private Property PasswordAttrs As PasswordsAttributes Private Property InvalidPassReasonsMessage As New StringBuilder Private Property Password As String Public Sub New() MyBase.New() PasswordAttrs = GetPasswordsAttributes() End Sub Protected Overrides Function IsValid(value As Object, validationContext As ValidationContext) As ValidationResult SetCultureWithCookie() Password = If(value Is Nothing, String.Empty, value.ToString) InvalidPassReasonsMessage.Clear() IfConditionMetAddReason(IsInvalidMinLength(), String.Format(Resources.Account.PassMinLengthErr, PasswordAttrs.MinLength)) IfConditionMetAddReason(IsInvalidMaxLength(), String.Format(Resources.Account.PassMaxLengthErr, PasswordAttrs.MaxLength)) IfConditionMetAddReason(IsInvalidNeedSpecialCharacter(), Resources.Account.PassNeedNonLetterOrDigitErr) IfConditionMetAddReason(IsInvalidNeedDigit(), Resources.Account.PassNeedDigitErr) IfConditionMetAddReason(IsInvalidNeedLowercase(), Resources.Account.PassNeedLowerErr) IfConditionMetAddReason(IsInvalidNeedUppercase(), Resources.Account.PassNeedUpperErr) Return GetPasswordValidationResult(InvalidPassReasonsMessage) End Function Private Sub SetCultureWithCookie() Dim location = HttpContext.Current.Request.QueryString("location") If String.IsNullOrEmpty(location) Then location = "default" Dim webSettings As Collections.Generic.Dictionary(Of String, String) = ICE.Utility.IceApplication.instance.Location(location).WebSettings If Utility.GlobalUtility.LanguageCookie(location, webSettings) = Constants.GlobalConstant.Language.French Then CultureInfo.CurrentUICulture = New CultureInfo("fr") CultureInfo.CurrentCulture = New CultureInfo("fr") Else CultureInfo.CurrentUICulture = New CultureInfo("en") CultureInfo.CurrentCulture = New CultureInfo("en") End If End Sub Private Sub IfConditionMetAddReason(condition As Boolean, msg As String) If condition Then InvalidPassReasonsMessage.Append(msg) End If End Sub Private Function GetPasswordValidationResult(reason As StringBuilder) As ValidationResult If reason.Length = 0 Then Return ValidationResult.Success Else reason.Insert(0, Resources.Account.PassErr) Return New ValidationResult(reason.ToString) End If End Function Private Function IsInvalidMinLength() As Boolean Return String.IsNullOrEmpty(Password) OrElse Password.Length &lt; PasswordAttrs.MinLength End Function Private Function IsInvalidMaxLength() As Boolean Return Password.Length &gt; PasswordAttrs.MaxLength End Function Private Function IsInvalidNeedSpecialCharacter() As Boolean Return PasswordAttrs.NeedSpecialCharacter AndAlso Not ContainsSpecialChar(Password) End Function Private Function IsInvalidNeedDigit() As Boolean Return PasswordAttrs.NeedDigit AndAlso Not ContainsDigit(Password) End Function Private Function IsInvalidNeedLowercase() As Boolean Return PasswordAttrs.NeedLowercase AndAlso Not ContainsLowercase(Password) End Function Private Function IsInvalidNeedUppercase() As Boolean Return PasswordAttrs.NeedUppercase AndAlso Not ContainsUppercase(Password) End Function Private Function ContainsSpecialChar(s As String) As Boolean Return s.Any(Function(c) (Not Char.IsLetterOrDigit(c) AndAlso Not Char.IsWhiteSpace(c))) End Function Private Function ContainsDigit(s As String) As Boolean Return s.Any(Function(c) (Char.IsDigit(c))) End Function Private Function ContainsLowercase(s As String) As Boolean Return s.Any(Function(c) (Char.IsLower(c))) End Function Private Function ContainsUppercase(s As String) As Boolean Return s.Any(Function(c) (Char.IsUpper(c))) End Function Private Function GetPasswordsAttributes() As PasswordsAttributes Dim adoTable As New System.Data.DataTable ICE.ContextLess.FillDataTable(adoTable, "SELECT * FROM LOGINPARAMETERS_T") If adoTable.Rows.Count = 1 Then Return New PasswordsAttributes(adoTable.Rows(0)) End If Return Nothing End Function Private Class PasswordsAttributes Public Property MinLength As Integer Public Property MaxLength As Integer Public Property NeedSpecialCharacter As Boolean Public Property NeedDigit As Boolean Public Property NeedLowercase As Boolean Public Property NeedUppercase As Boolean Public Sub New() End Sub Public Sub New(row As DataRow) If Not IsDBNull(row("PWD_MIN_LEN")) Then Me.MinLength = CInt(row("PWD_MIN_LEN")) If Not IsDBNull(row("PWD_MAX_LEN")) Then Me.MaxLength = CInt(row("PWD_MAX_LEN")) If Not IsDBNull(row("PWD_REQ_SP_CHAR_IND")) Then Me.NeedSpecialCharacter = CBool(row("PWD_REQ_SP_CHAR_IND")) If Not IsDBNull(row("PWD_REQ_DIG_IND")) Then Me.NeedDigit = CBool(row("PWD_REQ_DIG_IND")) If Not IsDBNull(row("PWD_REQ_LOCS_CHAR_IND")) Then Me.NeedLowercase = CBool(row("PWD_REQ_LOCS_CHAR_IND")) If Not IsDBNull(row("PWD_REQ_UPCS_CHAR_IND")) Then Me.NeedUppercase = CBool(row("PWD_REQ_UPCS_CHAR_IND")) End Sub End Class End Class </code></pre> <p>How can this be improved? Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T05:34:33.210", "Id": "457182", "Score": "0", "body": "Just to confirm, this is a database that is storing the passwords in the clear?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:48:44.907", "Id": "457245", "Score": "0", "body": "@AJD not at all. The password in clear comes from the parameter in IsValid. And it is stored encrypted but not it this part of the code. This is only the validator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T19:34:52.490", "Id": "462255", "Score": "0", "body": "Move away from the archaic, currently-non-standard complexity rules for passwords. Reference the NIST current standards at https://pages.nist.gov/800-63-3/sp800-63b.html Specifically, look at section 5.1.1.1. They use \"memorized secret\" for password." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T19:41:30.820", "Id": "462256", "Score": "0", "body": "@HardCode I understand your point bu clients want what they want and we figured it is better to have more than less. By default only the min length and max length will be set and the other ones won't be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T19:47:18.907", "Id": "462257", "Score": "0", "body": "@Edit fair enough, customers pay the bills. It looks like you're building out what FluentValidation does. Have you looked into it before?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:04:30.760", "Id": "233820", "Score": "1", "Tags": [ "object-oriented", "vb.net" ], "Title": "Password validation class using database values" }
233820
<p>I'm new to TPL Dataflow and was looking for an action block to basically push an object on a timer - specifically to produce heartbeats on every interval. I was unable to find anything out of the box so I decided to create a wrapper class on action block that would give me the desired functionality. I also wanted to include async/await pattern in the implementation. </p> <p>Given the following heartbeat object:</p> <pre><code>public class Heartbeat { public DateTime HearbeatTimeUtc { get; set; } } </code></pre> <p>The wrapper class:</p> <pre><code>public class TimerActionBlock&lt;TInput&gt; { private readonly ActionBlock&lt;TInput&gt; _actionBlock; public TimerActionBlock(Func&lt;TInput, Task&gt; func, Func&lt;TInput, Exception, Task&gt; excptionFunc) { _actionBlock = new ActionBlock&lt;TInput&gt;(async input =&gt; { try { await func(input); } catch (Exception e) { await excptionFunc(input, e); } }); } public void Start(Func&lt;Task&lt;TInput&gt;&gt; inputFunc, TaskScheduler scheduler, TimeSpan dueTime, TimeSpan period, CancellationToken cancellationToken, Action&lt;Exception&gt; onError) { Task .Factory .StartNew(async () =&gt; { await Task.Delay(dueTime); while (true) { var input = await inputFunc(); await _actionBlock.SendAsync(input); var task = Task.Delay(period, cancellationToken); try { await task; } catch (TaskCanceledException) { return; } } }, cancellationToken, TaskCreationOptions.LongRunning, scheduler) .ContinueWith(task =&gt; { onError(task.Exception); }, TaskContinuationOptions.OnlyOnFaulted); } } </code></pre> <p>Calling code would something like the following:</p> <pre><code>var timerActionBlock = new TimerActionBlock&lt;Heartbeat&gt;(heartbeat =&gt; { Console.WriteLine(JsonConvert.SerializeObject(heartbeat)); return Task.CompletedTask; }, (heartbeat, exception) =&gt; { Console.WriteLine(exception); return Task.CompletedTask; }); timerActionBlock .Start(() =&gt; Task.FromResult(new Heartbeat { HearbeatTimeUtc = DateTime.UtcNow }), TaskScheduler.Default, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(1000), CancellationToken.None, Console.WriteLine); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T17:02:42.037", "Id": "459445", "Score": "0", "body": "TPL DataFlow is about creating a data mesh and having data flow. I'm not sure I understand the need to have an action block that just fires on a timer. When you say you want the timer to push an object on a timer do you want this to be the source of the Data Flow? If so then Action block isn't the correct block to base it on. With more information I could maybe help provide an answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:46:08.567", "Id": "463343", "Score": "0", "body": "You might also look at the periodic stuff in this library that I created: https://github.com/BrannonKing/Kts.ActorsLite" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T21:57:53.197", "Id": "233822", "Score": "6", "Tags": [ "c#", "async-await", "tpl-dataflow" ], "Title": "TPL Dataflow - Timer Action Block" }
233822
<p>Below is an example of a simple converter. In the first example <code>temperature</code> I have used a function within a function. In the second example <code>milli</code> I have used a more direct approach. Which would you consider is the better method to handling calculations in functions and why? Also feedback on my approach and examples of other methods is appreciated. </p> <pre><code>def temperature(): while True: try: user_in = float(input('Number to convert:&gt; ')) t = user_in def cel_to_far(x): return 9 * x / 5 + 32 result = 'is: {} degrees Fahrenheit'.format(cel_to_far(t)) print('Input: {} degrees Celcius'.format(t), result) break except ValueError: print('Enter numbers only!') def milli(): while True: try: user_in = float(input('Number to convert:&gt; ')) n = 1 * user_in / 25.4 print('Input: {} millimeters is: {} inches'.format(user_in, n)) break except ValueError: print('Enter numbers only!') </code></pre>
[]
[ { "body": "<p>My general rule is that if I'm going to need to refer to something more than once, I give it a name, and if not, then I skip the syntactic sugar and just use the expression in place. This usually makes the code more concise and reduces the burden on the reader of having to keep track of a bunch of different variable names.</p>\n\n<p>Applying that principle to your first example, I'd get rid of not only <code>cel_to_far</code> but also <code>t</code> and <code>result</code>, which would give me:</p>\n\n<pre><code>def temperature() -&gt; None:\n while True:\n try:\n user_in = float(input('Number to convert:&gt; '))\n print(\n 'Input: {} degrees Celsius'.format(user_in),\n 'is: {} degrees Fahrenheit'.format(9 * user_in / 5 + 32)\n )\n break\n except ValueError:\n print('Enter numbers only!')\n</code></pre>\n\n<p>IMO this is a lot more clear because you can see at a glance what's happening to the input without having to trace it through multiple assignments and function calls (maintaining multiple pieces of mental state to be able to execute the code in your head and figure out what it's doing). </p>\n\n<p>The new version of the <code>print</code> call also shows a preview within the code of exactly what the output will look like, rather than assembling it in reverse order (again, making the reader mentally execute the code in order to visualize the final result).</p>\n\n<p>If you think you might have any other functions that would need to do the same conversion, then of course it makes sense to define a function for it, but you'd do it in the outer scope so that it's actually reusable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:59:48.560", "Id": "233827", "ParentId": "233826", "Score": "6" } }, { "body": "<p>I think it depends on how self-evident the code is. If it's clear from context what the intent of a calculation or function call is, then I agree with @Sam that the code will be more concise without giving it a name.</p>\n\n<p>On the other end though, depending on the context, <code>9 * x / 5 + 32</code> might not be obvious in what it's doing. You may find that giving that equation a name helps readability in general, which may trump conciseness.</p>\n\n<p>In this exact case though, I don't think there's a ton of benefit to giving it a name unless you strongly suspected that you'd need it elsewhere in the future, or you personally like the way having a name reads. I think that that formula is well-known enough that most people would be able to tell what it's doing; especially when it's inside of a function called <code>temperature</code>.</p>\n\n<hr>\n\n<p>In this case though, there's no good reason that the function should be inside of <code>temperature</code>. Defining one function inside of another suggests that the inner function has no meaning outside of enclosing function, which may be the case if you're forming a closure over a local variable or something similar. In this case though, <code>cel_to_far</code> is just simply taking a parameter and returning an output. It isn't using anything local to <code>temperature</code>. If you wanted to have a standalone function, I would definitely move <code>cel_to_far</code> outside of temperature. If you want it to be \"private\" to the module, prefix the name with an <code>_</code>:</p>\n\n<pre><code>def _cel_to_far(x):\n return 9 * x / 5 + 32\n\ndef temperature():\n . . .\n</code></pre>\n\n<hr>\n\n<p>You're only using two spaces of indentation. Please use <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">four-spaces</a>, as per PEP8.</p>\n\n<hr>\n\n<p><code>t = user_in</code> isn't useful. You're taking a line to rename an already short variable name to something obscure. If you need to reduce line lengths, there are other more readable ways of achieving that. Here though, the longest line is only 76 characters long after fixing the indentation and getting rid of <code>t</code>. That's not very long, and <code>user_in</code> is a much more descriptive name.</p>\n\n<hr>\n\n<p>In both your main functions, you're getting float input from the user manually with a <code>while True</code> and <code>try</code>. In an effort to reduce duplication and centralize how you're handling input, I'd make a helper function:</p>\n\n<pre><code>def _ask_for_float():\n while True:\n try:\n return float(input('Number to convert:&gt; '))\n\n except ValueError:\n print('Enter numbers only!')\n</code></pre>\n\n<p>Instead of repeating the <code>while True: try . . .</code> part, make that a function, then call the function. Notice how much neater this makes each of the functions:</p>\n\n<pre><code>def _ask_for_float():\n while True:\n try:\n return float(input('Number to convert:&gt; '))\n\n except ValueError:\n print('Enter numbers only!')\n\n\ndef _cel_to_far(x):\n return 9 * x / 5 + 32\n\n\ndef temperature():\n user_in = _ask_for_float()\n result = 'is: {} degrees Fahrenheit'.format(_cel_to_far(user_in))\n\n print('Input: {} degrees Celcius'.format(user_in), result)\n\n\ndef milli():\n user_in = _ask_for_float()\n n = 1 * user_in / 25.4\n\n print('Input: {} millimeters is: {} inches'.format(user_in, n))\n</code></pre>\n\n<p>That immediately fixes any line-length issues by removing two levels of indentation, and makes each function trivial.</p>\n\n<hr>\n\n<p>Finally, lines like:</p>\n\n<pre><code>print('Input: {} degrees Celcius'.format(user_in), result)\n</code></pre>\n\n<p>Can be written inline using <a href=\"https://www.python.org/dev/peps/pep-0498/#abstract\" rel=\"nofollow noreferrer\">f-strings</a>. I'd collapse <code>result</code> back into the literal for readability as well:</p>\n\n<pre><code>def temperature():\n user_in = _ask_for_float()\n\n print(f'Input: {user_in} degrees Celcius is: {_cel_to_far(user_in)} degrees Fahrenheit')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:01:31.697", "Id": "457964", "Score": "0", "body": "To make in more user friendly, `_ask_for_float()` should take a str argument to be passed to `input()`. It can default to 'Number to convert:> '. That way the prompt can be something more useful, like \"Enter degrees Celcius:> \"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:34:13.510", "Id": "458024", "Score": "0", "body": "@RootTwo When I've suggested this function previously, I had just that. I intentionally wanted to keep it simple here though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T23:59:13.557", "Id": "233828", "ParentId": "233826", "Score": "10" } } ]
{ "AcceptedAnswerId": "233828", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T22:40:31.940", "Id": "233826", "Score": "7", "Tags": [ "python", "functional-programming" ], "Title": "Simple converter: Is it better to use a function within a function?" }
233826
<blockquote> <p>Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.</p> <p>For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.</p> <p>Evaluate the sum of all the amicable numbers under 10000.</p> </blockquote> <p>I have the following code which I know works, but is very slow for large numbers.</p> <pre><code>import time start = time.time() n = int(input("Enter a number")) def factor(c): factors = [] for d in range(1, int(c / 2) + 1): if c % d == 0: factors.append(d) return sum(factors) def sum_ammicable(x): ammicable = set() for a in range(1, x): for b in range(1, x): if a != b: if factor(a) == b and factor(b) == a: ammicable.update([a,b]) return sum(ammicable) print(sum_ammicable(n)) end = time.time() print(end -start) </code></pre> <p>How can I optimise this code</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T03:37:33.727", "Id": "457177", "Score": "0", "body": "Have you solved the problem? If so, the Project Euler site has an [overview](https://projecteuler.net/overview=021) you can read with lots of speed improvement tips." } ]
[ { "body": "<h2>Integer Division</h2>\n\n<p>Python comes with a built-in integer division operator. So instead of writing <code>int(c / 2) + 1</code>, you could simply write <code>c // 2 + 1</code>. It is slightly faster.</p>\n\n<h2>Unnecessary List Creation</h2>\n\n<p>Creating a list of <code>factors</code> just to <code>sum(factors)</code> afterwards is unnecessary busy work, which takes time. Simply add up the factors as you find them:</p>\n\n<pre><code>def factor(c):\n total = 0\n for d in range(1, c // 2 + 1):\n if c % d == 0:\n total += d\n return total\n</code></pre>\n\n<p>Or, use a generator expression with <code>sum()</code>:</p>\n\n<pre><code>def factor(c):\n return sum(d for d in range(1, c // 2 + 1) if c % d == 0)\n</code></pre>\n\n<p>There is no need to store the factors you found.</p>\n\n<h2>Move Invariants out of Loops</h2>\n\n<p>Consider:</p>\n\n<pre><code>def sum_ammicable(x):\n ...\n for a in range(1, x):\n for b in range(1, x):\n if a != b:\n if factor(a) == b and ...:\n ...\n ...\n</code></pre>\n\n<p>How many times is <code>factor(a)</code> computed when <code>a==1</code>? If <code>x == 10000</code>, it gets computed 10000 times ... once for each <code>b</code> value. How many times when <code>a==2</code>? It'll get computed 10000 times as well. But does <code>factor(a)</code> depend on the value of <code>b</code>? No. Each time you compute <code>factor(a)</code>, for the same value of <code>a</code>, the same result is produced.</p>\n\n<p>Can you calculate this value once per <code>a</code> loop? Sure! Move it out of the <code>b</code> loop!</p>\n\n<pre><code>def sum_ammicable(x):\n ...\n for a in range(1, x):\n factor_a = factor(a)\n for b in range(1, x):\n if a != b:\n if factor_a == b and ...:\n ...\n ...\n</code></pre>\n\n<p>Instead of computing <code>factor(a)</code> 100,000,000 times, you now only compute it 10,000 times, which should be a significant improvement in speed.</p>\n\n<p>Finally, considering that:</p>\n\n<pre><code> for b in range(1, x):\n ...\n if factor_a == b and ...:\n ...\n</code></pre>\n\n<p>will only execute the rest of the <code>if</code> statement (and perhaps the body of the <code>if</code>) for exactly one value of <code>b</code>, do you really need to loop over all 10,000 possible <code>b</code> values? With a little thought, and a little reworking of the code, you can remove the <code>b</code> loop altogether!</p>\n\n<h2>Group Related Code Together</h2>\n\n<p>You start with </p>\n\n<pre><code>start = time.time()\n\nn = int(input(\"Enter a number\"))\n</code></pre>\n\n<p>then 2 function definitions, and then you continue with mainline code:</p>\n\n<pre><code>print(sum_ammicable(n))\n\nend = time.time()\nprint(end -start)\n</code></pre>\n\n<p>Move the code together, after the function declarations. Even better, place it inside a <code>if __name__ == '__main__':</code> guard, so you can import <code>factor(c)</code> and <code>sum_ammicable(x)</code> functions into other code:</p>\n\n<pre><code>if __name__ == '__main__':\n\n start = time.time()\n\n n = int(input(\"Enter a number\"))\n\n print(sum_ammicable(n))\n\n end = time.time()\n print(end - start)\n</code></pre>\n\n<p>Now that this code isn't separated by 2 functions, it becomes apparent you are timing how long the user takes to \"Enter a number\" in addition to the time it takes to compute <code>sum_ammicable(n)</code>. Is the user's reaction &amp; typing speed really being profiled here? Perhaps you want to move <code>start = time.time()</code> after the input statement.</p>\n\n<p>Pro tip: use <code>time.perf_counter()</code> instead of <code>time.time()</code> for higher accuracy profiling.</p>\n\n<hr>\n\n<p>Algorithmic improvements are covered on the Project Euler site itself. Read the problem <a href=\"https://projecteuler.net/overview=021\" rel=\"nofollow noreferrer\">overview</a> after successfully completing the problem for some additional dramatic improvements. There is no need to reproduce their analysis here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:03:24.760", "Id": "457321", "Score": "0", "body": "Yeh I just realised how stupid it waste start timing before the user enters the number. I also figured out that the for loop for b wasn't required as well. Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T04:08:48.683", "Id": "233836", "ParentId": "233832", "Score": "4" } }, { "body": "<p>One other major and easy improvement is to notice that factors come in pairs: if <code>a%n==0</code>, than <code>(n/a)%n==0</code>. Thus you only need to look for factors less that <code>n**.5+1</code>. Here's how the factor sum code looks now:</p>\n\n<pre><code>def factor(c):\n total = 1\n for d in range(2, int(c**.5 + 1)):\n if c % d == 0:\n total += d\n if c//d &gt; d:\n total += (c//d)\n return total\n</code></pre>\n\n<p>note that by <code>n=10_000</code>, this loop only has <code>100</code> iteration, compared to <code>5000</code> before. That's a roughly 50x speedup. For another factor of 2 speedup, notice that a,b is amicable if and only if b,a is amicable, so you can start the b loop at the value of a+1</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T04:53:53.693", "Id": "233839", "ParentId": "233832", "Score": "2" } }, { "body": "<p>The following is an updated version of my code:</p>\n\n<pre><code>import time\nimport math\n\n# finds the sum of the proper divisors of a number c\n\ndef factor(c):\n sum_of_factors = 1\n if type(math.sqrt(c)) is int:\n sum_of_factors += math.sqrt(c)\n for d in range(2, int(math.sqrt(c)) + 1):\n if c % d == 0:\n sum_of_factors += d + (c / d)\n return sum_of_factors\n\n# finds sum of amicable numbers\n\ndef sum_amicable(x):\n amicable = 0\n for a in range(1, x):\n b = factor(a)\n if a != b and factor(a) == b and factor(b) == a:\n amicable += (a + b) / 2\n return amicable\n\n\nn = int(input(\"Enter a number\"))\n\nstart = time.time()\n\nprint(sum_amicable(n))\n\nend = time.time()\nprint(end - start)\n</code></pre>\n\n<p>I found the answer in 0.16054987907409668 seconds</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T04:47:55.593", "Id": "457326", "Score": "0", "body": "`type(math.sqrt(4)) is int` results in `False` instead of `True`. And `factor(4)` results in `5.0` instead of `3`. While you might end up getting the correct answer, this code is broken; the original code was correct, but slower, and correctness matters more than speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T04:51:35.980", "Id": "457327", "Score": "0", "body": "This is not a proper answer on Code Review. Answers must critic the original code, and explain why code should be changed from the original and why the change is an improvement. Simply posting updated code based on feedback in other answers does not constitute a review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:04:17.787", "Id": "233894", "ParentId": "233832", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T01:57:42.757", "Id": "233832", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Project Euler 21: Sum of amicable numbers optimisation" }
233832
<p>I have RGB Images, Depth images and OpenPose Images(generated from RGB Images). The number of RGB and Depth images are different so I have to find the exactly which RGB images corresponds to which depth images. This is done using the time stamp values I have for both RGB and Depth Images.</p> <p>The problem here is this code I have written takes around 7-10 minutes to execute which I feel is a lot. How can the time be reduced for the same? Here mainly imwrite is taking lot of time.</p> <pre><code>function image_sorting(color_img, depth_img, Openpose, selected_color, selected_depth) filePattern = fullfile(depth_img, '*.timestamp'); file = dir(filePattern); filePattern2 = fullfile(color_img, '*.timestamp'); file2 = dir(filePattern2); filePattern3 = fullfile(depth_img, '*.bmp'); file3 = dir(filePattern3); filePattern4 = fullfile(Openpose, '*.png'); file4 = dir(filePattern4); for k = 1:length(file) depthTimestampBase = file(k).name; depthTimestamp = fullfile(depth_img, depthTimestampBase); fileID = fopen(depthTimestamp,'r'); % format longG A(k,:) = textscan(fileID,'%d64') ; fclose(fileID); end for m = 1:length(file2) rgbTimestampBase = file2(m).name; rgbTimestamp = fullfile(color_img, rgbTimestampBase); fileID2 = fopen(rgbTimestamp,'r'); %format longG B(m,:) = textscan(fileID2,'%d64') ; fclose(fileID2); end %%%%%% Here there are two parts. Use any of them according to conditions if length(file2) &lt;= length(file) %PART 1:- If RGB images are less than depth then use the following code for m = 1:length(file2) for k = 1:length(file) C{k,m} = A{k,1} - B{m,1}; if C{k,m}&lt;0 C{k,m} = -C{k,m}; end end end [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns % V gives minimum value and X gives Index m = 1; for w= X depthDataBase = file3(w).name; rgbDataBase = file4(m).name; depthData = fullfile(depth_img, depthDataBase); rgbData = fullfile(Openpose, rgbDataBase); imageArrayy = imread(depthData); imageArrayy2 = imread(rgbData); depthData2 = fullfile(selected_depth, depthDataBase); imwrite(imageArrayy, depthData2); rgbData2 = fullfile(selected_color, rgbDataBase); imwrite(imageArrayy2, rgbData2); m = m+1; % for part 2 m = m+1 end % % PART 2:- If RGB images are more than depth then use the following code else for m = 1:length(file2) for k = 1:length(file) C{m,k} = A{k,1} - B{m,1}; if C{m,k}&lt;0 C{m,k} = -C{m,k}; end end end [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns % V gives minimum value and X gives Index w = 1; for m= X depthDataBase = file3(w).name; rgbDataBase = file4(m).name; depthData = fullfile(depth_img, depthDataBase); rgbData = fullfile(Openpose, rgbDataBase); imageArrayy = imread(depthData); imageArrayy2 = imread(rgbData); depthData2 = fullfile(selected_depth, depthDataBase); imwrite(imageArrayy, depthData2); rgbData2 = fullfile(selected_color, rgbDataBase); imwrite(imageArrayy2, rgbData2); w = w+1; end end </code></pre> <p>Update 1:- Screenshot of Profile execution time. <a href="https://i.stack.imgur.com/T39nZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T39nZ.png" alt="Profile execution time"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T22:09:09.040", "Id": "457307", "Score": "0", "body": "Have you used the profiler to determine `imwrite` is taking a lot of time? If so, a screen shot of the profiler output might be helpful (it also might not be). How many images and what size are you working with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T22:27:52.820", "Id": "457308", "Score": "0", "body": "And also if you could clarify `A` and `B` which are first defined as arrays, but then used as cell arrays when calculating `C`, should they be cell arrays or normal arrays?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T10:41:08.040", "Id": "457362", "Score": "0", "body": "@David I have added screenshot of profile. Also about the arrays, First I am reading timestamp values of both RGB and Depth images in B and A respectively. Now to find the frames which were taken on almost same time, I am subrtacting each value of B with one value of A for all the values of A and then finally taking that value of A and B which has the minimum difference value. So I think it has to be used as cell arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:02:17.707", "Id": "457444", "Score": "0", "body": "Wow imwrite really is taking all the time! Given it's a builtin mex file I can't think of anything you'll be able to do given you can't reduce the number of images to save." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T16:42:33.223", "Id": "460143", "Score": "0", "body": "I have rolled back your latest edit. 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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T16:46:21.237", "Id": "460144", "Score": "0", "body": "@Heslacher Sure.. I didn't know about this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T16:56:07.873", "Id": "460147", "Score": "0", "body": "No problem. Just keep it in mind for the future." } ]
[ { "body": "<p>You are reading in an image and then writing it back out again without making any changes. If the purpose is to copy the file, you are better off directly copying the file. You can use the function <a href=\"https://www.mathworks.com/help/matlab/ref/copyfile.html\" rel=\"nofollow noreferrer\"><code>copyfile</code></a> for that.</p>\n\n<hr>\n\n<p>The code is fairly readable. There are some improvements you can make:</p>\n\n<blockquote>\n<pre><code>filePattern = fullfile(depth_img, '*.timestamp');\nfile = dir(filePattern);\n\nfilePattern2 = fullfile(color_img, '*.timestamp');\nfile2 = dir(filePattern2);\n\nfilePattern3 = fullfile(depth_img, '*.bmp');\nfile3 = dir(filePattern3);\n\nfilePattern4 = fullfile(Openpose, '*.png');\nfile4 = dir(filePattern4);\n</code></pre>\n</blockquote>\n\n<p>The four <code>filePatternN</code> variables are never used again. Why use four different variables, rather than repeat the same name? Why not omit the temporary variable and put these into single lines?</p>\n\n<pre><code>file = dir(fullfile(depth_img, '*.timestamp'));\n</code></pre>\n\n<p>Next, you have two identical loops, one reads from <code>file</code>, one from <code>file2</code>. One writes to <code>A</code>, one to <code>B</code>. Why not make this into a function? You can write local functions at the end of your M-file. You'd simplify this bit to:</p>\n\n<pre><code>A = get_time_stamps(file);\nB = get_time_stamps(file2);\n</code></pre>\n\n<p>Another difference between these two loops is that one uses <code>fileID</code> and one uses <code>fileID2</code>. There is again no need to use two different names for local variables that you don't use outside the loop.</p>\n\n<p>You can improve your code by making <code>A</code> and <code>B</code> numeric arrays rather than cell arrays:</p>\n\n<pre><code>tmp = textscan(fileID,'%d64');\nA(k) = tmp{1};\n</code></pre>\n\n<p>Be sure to <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html\" rel=\"nofollow noreferrer\">preallocate the arrays!</a> </p>\n\n<p>Next you have again two large blocks of mostly repeated code. <code>if length(file2) &lt;= length(file)</code>. You could put this into a function and call it <code>do_stuff(file,file2)</code> or <code>do_stuff(file2,file)</code> depending on which of the two is larger. But really, this might not be necessary at all with some better logic.</p>\n\n<p>To find which time stamps are closest to each other, you don't need a O(n<sup>2</sup>) algorithm. You could instead sort the two arrays of time stamps, and walk through them one by one. The algorithm might be slightly more complex, but you wouldn't need to duplicate the code.</p>\n\n<p>The other alternative is to use vectorized processing to do the O(n<sup>2</sup>) computation without using loops at all. But in modern versions of MATLAB, loops are not so slow any more, so this is not something you should be worrying about anyway. The way to speed up this loop is to <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html\" rel=\"nofollow noreferrer\">preallocate the array <code>C</code></a>.</p>\n\n<p>You can also simplify it by writing <code>C{m,k} = abs(A{k,1} - B{m,1});</code>, and removing the <code>if</code> statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T16:05:45.593", "Id": "460138", "Score": "0", "body": "Thank you. I have reduced the time by 1/10th by using the copyfile hint. Also I have changed the first part of my code related to Paths." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:20:41.200", "Id": "233974", "ParentId": "233833", "Score": "1" } }, { "body": "<p>As suggested by Cris, did the changes in path and used the hint of copy files and now the it takes around 21 seconds. Here is the solution </p>\n\n<pre><code>function image_sorting(color_img, depth_img, Openpose, selected_color, selected_depth)\n\n\nfile = dir(fullfile(depth_img, '*.timestamp'));\n\nfile2 = dir(fullfile(color_img, '*.timestamp'));\n\nfile3 = dir(fullfile(depth_img, '*.bmp'));\n\nfile4 = dir(fullfile(Openpose, '*.png'));\n\n\nfor k = 1:length(file)\n fileID = fopen(fullfile(depth_img, file(k).name),'r');\n % format longG\n A(k,:) = textscan(fileID,'%d64') ;\n fclose(fileID);\nend\n\n\nfor m = 1:length(file2)\n\n fileID2 = fopen(fullfile(color_img, file2(m).name),'r');\n %format longG\n B(m,:) = textscan(fileID2,'%d64') ;\n fclose(fileID2);\nend\n\n%%%%%% Here there are two parts. Use any of them according to conditions\nif length(file2) &lt;= length(file)\n %PART 1:- If RGB images are less than depth then use the following code\n\n for m = 1:length(file2)\n for k = 1:length(file)\n\n C{k,m} = A{k,1} - B{m,1};\n if C{k,m}&lt;0\n C{k,m} = -C{k,m};\n end\n end\n end\n\n [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns\n % V gives minimum value and X gives Index\n\n m = 1;\n copyfile(Openpose, selected_color) \n for w= X\n\n depthDataBase = file3(w).name;\n %rgbDataBase = file4(m).name;\n\n depthData = fullfile(depth_img, depthDataBase);\n %rgbData = fullfile(Openpose, rgbDataBase);\n\n imageArrayy = imread(depthData);\n %imageArrayy2 = imread(rgbData);\n\n depthData2 = fullfile(selected_depth, depthDataBase);\n imwrite(imageArrayy, depthData2);\n %rgbData2 = fullfile(selected_color, rgbDataBase);\n %imwrite(imageArrayy2, rgbData2);\n %movefile(file4, file5) \n\n\n m = m+1; % for part 2 m = m+1\n end\n\n\n %\n % PART 2:- If RGB images are more than depth then use the following code\nelse\n\n for m = 1:length(file2)\n for k = 1:length(file)\n\n C{m,k} = A{k,1} - B{m,1};\n if C{m,k}&lt;0\n C{m,k} = -C{m,k};\n end\n end\n end\n\n [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns\n % V gives minimum value and X gives Index\n\n copyfile(depth_img, selected_depth)\n for m= X\n\n %depthDataBase = file3(w).name;\n rgbDataBase = file4(m).name;\n\n %depthData = fullfile(depth_img, depthDataBase);\n rgbData = fullfile(Openpose, rgbDataBase);\n\n %imageArrayy = imread(depthData);\n imageArrayy2 = imread(rgbData);\n\n %depthData2 = fullfile(selected_depth, depthDataBase);\n %imwrite(imageArrayy, depthData2);\n rgbData2 = fullfile(selected_color, rgbDataBase);\n imwrite(imageArrayy2, rgbData2);\n\n\n w = w+1;\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T16:51:26.650", "Id": "235176", "ParentId": "233833", "Score": "0" } } ]
{ "AcceptedAnswerId": "233974", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T01:58:33.720", "Id": "233833", "Score": "3", "Tags": [ "sorting", "matlab" ], "Title": "Reduction of time for the code of sorting RGB and Depth images according to timestamp values" }
233833
<p><em>This is my first big project that I've decided to release publically. It's available on my <a href="https://github.com/Linnydude3347/delicioussoda" rel="noreferrer">Github</a>, and through <code>pip3</code>: <code>pip3 install delicioussoda</code>.</em></p> <p>This is a simple parser for robots.txt files for a website. And yes, the name "DeliciousSoda" is a play off of "BeautifulSoup".</p> <p>As I intended to keep developing and adding more features to this module, I would really appreciate some feedback on every part of my code. Here are a couple main things:</p> <ul> <li>How is my handling of ensuring the url is valid, and that the site has a robots.txt file?</li> <li>How is my use of custom exceptions?</li> <li>I've decided to use <code>__</code> before some methods only used within the class. I also do this for any variables. Is this unnecessary?</li> <li><code>get_allowed</code> and <code>get_disallowed</code> both seem unnecessarily complicated. I feel like I can accomplish the same thing with less code. Is this possible?</li> <li>How is my example usage? I use this to test the module without writing another file. Should I implement something like <a href="https://docs.python.org/3/library/unittest.html" rel="noreferrer"><code>unittest</code></a>?</li> </ul> <p>Appreciate any and all feedback provided. Thank you in advance.</p> <pre><code>""" DeliciousSoda ~~~~~~~~~~~~~ DeliciousSoda is a webscraper for robots.txt files. Basic usage: &gt;&gt;&gt; from delicioussoda import DeliciousSoda &gt;&gt;&gt; s = DeliciousSoda('https://www.google.com') &gt;&gt;&gt; s.get_allowed() ['Allow: /search/about', 'Allow: /search/static', ...] :copyright: (c) 2019 by Ben Antonellis. :license: MIT, see LICENSE for more details. """ __all__ = [ "DeliciousSoda" ] # Standard Library Imports import os from typing import List, Dict, Union import urllib.request from urllib.error import HTTPError # Install Requires import requests from requests.exceptions import SSLError class DeliciousSoda(): """ A custom robots.txt parser. Assumes ' User-agent: * '. """ def __init__(self, url=None): self.__url = url self.__robots_file = None if self.__url is not None: self.set_url(url) self.__validate_url() self.__content = self.__download_robots() def __str__(self) -&gt; str: return f"DeliciousSoda Parsing: {self.__url}" def set_url(self, url: str) -&gt; None: """ Sets DeliciousSoda to retrieve robots.txt from this url. :param url -&gt; str: Url :return: None """ if not url.endswith("robots.txt"): if url.endswith("/"): self.__url = f"{url}robots.txt" else: self.__url = f"{url}/robots.txt" else: self.__url = url self.__content = self.__download_robots() def __validate_url(self) -&gt; None: """ Checks current url's validity. :return: None """ try: response = requests.get(self.__url, timeout=5) except SSLError: raise InvalidUrlException("\n\nInvalidUrlException: Invalid Url.\n") def __download_robots(self) -&gt; List[str]: """ Downloads robots.txt file from url, loads the content from it, and returns a list of lines in the file. :return List[str]: Lines in the file """ if self.__url is not None: # Ensure url is valid # self.__validate_url() # Ensure file exists # try: self.__robots_file, _ = urllib.request.urlretrieve(self.__url, filename="page.html") except HTTPError as error: if error.code == 404: raise InvalidUrlException(f"\n\nInvalidUrlException: Site does not have a robots.txt file.\n") # Load lines and return list # with open(self.__robots_file, "r") as file: content = [line for line in file] # Remove file and return lines # os.remove(self.__robots_file) return content raise InvalidUrlException("\n\nInvalidUrlException: Invalid Url.\n") def get_sitemap(self) -&gt; Union[str, None]: """ Returns the sitemap of the webiste, None if it doesn't exist. :return Union[str, None]: Either the sitemap of robots.txt, or None """ for line in self.__content: if line.startswith("Sitemap:"): return line[9:].rstrip() return None def get_allowed(self) -&gt; List[str]: """ Gets all allowed directories for the url. :return List[str]: Allowed directories """ if self.__url is not None: allowed = [] for line in self.__content: if line == "\n": break if line.startswith("Allow:"): allowed.append(line.rstrip()[7:]) return allowed raise InvalidUrlException("\n\nInvalidUrlException: Invalid Url.\n") def get_disallowed(self) -&gt; List[str]: """ Gets all disallowed directories for the url. :return List[str]: Disallowed directories """ if self.__url is not None: disallowed = [] for line in self.__content: if line == "\n": break if line.startswith("Disallow:"): disallowed.append(line.rstrip()[10:]) return disallowed raise InvalidUrlException("\n\nInvalidUrlException: Invalid Url.\n") def get_all(self) -&gt; Dict[str, List[str]]: """ Returns a dict of both allowed and disallowed directories under User-agent: *. :return Dict[str, List[str]]: Dictionary of allowed and disallowed directories under User-agent: * """ if self.__url is not None: return { "Allow": self.get_allowed(), "Disallow": self.get_disallowed() } raise InvalidUrlException("\n\nInvalidUrlException: Invalid Url.\n") class InvalidUrlException(Exception): """ Url passed to DeliciousSoda object is `Invalid`. """ pass # Example Usage if __name__ == "__main__": __robot = DeliciousSoda("https://www.google.com") __sitemap = __robot.get_sitemap() __allowed = __robot.get_allowed() __disallowed = __robot.get_disallowed() __both = __robot.get_all() # print(__robot) # print(__sitemap) # print(__allowed) # print(__disallowed) # print(__both) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:38:25.837", "Id": "457190", "Score": "2", "body": "What documentation generator are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:42:49.433", "Id": "457212", "Score": "1", "body": "@Peilonrayz None, I write all of the documentation myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:44:12.873", "Id": "457213", "Score": "1", "body": "A document generator doesn't generate docstrings. It generates websites _from your docstrings_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T10:25:53.860", "Id": "457499", "Score": "0", "body": "Write programs that do one thing well. Does it really need to download the file, or just parse it?" } ]
[ { "body": "<p>Disclaimer: Don't know Python nor PEP 8.</p>\n\n<p>In <code>__download_robots(self)</code> you could reverse the <code>if</code> condition and return early which saves one level of indentation. </p>\n\n<pre><code>if self.__url is None:\n raise InvalidUrlException(\"\\n\\nInvalidUrlException: Invalid Url.\\n\") \n\n..the remaining code \n</code></pre>\n\n<p>this applies to <code>get_allowed(self)</code>, <code>get_disallowed(self)</code> and <code>get_all(self)</code> as well. </p>\n\n<p>In the <code>except</code> block of <code>__download_robots(self)</code> you only check for <code>if error.code == 404:</code> shouldn't you check for other error codes, like <code>401 Unauthorized</code> as well? </p>\n\n<hr>\n\n<p><code>get_disallowed(self)</code> and <code>get_allowed(self)</code> could be combined in one method in which you pass a <code>search_phrase</code> containing either <code>Allow:</code> or <code>Disallow:</code> and using the <code>len(search_phrase) + 1</code> as the array-index.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:20:09.390", "Id": "233846", "ParentId": "233841", "Score": "7" } }, { "body": "<ul>\n<li><p>I tried using <code>__</code> once and found it to produce more problems than it's worth. Take:</p>\n\n<pre><code>def __foo():\n return 'foo'\n\n\nclass Bar:\n def __init__(self):\n self.__baz = __foo()\n\n\nBar()\n</code></pre>\n\n<pre><code>NameError: name '_Bar__foo' is not defined\n</code></pre>\n\n<p>I'd suggest you follow PEP 8 and only use it for classes that <em>will be subclassed</em> and where you <em>need</em> to prevent name collisions. <code>__robot</code> in global scope isn't following the advice in <a href=\"https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow noreferrer\">PEP 8's Naming Conventions - Method Names and Instance Variables</a></p>\n\n<blockquote>\n <p>Python mangles these names with the class name: if class Foo has an attribute named <code>__a</code>, it cannot be accessed by <code>Foo.__a</code>. (An insistent user could still gain access by calling <code>Foo._Foo__a</code>.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.</p>\n \n <p>Note: there is some controversy about the use of __names (see below).</p>\n</blockquote></li>\n<li><p>Your docstrings aren't consistent, nor are they PEP 257 compliant.<br>\nYou should lint your code and use Sphinx.</p></li>\n<li>Your class seems to have a lot of noise in it because you've chosen to make it mutable. This is a poor design choice.</li>\n<li>You can <code>url.rstrip('/')</code> to remove the need for another <code>if</code> in <code>_set_url</code>.</li>\n<li>If <code>url</code> is passed to <code>DeliciousSoda</code> than you run <code>__download_robots</code> twice. This is a waste.</li>\n<li>Don't add <code>\\n</code> to exceptions. If you really want to add this mutate the <code>InvalidUrlException</code>'s <code>__init__</code>. But seriously, please don't.</li>\n<li>Don't add the name of the exception to the exception message. Python does this automagically.</li>\n<li>If I were a consumer, I would prefer to be able to distinguish between the errors your program raises. You should raise different errors when there's an invalid URL or the site doesn't have a robots.</li>\n<li><code>__download_robots</code> shouldn't be validating the URL. You should do that when you set the URL. Furthermore if your class was immutable then you could ignore all of this. Including the <code>self.__url is not None</code> part.</li>\n<li><code>__download_robots</code> seems overly engineered. You're downloading a file to your filesystem to then reading the <em>entire</em> file into memory. Clearly there's an unneeded step.</li>\n<li>You should make <code>set_url</code>, <code>__validate_url</code> and <code>__download_robots</code> become one single, <code>download_robots</code> function, not method. This function can also take an *args and **kwargs that delegates to <code>requests.get</code>.</li>\n<li>The rest of your code is how you parse the robots. At which point you may as well just make that a function and return a dictionary.</li>\n</ul>\n\n<pre><code>\"\"\"\n:copyright: (c) 2019 by Ben Antonellis, Peilonrayz.\n:license: CC BY-SA 4.0.\n\"\"\"\n\nfrom typing import List, Dict\nimport collections\nimport os\n\nfrom requests.exceptions import SSLError\nimport requests\n\n\ndef _normalize_robots_url(url: str) -&gt; str:\n url = url.rstrip('/')\n if not url.endswith('robots.txt'):\n url += \"/robots.txt\"\n return url\n\n\ndef _download_robots(url: str, *args, **kwargs) -&gt; str:\n url = _normalize_robots_url(url)\n try:\n r = requests.get(url, *args, **kwargs)\n except SSLError:\n raise InvalidUrlException(\"Invalid Url\")\n r.raise_for_status()\n return r.text\n\n\ndef _parse_robots(robots: str) -&gt; Dict[str, List[str]]:\n info: Dict[str, List[str]] = collections.defaultdict(list)\n for line in robots.split('\\n'):\n name, value, *_ = *line.split(': ', 1), None\n if name and not name.startswith('#'):\n info[name].append(value)\n return info\n\n\ndef delicious_soda(url: str, *args, **kwargs) -&gt; Dict[str, List[str]]:\n robots = _download_robots(url, *args, **kwargs)\n return _parse_robots(robots)\n\n\nclass InvalidUrlException(Exception):\n \"\"\" Url passed to DeliciousSoda object is `Invalid`. \"\"\"\n pass\n\n\n# Example Usage\nif __name__ == \"__main__\":\n robots = delicious_soda(\"https://www.google.com\")\n print(robots.keys())\n print(robots['Sitemap'])\n print(robots['User-agent'])\n print(robots['Allow'])\n print(robots['Disallow'])\n</code></pre>\n\n<hr>\n\n<p>Given the above functions I still have some concerns.</p>\n\n<ol>\n<li><p>I personally consider calling <code>_normalize_robots_url</code> inside <code>_download_robots</code> an anti-pattern. The <em>normalizing in fetch</em> anti-pattern if you will.</p>\n\n<p>You should normalize your data before you perform the fetch. If I'm asking for <code>example.com/robots-new.txt</code> then I should have a pretty good reason to. Your 'help' of then appending <code>/robots.txt</code> to the end of <em>my valid url</em> has caused me needless problems.</p>\n\n<p>I recommend exposing <code>_normalize_robots_url</code> as a function that people can call <em>if</em> they want that behavior.</p></li>\n<li><p>I also find <code>delicious_soda</code> to be an anti-pattern. The <em>fetch and parse</em> anti-pattern if you will.</p>\n\n<p>This is bad as it needlessly locks users into one usage. What if I want to cache the fetch, what if I need to stream it, what if I need to handle user authentication. What if I need to do something with the fetch <em>you can't think of</em>? At that point I can't use your library.</p>\n\n<p>IMO a library provider always needs to provide fetching and parsing as two separate entities. The cost to most users is having to do <code>parse(fetch())</code>. If you want to expose a helper function too, that's cool, but not exposing both as separate things is just bad.</p></li>\n<li><p>The function <code>_parse_robots</code> seems like the best part of the library. Whilst the way you implemented it in <code>DeliciousSoda</code> isn't great. It's the best part of the library.</p>\n\n<p>But I don't think it's great as a stand alone library, as I've implemented most of the features in a 7 line function, which I'd hope most Python programmers could mimic with ease.</p></li>\n</ol>\n\n<p>In all currently the library is just a 7 line function - <code>_parse_robots</code>. I don't think <code>_download_robots</code> is great as part of the library. I'd elect to just use <code>requests</code> which is more powerful and I know it won't break when I enter valid urls.</p>\n\n<p>I would suggest expanding on <code>_parse_robots</code> in a way that makes the library somewhat more usable. Say converting it into a class and adding a <code>DS.allowed_url</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T04:19:50.193", "Id": "457325", "Score": "0", "body": "You've given me a lot to think about and improve upon. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:37:59.337", "Id": "457345", "Score": "1", "body": "When I read through the code I wondered why you kept \"normalize\", \"fetch\" and \"parse\" module privates. Further points expand on that and I'd add that, since `delicious_soda` is just an helper function, you can add a `normalize_url=True` parameter on top of moving the normalize call here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:03:34.567", "Id": "457349", "Score": "0", "body": "@409_Conflict I think moving the normalize into the helper with that flag could be a pretty good solution too. +1 Yeah, I thought explicitly stating why removing that `_` makes such a big difference to the general design would help a lot (even though the anti-patterns are basically just instances of \"no god-classes\" and SRP)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:44:20.807", "Id": "233850", "ParentId": "233841", "Score": "13" } } ]
{ "AcceptedAnswerId": "233850", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T05:44:26.430", "Id": "233841", "Score": "10", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "DeliciousSoda: A simple parser for robots.txt files" }
233841
<p>I'm writing a toy vector library in C to learn a bit about the language. The excerpt below shows my vector structure and two functions:</p> <ul> <li><code>vec2_magnitude</code> calculates the magnitude (length) of a vector</li> <li><code>vec2_unit</code> uses the magnitude to calculate the unit vector</li> </ul> <pre class="lang-c prettyprint-override"><code>#include &lt;math.h&gt; // A fixed-length vector w/ 2 elements. typedef struct { double a; double b; } vec2_t; // Compute the magnitude of a vec2_t. double vec2_magnitude(const vec2_t *vec) { double a2 = vec-&gt;a * vec-&gt;a; double b2 = vec-&gt;b * vec-&gt;b; return sqrt(a2 + b2); } // Compute the unit vector of a vec2_t. void vec2_unit(const vec2_t *vec, vec2_t *unit) { double mag = vec2_magnitude(vec); unit-&gt;a = (vec-&gt;a / mag); unit-&gt;b = (vec-&gt;b / mag); } </code></pre> <p>Currently, <code>vec2_unit</code> takes two vector arguments. It performs the calculation based on the first argument, then stores its result in the second argument. I wrote the function this way so the original vector wouldn't be affected (in case it is still needed).</p> <p>That being said, I'd like a way to calculate the unit vector in-place, since you may not always need the old vector (in such a situation, an in-place calculation is more convenient). I was originally going to write two functions, but noticed a clever way to achieve both functionalities using only the function shown above.</p> <p>To operate non-destructively, <code>vec2_unit</code> can be called like this:</p> <pre class="lang-c prettyprint-override"><code>vec2_t orig_vector = {1, 1}; vec2_t unit_vector; vec2_unit(orig_vector, unit_vector); </code></pre> <p>To operate in-place, <code>vec2_unit</code> can be called like this:</p> <pre class="lang-c prettyprint-override"><code>vec2_t orig_vector = {1, 1}; vec2_unit(orig_vector, orig_vector); </code></pre> <p>I like this solution, and it seems to work. I also understand that C is a language where many things aren't "safe", and just because you can do something doesn't mean you should. Are there any reasons something like this shouldn't be done? Are there other examples of common C functions that work in a similar way? Is there a better way to accomplish what I'm trying to do?</p> <p>I appreciate all help. Feel free to comment on anything else you see as well. Thanks!</p>
[]
[ { "body": "<p>Personaly I would put the non constant argument first:</p>\n\n<p>I would also check for the first argument for being null too.</p>\n\n<p>And you can define a shortcut function for passing the same argument twice.</p>\n\n<pre><code>double vec2_magnitude(const vec2_t *vec)\n{\n if (vec == NULL) return NaN;\n double a2 = vec-&gt;a * vec-&gt;a;\n double b2 = vec-&gt;b * vec-&gt;b;\n return sqrt(a2 + b2);\n}\n\nint vec2_unit(vec2_t * unit, const vec2_t * vec)\n{\n if (unit == NULL) return -1;\n double mag = vec2_magnitude(vec);\n if (mag == 0.0 || isnan(mag)) return -1;\n unit-&gt;a = (vec-&gt;a / mag);\n unit-&gt;b = (vec-&gt;b / mag);\n return 0;\n}\n\nint vec2_norm(vec2_t * vec)\n{\n return vec2_unit(vec, vec);\n}\n</code></pre>\n\n<p>Further, division by zero is forbidden and so I check for that as well...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:17:27.590", "Id": "233845", "ParentId": "233844", "Score": "4" } }, { "body": "<ul>\n<li><p>It is custom/industry de facto standard to place the parameter to be changed first, as done in <code>memcpy</code>, <code>strcpy</code> etc (this tradition goes all the way back to assembler).</p>\n\n<p>So you should do <code>void vec2_unit (vec2_t* dst, const vec2_t* src);</code>.</p></li>\n<li><p>Regarding in-place or not, it is mostly a matter of style in this case. </p>\n\n<p>Functions/APIs working on \"immutable\" objects (objects not modified by the function) are often considered better style when that option is available, since that minimizes the chance of caller-side bugs.</p>\n\n<p>The discussion about in-place vs immutable mostly makes sense for larger data types, where taking a copy of the data object is regarded as costly. A struct with 2 <code>double</code> isn't really that heavy to copy<sup>(note 1)</sup>, so you could design this API with an immutable object interface. You could even get away with passing the structs to/from the functions by value, which is otherwise normally frowned upon.</p>\n\n<p>Note: if these functions will reside in the same translation unit as the caller code (which doesn't seem likely here?), the whole discussion about performance is pointless since they will be inlined anyway in that case.</p></li>\n<li><p>If you go for the immutable version, it could be written as</p>\n\n<p><code>void vec2_unit (vec2_t* restrict dst, const vec2_t* restrict src);</code></p>\n\n<p>This tells the compiler and the caller both that these two objects shall <em>not</em> be the same one. That will in turn increase performance, but it will not allow you to pass the same object as both source and destination.</p></li>\n</ul>\n\n<hr>\n\n<p><sup>(note 1)</sup> We can assume that systems using <code>double</code> are able to copy it in a few instructions. Systems where copying a <code>double</code> would be lots of work, such as small microcontroller systems, shouldn't be using <code>double</code> (or <code>float</code>) in the first place, since they lack a FPU. I would safely assume that any program using floating point is meant to run on a Cortex M3 or bigger. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:07:25.763", "Id": "457419", "Score": "0", "body": "`vec2_unit (vec2_t* restrict dst, const vec2_t* restrict src);` also implies there is no overlap either, not only `dst != src`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:01:48.527", "Id": "457431", "Score": "0", "body": "\"You could even get away with passing the structs to/from the functions by value, ...\" --> Agree, especially when the objects represent a \"number\" as most `<math.h>` functions/parameters use this model." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:15:36.567", "Id": "233851", "ParentId": "233844", "Score": "9" } }, { "body": "<p>In general you can \"remove\" const legally if the original variable wasn't declared const, ie.</p>\n\n<pre><code>int a;\nconst int c;\n\nvoid foo(const int *x)\n{\n int *p = (int *)x;\n p++;\n}\n\nfoo(&amp;a); // legal\nfoo(&amp;c); // illegal\n</code></pre>\n\n<p>The rationale is that const-variables are often declared in read-only memory segments. As far as I know, the compiler is not allowed more than that (<code>const</code> doesn't have much impact in C, Ritchie even didn't want it included in C). Additionally the compiler cannot assume that the memory areas do <em>not</em> overlap (because they aren't declared as <code>restrict</code>), so this code should be completely legal and even safe as it is only illegal if the argument was defined to be <code>const</code>:</p>\n\n<pre><code>const vec2_t v;\nvec2_unit(&amp;v, &amp;v);\n</code></pre>\n\n<p>But then it should warn about the second argument discarding <code>const</code>.</p>\n\n<p>Additional note: <code>vec2_t</code> is a reserved type by POSIX, as are all types with suffix <code>_t</code>, you are encouraged to use a different type name.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:25:00.537", "Id": "457488", "Score": "0", "body": "@chux-ReinstateMonica Ah, I've missed the `&`, thanks for pointing out!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:24:55.230", "Id": "233852", "ParentId": "233844", "Score": "3" } }, { "body": "<p>Instead of summing squares manually and passing to <code>sqrt()</code>, we should be using the <strong><code>hypot()</code></strong> function. That's functionally similar, but has better guarantees of accuracy and correctness (particularly when faced with unusual inputs, such as subnormals).</p>\n\n<pre><code>double vec2_magnitude(const vec2_t *vec)\n{\n return hypot(vec-&gt;a, vec-&gt;b);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:46:03.450", "Id": "233855", "ParentId": "233844", "Score": "7" } }, { "body": "<p>It is not uncommon for C API functions to simply branch if <code>NULL</code> pointers are received. Consider the following:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void vec2_unit(vec2_t *vec, vec2_t* unit)\n{\n double mag = vec2_magnitude(vec);\n\n if(unit == NULL){\n vec-&gt;a /= mag;\n vec-&gt;b /= mag;\n return;\n }\n\n unit-&gt;a = vec-&gt;a / mag;\n unit-&gt;b = vec-&gt;b / mag;\n}\n</code></pre>\n\n<p>Here you update the <code>unit</code> vector only if it is supplied. Otherwise <code>vec</code> is updated. If you wanted to be more verbose, you could also consider:</p>\n\n<pre><code>// You can name this macro whatever you'd like\n#define PERFORM_OP_INPLACE NULL\n\nint main(){\n vec2_t vec = {1.0, 1.0};\n\n vec2_unit(&amp;vec, PERFORM_OP_INPLACE);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:35:11.973", "Id": "457424", "Score": "0", "body": "Instead of `if(unit == NULL){\n vec->a /= mag;\n vec->b /= mag;\n return;\n }`, coudl use `if(unit == NULL){ vec = unit; }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:27:57.983", "Id": "457449", "Score": "0", "body": "@chux-ReinstateMonica True, but it would actually be `if(unit == NULL){ unit = vec; }` and the you can edit `unit`. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:29:58.983", "Id": "457450", "Score": "0", "body": ".backwards that had I Yes" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:19:34.663", "Id": "233890", "ParentId": "233844", "Score": "4" } } ]
{ "AcceptedAnswerId": "233851", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T06:34:04.420", "Id": "233844", "Score": "11", "Tags": [ "c" ], "Title": "Toy Vector Library - Magnitude & Unit Vector Functions" }
233844
<p>Here is my code:</p> <pre><code>defmodule LineScanner do @spec scan(String.t()) :: [Token.t()] def scan(line) when is_binary(line), do: scan_(line, {[], ""}) |&gt; Enum.reverse() ### The function below needs some refactoring ###### @spec scan_(String.t(), {[Token.t()], binary()}) :: [Token.t()] def scan_(line, {acc, fragments}) when is_binary(line) do case token(line, fragments) do {nil, "", f} -&gt; [%TextNode{text: f} | acc] {nil, rest, f} -&gt; scan_(rest, {acc, f}) {t, "", ""} -&gt; [t | acc] {t, "", f} -&gt; [t | [%TextNode{text: f} | acc]] {t, rest, "" = f} -&gt; scan_(rest, {[t | acc], f}) {t, rest, f} -&gt; scan_(rest, {[t | [%TextNode{text: f} | acc]], ""}) end end ##################################################### @spec token(String.t(), binary()) :: {Token.t(), String.t()} def token(&lt;&lt;c::utf8, rest::binary&gt;&gt;, fragments) do case c do ?# -&gt; {%Header{}, rest, fragments} ?&gt; -&gt; {%BlockQuoteCaret{}, rest, fragments} x when x in [?-, ?*] -&gt; {%Bullet{}, rest, fragments} ?` -&gt; {%BackTick{}, rest, fragments} _ = cp -&gt; {nil, rest, fragments &lt;&gt; &lt;&lt;cp&gt;&gt;} end end end </code></pre> <p>A brief synopsis. I'm building a scanner for Markdown syntax. It needs to pick up significant tokens but also intermediary text fragments.</p> <p>Given that <code>token()</code> returns a 3-tuple, my case statement will need to test 2^3 combination. Since the <code>nil</code> case only ever returns a non-empty string, 2 of those are automatically eliminated, leaving the 6 below. But it is still rather clunky. This is what's going on: </p> <ol> <li>A text fragment exists, but the end of the line has been reached. RETURN: the accumulator + text node</li> <li>A text fragment exists RETURN: another call to scan</li> <li>A token has been found at the end of the line. RETURN: the accumulator + token</li> <li>A token has been found at the end of the line AND a text fragment exists. RETURN: The accumulator + text node + token</li> <li>A token has been found and there is not fragment RETURN: another call to scan with the new token added to the accumulator</li> <li>A token has been found AND there is a text fragment RETURN: another call to scan with the token and text node added to the accumulator</li> </ol> <p>I'm racking my brain to figure out how to slim this down, but every case seems significant. Please help.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T07:59:41.290", "Id": "233847", "Score": "5", "Tags": [ "parsing", "reinventing-the-wheel", "elixir", "lexer" ], "Title": "Scanning a string into a list of tokens" }
233847
<p>This is a follow-up on <a href="https://codereview.stackexchange.com/q/233770/214731">Change size of elements until parent reaches certain height</a></p> <p>The goal of the function is to find a size for the elements inside a parent, so they all fit in a single row. I tried it with a loop (check previous question), and now I changed it to if statements. However I would like to simplify it, but I can't find how. The Size of the elements don't have to be exactly how they are now. The default size is <code>width: 10px; height: 10px; margin: 5px 7px</code>, which is a total of <code>24px</code> wide.</p> <pre><code>function _AdjustHeightOwlDots(id) { const thisElementId = `owl-carousel-${id}`; const dotRowWidth = $(`#${thisElementId} .owl-dots`).width(); const amountOfDots = document.querySelector(`#${thisElementId} .owl-dots`).childElementCount; const singleDotWidth = $(`#${thisElementId} .owl-dots &gt; button`).width(); if ( (singleDotWidth * amountOfDots) &lt; dotRowWidth ) { // dots fit in single row return; } let maxDotWidth = Math.floor(dotRowWidth / amountOfDots); const setNewStyle = function(hw, margin) { $(`#${thisElementId} div.owl-dots &gt; button &gt; span`).css('width', `${hw}px`); $(`#${thisElementId} div.owl-dots &gt; button &gt; span`).css('height', `${hw}px`); $(`#${thisElementId} div.owl-dots &gt; button &gt; span`).css('margin', `5px ${margin}px`); } if (maxDotWidth % 2 === 1) { maxDotWidth -= 1; } // A/B // width = Apx // height = Apx // margin = 5px Bpx if (maxDotWidth &lt;= 3) { // set to 1/1 setNewStyle(1, 1); } else if (maxDotWidth === 4) { // set to 2/1 setNewStyle(2, 1); } else if (maxDotWidth === 6) { // set to 2/2 setNewStyle(2, 2); } else if (maxDotWidth === 8) { // set to 4/2 setNewStyle(4, 2); } else if (maxDotWidth === 10) { // set to 4/3 setNewStyle(4, 3); } else if (maxDotWidth === 12) { // set to 6/3 setNewStyle(6, 3); } else if (maxDotWidth === 14) { // set to 6/4 setNewStyle(6, 4); } else if (maxDotWidth === 16) { // set to 8/4 setNewStyle(8, 4); } else if (maxDotWidth === 18) { // set to 8/5 setNewStyle(8, 5); } else if (maxDotWidth === 20) { // set to 10/5 setNewStyle(10, 5); } else if (maxDotWidth === 22) { // set to 10/6 setNewStyle(10, 6); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:34:24.587", "Id": "457210", "Score": "0", "body": "What is `{{!block.id}}`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:58:10.320", "Id": "457220", "Score": "0", "body": "@RoToRa It's a python variable from the templating engine. I removed it from the code it was confusing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:19:45.403", "Id": "457235", "Score": "0", "body": "Please don't change code after posting it. My review referrers to it." } ]
[ { "body": "<p>Using a template variable in the script means you have this script in the HTML document and repeat it for each owl carousel. That is a vary bad idea, mostly because that way you may have multiple functions with the same name. </p>\n\n<p>Generally your HTML shouldn't \"know about\" (reference) your JavaScript. Instead the JavaScript should find the elements it wants to attach itself to.</p>\n\n<p>Put the function in a separate script file (together with all of your other scripts, wrapped in an <a href=\"https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript\">IIFE</a>) and include it once with <code>&lt;script src=\"...\"&gt;</code> at the end of the HTML.</p>\n\n<p>Then place a class on all owl carousels you want to apply the function to and use that to call the script for all and any elements with this class. For example, with jQuery:</p>\n\n<pre><code>(function() {\n\n $('.owl-carousel--adjust-height').each(function () {\n _AdjustHeightOwlDots($(this));\n };\n\n function _AdjustHeightOwlDots(owlCarousel) {\n // ...\n }\n\n})();\n</code></pre>\n\n<p>Now, inside \"find\" the sub elements (and save references to avoid duplicate queries of the same elements):</p>\n\n<pre><code>const dots = owlCarousel.find('.owl-dots');\nconst dotRowWidth = dots.width();\nconst amountOfDots = dots[0].childElementCount;\nconst dotButtons = dots.find('&gt; button');\nconst singleDotWidth = dotButtons.width();\n</code></pre>\n\n<p>(You learn new things every day. Never heard of <code>childElementCount</code> before this - and it's not even a new thing.)</p>\n\n<p>In <code>setNewStyle</code> the query is also repeated and can be replaced with chaining (or the alternative syntax for <code>.css()</code> using an object) and also can be moved outside the function:</p>\n\n<pre><code>const dotButtonSpans = dotButtons.find('&gt; span');\n\nconst setNewStyle = function(hw, margin) {\n dotButtonSpans\n .css('width', `${hw}px`)\n .css('height', `${hw}px`)\n .css('margin', `5px ${margin}px`);\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>const setNewStyle = function(hw, margin) {\n dotButtonSpans.css({\n width: `${hw}px`, \n height: `${hw}px`, \n margin: `5px ${margin}px`\n });\n}\n</code></pre>\n\n<p>Finally the big if block can be replaced with a simple calculation (including removing the part that makes <code>maxDotWidth</code> even, instead using <code>| 0</code> as a short cut to round numbers to integers):</p>\n\n<pre><code>const size = ((maxDotWidth / 4) | 0) + 1;\nconst margin = maxDotWidth &lt; 2 ? 1 : (((maxDotWidth - 2) / 4) | 0) + 1;\n\nsetNewStyle(size , margin);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:24:41.820", "Id": "457265", "Score": "0", "body": "Hey thanks for the response, I implemented your feedback, however I changed the calculations of the size to `const size = maxDotWidth <= 2 ? 1 : (maxDotWidth - margin * 2)`; this way I don't waste any pixels!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:16:50.283", "Id": "233862", "ParentId": "233848", "Score": "3" } }, { "body": "<p>Some remarks on chains of <code>if (...) else if (...)</code> calling same function. You can replace them with <code>swich case</code> which also is not ideal. What I like to do is something like this:</p>\n\n<pre><code>let styleDataList = {\n 4: { hw: 2, margin: 1 },\n 6: { hw: 4, margin: 2 },\n 8: { hw: 4, margin: 2 },\n 10: { hw: 4, margin: 3 },\n 12: { hw: 6, margin: 3 },\n 14: { hw: 6, margin: 4 },\n 16: { hw: 8, margin: 4 },\n 18: { hw: 8, margin: 5 },\n 20: { hw: 10, margin: 5 },\n 22: { hw: 10, margin: 6 }\n};\n\nlet styleData = styleDataList[maxDotWidth] || { hw: 1, margin: 1 };\nsetNewStyle( styleData );\n</code></pre>\n\n<p>But yes, as @RoToRa pointed out - this whole structure can most likely be reduced to a simple calculation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:24:25.317", "Id": "233874", "ParentId": "233848", "Score": "2" } } ]
{ "AcceptedAnswerId": "233862", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T08:34:59.933", "Id": "233848", "Score": "2", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Find size for elements to fit in certain width" }
233848
<p>I have written a code for my little little website to make it multilanguage. It is a simple "developer" page where you can select from four different languages. Hungarian, English, Deutch and Roman. Then i wanted to modify all the words each by each in a table like div on the page and then save it on my backend. So I did.</p> <p><strong>How code works on theory:</strong></p> <p>The words on my page coming from an object array from javascript first. If there is no saved file on the backend. After that if the user open the table up, the javascript generates a table element from that javascript object where all the words are. And if everything is okay ( usually is ) the user can modify the existing words on the page in a table. If the user clicks save, the words are going to my backend in a post request to be saved and if it is saved the backend immediately sends the words back and the js put it into the object array because it is modified and do the translate in the page as well from the object array.</p> <p><strong>The asking:</strong></p> <p>So I'm not very experienced programmer. I've written this little thing but it is bleeding from every possible line. I don't know how to work properly with objects and such things like that in javascript. So if somebody can review the code snippets and can give me some suggestions on how or where to improve it i would be very glad.</p> <p><strong>The HTML side:</strong></p> <pre><code>&lt;div class="column"&gt; &lt;h2 class="lang" key="LANGUAGES"&gt;Languages&lt;/h2&gt; &lt;p class="btn-group"&gt; &lt;button onclick="location.href='/magyar';" class="translate Button_OK" key=HUN ID=HU&gt;&lt;i class="icon-hu"&gt;&lt;/i&gt;HU&lt;/button&gt; &lt;button onclick="location.href='/angol';" class="translate Button_OK" key=ENG ID=EN&gt;&lt;i class="icon-en"&gt;&lt;/i&gt;EN&lt;/button&gt; &lt;button onclick="location.href='/nemet';" class="translate Button_OK" key=DEU ID=DE&gt;&lt;i class="icon-de"&gt;&lt;/i&gt;DE&lt;/button&gt; &lt;button onclick="location.href='/roman';" class="translate Button_OK" key=ROM ID=RO&gt;&lt;i class="icon-ro"&gt;&lt;/i&gt;RO&lt;/button&gt; &lt;/p&gt; &lt;button id="LangDivBTN" class="Button_OK lang" key=SHWTAB&gt;Szavak Módosítása&lt;/button&gt; &lt;/div&gt; </code></pre> <p><strong>The Javascript side:</strong></p> <p>The BASIC multilanguage JavaScript ( I'am using jquery and the html elements contains the ".lang" class and an ID for that word. the Set_Actual_Language function is running onload() )</p> <pre><code>/** LANGUAGE SETTINGS **/ var arrLang={ /*********************************************** MAGYAR ***********************************************/ HU:{ /****************** Tag Panel ******************/ "RFID" : "Beléptető Rendszer", "RECRUIT" : "Tag Felvétel", "DELETE" : "Tag Törlése", /****************** Tag Panel ******************/ /****************** Dev Panel ******************/ "DEVPAGE" : "Fejlesztői Lap", "DEBUG" : "Debug Ablak", "GFUP" : "Általános File Feltöltés", "FFUP" : "Firmware/SPIFFS Feltöltés(SPIFFS formázással)", "FDOWNLOAD" : "File Letöltések", "CUSFDOWN" : "Egyéni File Letöltés", /****************** Dev Panel ******************/ /****************** Set Panel ******************/ "SETTING" : "Beállítások", "LANGUAGES" : "Nyelvek", "RTCTIME" : "RTC Idő", "APMANAGE" : "Access Point Kezelés", "ETHMANAGE" : "Ethernet Kezelés", "WRDSMANG" : "Szavak Kezelése", "FDEL" : "Egyéni File Törlés", /****************** Set Panel ******************/ /****************** Inf Panel ******************/ "INFORM" : "Információk", "ACCESS" : "Elérhetőség", "ETHINFORM" : "Jelenlegi Ethernet Információk", "APINFORM" : "Jelenlegi Access Point Információk", "LICENSE" : "Licensz", /****************** Inf Panel ******************/ /****************** Buttons ******************/ "DELBTN" : "Törlés", "SETBTN" : "Beállít", "DEFBTN" : "Alapértelmezett", "CLR" : "Tisztítás", "TEMP" : "Hőmérséklet", "ALLF" : "Minden File", "LOGF" : "Log Fileok", "REQBTN" : "Lekérés", "RECRBTN" : "Felvétel", "SAVEBTN" : "Mentés", /****************** Buttons ******************/ }, /*********************************************** ANGOL ***********************************************/ EN:{ /****************** Tag Panel ******************/ "RFID" : "Access Control System", "RECRUIT" : "Tag Recruit", "DELETE" : "Tag Delete", /****************** Tag Panel ******************/ /****************** Dev Panel ******************/ "DEVPAGE" : "Development Page", "DEBUG" : "Debug Window", "GFUP" : "General File Upload", "FFUP" : "Firmware/SPIFFS Upload(With SPIFFS Erase)", "FDOWNLOAD" : "File Downloads", "CUSFDOWN" : "Custom File Download", /****************** Dev Panel ******************/ /****************** Set Panel ******************/ "SETTING" : "Settings", "LANGUAGES" : "Languages", "RTCTIME" : "RTC Time", "APMANAGE" : "Access Point Manage", "ETHMANAGE" : "Ethernet Manage", "WRDSMANG" : "Manage Words", "FDEL" : "Custom File Delete", /****************** Set Panel ******************/ /****************** Inf Panel ******************/ "INFORM" : "Information", "ACCESS" : "Accessibility", "ETHINFORM" : "Current Ethernet Information", "APINFORM" : "Current Access Point Information", "LICENSE" : "License", /****************** Inf Panel ******************/ /****************** Buttons ******************/ "DELBTN" : "Delete", "SETBTN" : "Set", "DEFBTN" : "Default", "CLR" : "Clear", "TEMP" : "Temperature", "ALLF" : "All Files", "LOGF" : "Log Files", "REQBTN" : "Request", "RECRBTN" : "Recruit", "SAVEBTN" : "Save", /****************** Buttons ******************/ }, /*********************************************** NÉMET ***********************************************/ DE:{ /****************** Tag Panel ******************/ "RFID" : "Zugriffskontroll", "RECRUIT" : "Tag Rekrutieren", "DELETE" : "Tag Löschen", /****************** Tag Panel ******************/ /****************** Dev Panel ******************/ "DEVPAGE" : "Entwicklungsseite", "DEBUG" : "Debug Fenster", "GFUP" : "Allgemeines Hochladen von Dateien", "FFUP" : "Firmware/SPIFFS hochladen(SPIFFS Formatierung)", "FDOWNLOAD" : "File Downloads", "CUSFDOWN" : "Brauch File Download", /****************** Dev Panel ******************/ /****************** Set Panel ******************/ "SETTING" : "die Einstellungen", "LANGUAGES" : "Sprachen", "RTCTIME" : "RTC Zeit", "APMANAGE" : "Access Point verwalten", "ETHMANAGE" : "Ethernet verwalten", "WRDSMANG" : "Szavak Kezelése", "FDEL" : "Custom File Delete", /****************** Set Panel ******************/ /****************** Inf Panel ******************/ "INFORM" : "Information", "ACCESS" : "Zugänglichkeit", "ETHINFORM" : "Aktuell Ethernet Information", "APINFORM" : "Aktuell Access Point Information", "LICENSE" : "Lizenz", /****************** Inf Panel ******************/ /****************** Buttons ******************/ "DELBTN" : "löschen", "SETBTN" : "einstellen", "DEFBTN" : "Standard", "CLR" : "klar", "TEMP" : "Temperatur", "ALLF" : "Alle Dateien", "LOGF" : "Log Files", "REQBTN" : "anfordern", "RECRBTN" : "rekrutieren", "SAVEBTN" : "Save", /****************** Buttons ******************/ }, /*********************************************** ROMÁN ***********************************************/ RO:{ /****************** Tag Panel ******************/ "RFID" : "Sistem de control al accesului", "RECRUIT" : "Înregistrare de etichete", "DELETE" : "Membru Șterge", /****************** Tag Panel ******************/ /****************** Dev Panel ******************/ "DEVPAGE" : "Pagina dezvoltatorului", "DEBUG" : "Fereastra de depanare", "GFUP" : "Încărcare generală de fișiere", "FFUP" : "Firmware/SPIFFS umplere(SPIFFS formatare)", "FDOWNLOAD" : "Descărcări de fișiere", "CUSFDOWN" : "Descărcare personalizată de fișiere", /****************** Dev Panel ******************/ /****************** Set Panel ******************/ "SETTING" : "setări", "LANGUAGES" : "limbi", "RTCTIME" : "RTC timp", "APMANAGE" : "Access Point administrare", "ETHMANAGE" : "Ethernet administrare", "WRDSMANG" : "Managementul cuvintelor", "FDEL" : "Ștergere fișier personalizate", /****************** Set Panel ******************/ /****************** Inf Panel ******************/ "INFORM" : "informații", "ACCESS" : "disponibilitate", "ETHINFORM" : "Informații Ethernet curente", "APINFORM" : "Informații curente despre punctul de acces", "LICENSE" : "licențiere", /****************** Inf Panel ******************/ /****************** Buttons ******************/ "DELBTN" : "anulare", "SETBTN" : "regla", "DEFBTN" : "lipsă", "CLR" : "curățenie", "TEMP" : "temperatură", "ALLF" : "Toate fișierele", "LOGF" : "Fișiere jurnal", "REQBTN" : "Cerere", "RECRBTN" : "Recruta", "SAVEBTN" : "salva", /****************** Buttons ******************/ } }; // The default language is Hungarian function Set_Actual_Language(){ var lang = "HU"; // Check for localStorage support if('localStorage' in window){ var usrLang = localStorage.getItem('uiLang'); if(usrLang) { lang = usrLang } } console.log(lang); $(document).ready(function() { $(".lang").each(function(index, element) { $(this).text(arrLang[lang][$(this).attr("key")]); }); }); $(".translate").click(function() { var lang = $(this).attr("id"); if('localStorage' in window){ localStorage.setItem('uiLang', lang); BejelFordit = localStorage.getItem('uiLang'); } $(".lang").each(function(index, element) { $(this).text(arrLang[lang][$(this).attr("key")]); }); }); } /** LANGUAGE SETTINGS END **/ </code></pre> <p>When the user click on the Modify Words button on the HTML side this function is called to create the table: ( Because the div is display="none" at first )</p> <p>I don't know how else would i determine the ID-s inside the object so i created an array with the ID-s and do a loop with its help to determine where and what ID is it. It is really not efficient because i have to modify this array with the object array too if i want new words in the site. And a couple of more reasons.</p> <pre><code>function Create_Table(){ var tbody = document.getElementById('tbody'); var TAGS = ["RFID","RECRUIT","DELETE","DEVPAGE","DEBUG","GFUP","FFUP","FDOWNLOAD","CUSFDOWN","SETTING","LANGUAGES","RTCTIME","APMANAGE","ETHMANAGE","WRDSMANG","FDEL","INFORM","ACCESS","ETHINFORM","APINFORM","LICENSE","DELBTN","SETBTN","DEFBTN","CLR","TEMP","ALLF","LOGF","REQBTN","RECRBTN","SAVEBTN"]; var Table_Lang = "&lt;tr&gt; &lt;th&gt;HU&lt;/th&gt; &lt;th&gt;EN&lt;/th&gt; &lt;th&gt;DE&lt;/th&gt; &lt;th&gt;RO&lt;/th&gt;&lt;/tr&gt;"; for(var i = 0; i &lt; TAGS.length;i++){ Table_Lang += "&lt;tr&gt;"; Table_Lang += "&lt;td style='text-shadow: none' contenteditable='true'&gt;" + arrLang.HU[TAGS[i]] + "&lt;/td&gt;"; Table_Lang += "&lt;td style='text-shadow: none' contenteditable='true'&gt;" + arrLang.EN[TAGS[i]] + "&lt;/td&gt;"; Table_Lang += "&lt;td style='text-shadow: none' contenteditable='true'&gt;" + arrLang.DE[TAGS[i]] + "&lt;/td&gt;"; Table_Lang += "&lt;td style='text-shadow: none' contenteditable='true'&gt;" + arrLang.RO[TAGS[i]] + "&lt;/td&gt;"; Table_Lang += "&lt;/tr&gt;"; } tbody.innerHTML = Table_Lang; } </code></pre> <p>So the table gets created and you can see the words inside it from the object array.</p> <p>Here is a picture from the table</p> <p><img src="https://i.stack.imgur.com/2IcB6.png" alt=""></p> <p>And you can modify the words like in this picture</p> <p><img src="https://i.stack.imgur.com/JFcSW.png" alt=""></p> <p>After all that if the user modifying any words and hits save button, this function is called: ( This function gets the rows and cells from the table and put it in different arrays. This is required for me on my backend because i want to arrange the words on the array in columns. like "HU","WORDS" etc... "DE","WORDS" etc... Not in rows. I want to save my backend from any heavy load like this.</p> <pre><code>function Save_Table(){ var Element_Lang_Names = []; var HU_Elems = []; var EN_Elems = []; var DE_Elems = []; var RO_Elems = []; var oTable = document.getElementById('tbody'); var rowLength = oTable.rows.length; var ElementCounter = 0; for (i = 0; i &lt; rowLength; i++){ var oCells = oTable.rows.item(i).cells; var cellLength = oCells.length; for(var j = 0; j &lt; cellLength; j++){ if(j == 0){ HU_Elems[ElementCounter] = oCells.item(j).innerHTML; }else if(j == 1){ EN_Elems[ElementCounter] = oCells.item(j).innerHTML; }else if(j == 2){ DE_Elems[ElementCounter] = oCells.item(j).innerHTML; }else if(j == 3){ RO_Elems[ElementCounter] = oCells.item(j).innerHTML; } ElementCounter++; } } var multipleArrays = [HU_Elems,EN_Elems,DE_Elems,RO_Elems]; var Element_Lang_Names = [].concat.apply([], multipleArrays); Post_Lang(Element_Lang_Names); } function Post_Lang(Elements){ //console.log(Elements); $.post("Save_Lang_Data",{Elements}, function(data,status){console.log("Data: " + data + "Status: "+ status);}); } </code></pre> <p>Okay , if the data saved the backend almost imidiatelly respond back to me not in the post request but in a websocket call on other part of the script. This is not meaningful here. After that the backend puts back the saved data and this function is called:</p> <p>This is one of the ugliest thing i or anyone done. On the save function the data gets corrupted. There are empty variables on the array and all the data gets saved like this. So when i read it back from the backend i have to split it to different arrays to clean them up a little bit.</p> <pre><code>function Get_Language_Object(Lang_Array){ var Lang_Array1 = Lang_Array.split(","); var HU_Langs = []; var EN_Langs = []; var DE_Langs = []; var RO_Langs = []; for(var i = 0; i &lt; Lang_Array1.length;i++){ if(Lang_Array1[i] != "EN"){ if(Lang_Array1[i] != ""){ HU_Langs[i] = Lang_Array1[i]; } }else{ for(i;i &lt; Lang_Array1.length;i++){ if(Lang_Array1[i] != "DE"){ if(Lang_Array1[i] != ""){ EN_Langs[i] = Lang_Array1[i]; } }else{ for(i;i &lt; Lang_Array1.length;i++){ if(Lang_Array1[i] != "RO"){ if(Lang_Array1[i] != ""){ DE_Langs[i] = Lang_Array1[i]; } }else{ for(i;i &lt; Lang_Array1.length;i++){ if(Lang_Array1[i] != ""){ RO_Langs[i] = Lang_Array1[i]; } } break; } } break; } } break; } } var TAGS = ["RFID","RECRUIT","DELETE","DEVPAGE","DEBUG","GFUP","FFUP","FDOWNLOAD","CUSFDOWN","SETTING","LANGUAGES","RTCTIME","APMANAGE","ETHMANAGE","WRDSMANG","FDEL","INFORM","ACCESS","ETHINFORM","APINFORM","LICENSE","DELBTN","SETBTN","DEFBTN","CLR","TEMP","ALLF","LOGF","REQBTN","RECRBTN","SAVEBTN"]; var New_HU_Langs = HU_Langs.filter(function () { return true }); var New_EN_Langs = EN_Langs.filter(function () { return true }); var New_DE_Langs = DE_Langs.filter(function () { return true }); var New_RO_Langs = RO_Langs.filter(function () { return true }); New_HU_Langs.shift(); New_EN_Langs.shift(); New_DE_Langs.shift(); New_RO_Langs.shift(); for(var i = 0; i &lt; TAGS.length;i++){ arrLang.HU[TAGS[i]] = New_HU_Langs[i]; arrLang.EN[TAGS[i]] = New_EN_Langs[i]; arrLang.DE[TAGS[i]] = New_DE_Langs[i]; arrLang.RO[TAGS[i]] = New_RO_Langs[i]; } //console.log(arrLang); Set_Actual_Language(); Notify("Lang_Set!","Success","Settings"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:48:20.550", "Id": "457214", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:16:11.123", "Id": "457228", "Score": "0", "body": "The picture of the table is not readable on my machine (on 27\", so that's not the problem). To clarify, this currently works as intended (produces the correct results) and you're looking for a cleaner solution, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:53:36.650", "Id": "457237", "Score": "0", "body": "Yes Mast you are correct. There is just one question or asking. I don't know where Heslacher sees more questions. This is one code and one goal only. Just in pieces.\nI need some cleaner solutions for the nested for loops for example. Or to the whole approach. ^^" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:25:42.377", "Id": "233853", "Score": "0", "Tags": [ "javascript", "object-oriented", "jquery", "array", "html" ], "Title": "Little Multilanguage site with modifiable words in a table.( Code improvement )" }
233853
<p>The below code is either inserting or updating a list of person with a lot of properties of these persons. The code is repeating itself a lot but is working as intended.</p> <p>Unfortunately making all the types implement a common interface is not an option for me.</p> <pre><code>public void BulkInsertPeople(List&lt;Person&gt; persons, User requestUser) { var credentials = new List&lt;Credential&gt;(); var educations = new List&lt;Education&gt;(); var addresses = new List&lt;Address&gt;(); var emails = new List&lt;Email&gt;(); var phones = new List&lt;Phone&gt;(); var practitionerDetails = new List&lt;PractitionerDetails&gt;(); var recruitingInfo = new List&lt;RecruitingInfo&gt;(); var familyMembers = new List&lt;FamilyMember&gt;(); var socialLinks = new List&lt;SocialLink&gt;(); var employments = new List&lt;Employment&gt;(); if (_context != null) { var strategy = _context.Database.CreateExecutionStrategy(); strategy.Execute(() =&gt; { using (var transaction = _context.Database.BeginTransaction()) { var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true, PreserveInsertOrder = true}; _context.BulkInsertOrUpdate(persons, bulkConfig); foreach (var person in persons) { person.CreatedDateTime = DateTime.Now; person.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; if(requestUser.AccountID.HasValue) person.AccountID = requestUser.AccountID.Value; foreach (var c in person.Credentials) { c.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB c.AccountID = person.AccountID; c.CreatedDateTime = DateTime.Now; c.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } credentials.AddRange(person.Credentials); foreach (var e in person.Education) { e.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB e.AccountID = person.AccountID; e.CreatedDateTime = DateTime.Now; e.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } educations.AddRange(person.Education); foreach (var a in person.Addresses) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } addresses.AddRange(person.Addresses ); foreach (var a in person.Emails) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } emails.AddRange(person.Emails); foreach (var a in person.Phones) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } phones.AddRange(person.Phones); foreach (var a in person.SocialLinks) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } socialLinks.AddRange(person.SocialLinks); foreach (var a in person.Employments) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } employments.AddRange(person.Employments); foreach (var a in person.FamilyMembers) { a.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB a.AccountID = person.AccountID; a.CreatedDateTime = DateTime.Now; a.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; } familyMembers.AddRange(person.FamilyMembers); person.PractitionerDetails.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB person.PractitionerDetails.AccountID = person.AccountID; person.PractitionerDetails.CreatedDateTime = DateTime.Now; person.PractitionerDetails.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; practitionerDetails.Add(person.PractitionerDetails); person.RecruitingInfo.PersonID = person.PersonID; // setting FK to match its linked PK that was generated in DB person.RecruitingInfo.AccountID = person.AccountID; person.RecruitingInfo.CreatedDateTime = DateTime.Now; person.RecruitingInfo.CreatedBy = requestUser.FirstName + " " + requestUser.LastName; recruitingInfo.Add(person.RecruitingInfo); } _context.BulkInsertOrUpdate(credentials, bulkConfig); _context.BulkInsertOrUpdate(educations, bulkConfig); _context.BulkInsertOrUpdate(addresses, bulkConfig); _context.BulkInsertOrUpdate(emails,bulkConfig); _context.BulkInsertOrUpdate(phones,bulkConfig); _context.BulkInsertOrUpdate(socialLinks,bulkConfig); _context.BulkInsertOrUpdate(practitionerDetails,bulkConfig); _context.BulkInsertOrUpdate(recruitingInfo,bulkConfig); _context.BulkInsertOrUpdate(familyMembers,bulkConfig); _context.BulkInsertOrUpdate(employments,bulkConfig); transaction.Commit(); } }); } } </code></pre>
[]
[ { "body": "<p>A dynamic expression might come in handy here to delegate the repeated code.</p>\n\n<pre><code>public static class PersonExtensions {\n\n public static T Populate&lt;T&gt;(this Person person, Func&lt;Person, T&gt; accessor) {\n T target = accessor(person);\n var type = target.GetType();\n if (target is IEnumerable &amp;&amp; type.IsGenericType) {\n var arg = type.GetGenericArguments().First();\n if (typeof(IEnumerable&lt;&gt;).MakeGenericType(arg).IsAssignableFrom(type))\n type = arg;\n }\n Action&lt;object&gt; invoke = person.BuildActionFor(type);\n\n if (target is IEnumerable collection) {\n foreach (var item in collection) {\n invoke(item);\n }\n } else {\n invoke(target);\n }\n return target;\n }\n\n private static Action&lt;object&gt; BuildActionFor(this Person person, Type type) {\n //object obj =&gt;\n var parameter = Expression.Parameter(typeof(object), \"obj\");\n // T p;\n var variable = Expression.Variable(type, \"p\");\n\n var statements = new[] {\n // p = (T)obj;\n Expression.Assign(variable, Expression.Convert(parameter, type)),\n // p.PersonID = person.PersonID;\n Expression.Assign(Expression.Property(variable, \"PersonID\"), Expression.Constant(person.PersonID)),\n // p.PersonID = person.AccountID;\n Expression.Assign(Expression.Property(variable, \"AccountID\"), Expression.Constant(person.AccountID)),\n // p.PersonID = person.CreatedDateTim;\n Expression.Assign(Expression.Property(variable, \"CreatedDateTime\"), Expression.Constant(person.CreatedDateTime)),\n // p.PersonID = person.CreatedBy;\n Expression.Assign(Expression.Property(variable, \"CreatedBy\"), Expression.Constant(person.CreatedBy)),\n };\n BlockExpression body = Expression.Block(\n new[] { variable },\n statements)\n ;\n // T p =&gt; { ... };\n var expression = Expression.Lambda&lt;Action&lt;object&gt;&gt;(body, parameter);\n Action&lt;object&gt; populate = expression.Compile();\n return populate;\n }\n}\n</code></pre>\n\n<p>The time stamp and created by are already set on the <code>person</code> at the beginning of the loop</p>\n\n<pre><code>//...\n\nforeach (var person in persons) {\n person.CreatedDateTime = DateTime.Now;\n person.CreatedBy = requestUser.FirstName + \" \" + requestUser.LastName;\n\n//...\n</code></pre>\n\n<p>so there was no need to recreate those values lower down. </p>\n\n<p>It meant that everything needed to populate the other object could be obtained from the already populate <code>Person</code> object.</p>\n\n<p>With the extension methods in place, the code refactors to</p>\n\n<pre><code>public void BulkInsertPeople(List&lt;Person&gt; persons, User requestUser) {\n var credentials = new List&lt;Credential&gt;();\n var educations = new List&lt;Education&gt;();\n var addresses = new List&lt;Address&gt;();\n var emails = new List&lt;Email&gt;();\n var phones = new List&lt;Phone&gt;();\n var practitionerDetails = new List&lt;PractitionerDetails&gt;();\n var recruitingInfo = new List&lt;RecruitingInfo&gt;();\n var familyMembers = new List&lt;FamilyMember&gt;();\n var socialLinks = new List&lt;SocialLink&gt;();\n var employments = new List&lt;Employment&gt;();\n\n if (_context != null) {\n var strategy = _context.Database.CreateExecutionStrategy();\n\n strategy.Execute(() =&gt; {\n using (var transaction = _context.Database.BeginTransaction()) {\n var bulkConfig = new BulkConfig() { \n SetOutputIdentity = true, \n CalculateStats = true, \n PreserveInsertOrder = true\n };\n _context.BulkInsertOrUpdate(persons, bulkConfig);\n\n foreach (var person in persons) {\n person.CreatedDateTime = DateTime.Now;\n person.CreatedBy = requestUser.FirstName + \" \" + requestUser.LastName;\n if(requestUser.AccountID.HasValue)\n person.AccountID = requestUser.AccountID.Value;\n\n credentials.AddRange(person.Populate(p =&gt; p.Credentials));\n educations.AddRange(person.Populate(p =&gt; p.Education));\n addresses.AddRange(person.Populate(p =&gt; p.Addresses));\n emails.AddRange(person.Populate(p =&gt; p.Emails));\n phones.AddRange(person.Populate(p =&gt; p.Phones));\n socialLinks.AddRange(person.Populate(p =&gt; p.SocialLinks));\n employments.AddRange(person.Populate(p =&gt; p.Employments));\n familyMembers.AddRange(person.Populate(p =&gt; p.FamilyMembers));\n\n practitionerDetails.Add(person.Populate(p =&gt; p.PractitionerDetails));\n recruitingInfo.Add(person.Populate(p =&gt; p.RecruitingInfo)); \n }\n\n _context.BulkInsertOrUpdate(credentials, bulkConfig);\n _context.BulkInsertOrUpdate(educations, bulkConfig);\n _context.BulkInsertOrUpdate(addresses, bulkConfig);\n _context.BulkInsertOrUpdate(emails,bulkConfig);\n _context.BulkInsertOrUpdate(phones,bulkConfig);\n _context.BulkInsertOrUpdate(socialLinks,bulkConfig);\n _context.BulkInsertOrUpdate(practitionerDetails,bulkConfig);\n _context.BulkInsertOrUpdate(recruitingInfo,bulkConfig);\n _context.BulkInsertOrUpdate(familyMembers,bulkConfig);\n _context.BulkInsertOrUpdate(employments,bulkConfig);\n\n transaction.Commit();\n }\n });\n }\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:08:31.943", "Id": "233869", "ParentId": "233858", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:26:17.343", "Id": "233858", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "Bulk inserting/updating people with additional properties" }
233858
<p>i am trying to learn mvc (model view controller). there are many texts out there explaining what mvc is. but not many explaining how to actually code mvc. i found a bunch of questions here asking about mvc. some seem to contradict each other (view observe model or not, controller listens to view or not).</p> <p>i made a simple calculator in java swing to try to implement mvc so i can get a review from you whether you think i have done it right or not. the calculator is super simple so the code can concentrate on the mvc aspects.</p> <p>the main class</p> <pre><code>public class Main { public static void main(String[] args) { Model model = new Model(); View view = new View(); Controller controller = new Controller(model, view); view.setController(controller); controller.start(); } } </code></pre> <p>the model</p> <pre><code>public class Model { public int calculate(int i1, String op, int i2) { int res; switch (op) { case "+": res = i1 + i2; break; case "-": res = i1 - i2; break; default: throw new RuntimeException("impossible operator"); } return res; } } </code></pre> <p>the view</p> <pre><code>public class View { Controller controller; JLabel result; public void setController(Controller controller) { this.controller = controller; } public void show() { JFrame frame = new JFrame("calculator mvc"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); JTextField input1 = new JTextField(10); JComboBox&lt;String&gt; operand = new JComboBox&lt;String&gt;( new String[] { "+", "-" }); JTextField input2 = new JTextField(10); JButton calcbutton = new JButton("calculate"); result = new JLabel(" "); result.setBorder(BorderFactory.createLineBorder(Color.BLACK)); calcbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String s1 = input1.getText(); String op = operand.getItemAt(operand.getSelectedIndex()); String s2 = input2.getText(); controller.handleUserInput(s1, op, s2); } }); panel.add(input1); panel.add(operand); panel.add(input2); panel.add(calcbutton); panel.add(result); frame.add(panel); frame.pack(); frame.setVisible(true); } public void setResult(String res) { this.result.setText(res); } } </code></pre> <p>the controller</p> <pre><code>public class Controller { Model model; View view; public Controller(Model model, View view) { this.model = model; this.view = view; } public void handleUserInput(String s1, String op, String s2) { int i1 = Integer.parseInt(s1); int i2 = Integer.parseInt(s2); int res = this.model.calculate(i1, op, i2); this.view.setResult(String.valueOf(res)); } public void start() { this.view.show(); } } </code></pre> <p>some comments:</p> <p>i took the mvc approach where view does not observe model. instead controller talks to view. in this case model does not have any state to observe anyway.</p> <p>the operators in model could have been done in command pattern or strategy pattern. but that would have added at least three more classes (or interfaces). i decided to keep it simple.</p> <p>model gets ints and returns ints. view gives strings and gets strings. controller is the one translating between the two.</p> <p>is this good mvc?</p> <p>just for comparison here is the code without mvc</p> <pre><code>public class MainNotMvc { public static void main(String[] args) { JFrame frame = new JFrame("calculator not mvc"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); JTextField input1 = new JTextField(10); JComboBox&lt;String&gt; operand = new JComboBox&lt;String&gt;( new String[] { "+", "-" }); JTextField input2 = new JTextField(10); JButton calcbutton = new JButton("calculate"); JLabel result = new JLabel(" "); result.setBorder(BorderFactory.createLineBorder(Color.BLACK)); calcbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i1 = Integer.parseInt(input1.getText()); String op = operand.getItemAt(operand.getSelectedIndex()); int i2 = Integer.parseInt(input2.getText()); int res; switch (op) { case "+": res = i1 + i2; break; case "-": res = i1 - i2; break; default: throw new RuntimeException("impossible operator"); } result.setText(String.valueOf(res)); } }); panel.add(input1); panel.add(operand); panel.add(input2); panel.add(calcbutton); panel.add(result); frame.add(panel); frame.pack(); frame.setVisible(true); } } </code></pre> <p>code in git: <a href="https://gitlab.com/lesmana/java-swing-simple-calculator-mvc" rel="nofollow noreferrer">https://gitlab.com/lesmana/java-swing-simple-calculator-mvc</a></p>
[]
[ { "body": "<p>Your controller class looked fine. The <code>calculate</code> method in the model class should have been located in this class. In this example application, the model class should be empty. There is no data to retain.</p>\n\n<p>Your <code>Main</code> class needs to put the creation and execution of the Swing components on the <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html\" rel=\"nofollow noreferrer\">Event Dispatch Thread</a>. Here's how I changed your <code>Main</code> class.</p>\n\n<pre><code>import javax.swing.SwingUtilities;\n\npublic class Main implements Runnable {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Main());\n }\n\n @Override\n public void run() {\n Model model = new Model();\n View view = new View();\n Controller controller = new Controller(model, view);\n view.setController(controller);\n controller.start();\n }\n\n}\n</code></pre>\n\n<p>In the View class, when creating Swing components, it's a good idea to group all of the method calls by each Swing component. The Swing components should be defined in row, column order.</p>\n\n<p>I also added <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html\" rel=\"nofollow noreferrer\">layout managers</a> for the <code>JPanel</code>s. You used a default <code>FlowLayout</code> for your one <code>JPanel</code>.</p>\n\n<p>I made a few other tweaks to make your GUI look more like a calculator.</p>\n\n<p><a href=\"https://i.stack.imgur.com/XeEg1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XeEg1.png\" alt=\"Calculator MVC\"></a></p>\n\n<p>Here's what I did to your <code>View</code> class.</p>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.FlowLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class View {\n\n Controller controller;\n JTextField result;\n\n public void setController(Controller controller) {\n this.controller = controller;\n }\n\n public void show() {\n JFrame frame = new JFrame(\"Calculator MVC\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n JPanel panel = new JPanel();\n panel.setLayout(new BorderLayout());\n\n JPanel calculatorPanel = new JPanel();\n calculatorPanel.setLayout(new FlowLayout());\n\n JTextField input1 = new JTextField(10);\n input1.setHorizontalAlignment(JTextField.RIGHT);\n calculatorPanel.add(input1);\n\n JComboBox&lt;String&gt; operand = new JComboBox&lt;String&gt;(\n new String[] { \"+\", \"-\" });\n calculatorPanel.add(operand);\n\n JTextField input2 = new JTextField(10);\n input2.setHorizontalAlignment(JTextField.RIGHT);\n calculatorPanel.add(input2);\n\n JLabel label = new JLabel(\" = \");\n calculatorPanel.add(label);\n\n result = new JTextField(10);\n result.setBorder(BorderFactory.createLineBorder(\n Color.BLACK));\n result.setEditable(false);\n result.setHorizontalAlignment(JTextField.RIGHT);\n calculatorPanel.add(result);\n\n panel.add(calculatorPanel, \n BorderLayout.BEFORE_FIRST_LINE);\n\n JPanel buttonPanel = new JPanel();\n buttonPanel.setLayout(new FlowLayout());\n\n JButton calcbutton = new JButton(\"Calculate\"); \n calcbutton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n String s1 = input1.getText();\n String op = operand.getItemAt(\n operand.getSelectedIndex());\n String s2 = input2.getText();\n controller.handleUserInput(s1, op, s2);\n }\n });\n buttonPanel.add(calcbutton);\n\n panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);\n\n frame.add(panel);\n frame.getRootPane().setDefaultButton(calcbutton);\n frame.pack();\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n }\n\n public void setResult(String res) {\n this.result.setText(res);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:39:43.550", "Id": "240827", "ParentId": "233859", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:36:02.600", "Id": "233859", "Score": "3", "Tags": [ "java", "mvc", "swing" ], "Title": "java swing super simple calculator mvc" }
233859
<p>I just wrote a short function to parse SO jobs <a href="https://stackoverflow.com/jobs/feed?r=true">XML feed</a> and return dicts containing information about each job entry.<br> Now, each job entry page is visited to grab info not present in the xml feed (company logo URL, salary info, etc.) through <code>bs4</code> with couple functions in the <code>get_so_extras</code> module.</p> <p><strong>parse_feed.py</strong>:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime as dt from xml.etree import ElementTree as etree from get_so_extras import get_company_logo, get_so_salary import urllib3 import json import sys def get_so_listings(url): """ Get remote job listings from stackoverflow.com xml feed """ http = urllib3.PoolManager() try: so_file = http.request("GET", url).data except Exception as e: print(e.args) sys.exit() so_root = etree.fromstring(so_file) items = so_root.findall("channel/item") # Parse SO xml feed in dict so_listings = [] for e in items: job_dict = { "so_id": e.findtext("guid"), "title": e.findtext("title"), "so_url": e.findtext("link"), "author": e.findtext( """{http://www.w3.org/2005/Atom}author/{http://www.w3.org/2005/Atom}name""" ), "description": e.findtext("description"), "published_at": str( dt.strptime( e.findtext("pubDate").strip(), "%a, %d %b %Y %H:%M:%S Z" ) ), "updated_at": str( dt.strptime( e.findtext("{http://www.w3.org/2005/Atom}updated"), "%Y-%m-%dT%H:%M:%SZ", ) ), "company_logo_url": get_company_logo(e.findtext("link")), "categories": [c.text for c in e.findall("category")], } # @TODO: get_company_logo(job_dict["so_url"]) so_listings.append(job_dict) print("Jobs imported: {}".format(len(so_listings))) # Helper - export to json, ideally pushed to db with open('output1.json', 'w', encoding='utf-8') as f: json.dump(so_listings, f, indent=4) return True </code></pre> <p>And here the helper function used to grab company logo URLs from <code>get_so_extras</code> module.</p> <p><strong>get_so_extras.py</strong>: </p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup import requests import time def get_company_logo(job_url): """ Get company logo from stackoverflow.com job listing page """ try: page = requests.get(job_url) soup = BeautifulSoup(page.text, 'html.parser') logo = soup.find("div", attrs={'class': 's-avatar s-avatar__lg mr8 bg-white fl-shrink0'}).\ img["src"] except Exception as e: print(e) pass time.sleep(5) # Be kind return logo </code></pre> <p>It'd be great to understand whether I made any obvious mistake or bad choice along the way. Obviously calling <code>get_company_logo</code> within the XML parsing loop slows things down, what would be the best approach to get those fields?<br> Probably checking if we're looking at a new company/listing from db before visiting the page to scrape the logo would be more efficient. </p> <p>edit: also, given job listings have pretty much similar attributes, could it make sense to create a class <code>listing</code> with attribute and a method to push it to db (with de-duplication logic perhaps)?</p> <p>Be ruthless, thanks in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T00:36:21.030", "Id": "457462", "Score": "0", "body": "I'm trying to familiarize myself with the feed etc., can't even get lxml to parse it --' Do you know if it's documented anywhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:23:50.333", "Id": "457487", "Score": "0", "body": "Haven't found any docs either. The structure is pretty straightforward though: results are stored in `<item>` tags inside `<channel>`. Each listing has just a handful of fields, you can eyeball them to decide which you want to parse." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:53:42.623", "Id": "457493", "Score": "0", "body": "I figured out the issue in the end. As you said, the rest should be straightforward, it’s rather simple format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T00:22:21.250", "Id": "457607", "Score": "0", "body": "What does your output look like, particularly for the description?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:16:59.113", "Id": "457647", "Score": "0", "body": "My output is a list of dictionaries (`so_listings`) where a dict represents a job entry. I've ditched the JSON output in favour of pushing the entry to a MySQL db through SQLAlchemy after checking for duplicates though." } ]
[ { "body": "<p>I've been experimenting with the best data structure for this. Here is what I have for now. It is definitely a work in progress, I hope to keep updating it constantly.</p>\n\n<p>The CSV output was unexpected, ultimately a result of my decision to use a namedtuple. I chose namedtuples because, like you, I thought the data fit that tabular style quite well. You wrote <em>given job listings have pretty much similar attributes, could it make sense to create a class listing with attribute and a method to push it to db</em>, and I mostly agree, I just didn't feel that the data itself warranted a whole class.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections as colls\nimport csv\nimport datetime as dt\n\nimport requests\nfrom lxml import etree\n\nJob = colls.namedtuple('Job', ['guid', 'title', 'url', 'author', 'logo', 'description', 'pub_date', 'update_date',\n 'categories'])\n\nhtml_parser = etree.HTMLParser()\n\nreq_session = requests.Session()\nreq = req_session.get(url_1)\n\nroot = etree.fromstring(req.content)\nns_map = root.nsmap\n\njob_elems = root.xpath('/rss/channel/item')[:10]\n\n\ndef parse_job_item(job_item):\n guid = job_item.findtext('guid')\n title = job_item.findtext('title')\n link = job_item.findtext('link')\n author = job_item.findtext('a10:author/a10:name', namespaces=ns_map)\n description = job_item.findtext('description')\n pub_date = job_item.findtext('pubDate')\n if pub_date:\n pub_date = dt.datetime.strptime(pub_date, \"%a, %d %b %Y %H:%M:%S Z\")\n update_date = job_item.findtext('a10:updated', namespaces=ns_map)\n if update_date:\n update_date = dt.datetime.strptime(update_date, \"%Y-%m-%dT%H:%M:%SZ\")\n categories = [elem.text for elem in job_item.findall('category')]\n\n job_page_elem = etree.fromstring(req_session.get(link).content, parser=html_parser)\n # \"//body/div[@class='container']/div[@id='content']/header/div/a/img/@src\"\n # contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')\n company_logo = job_page_elem.xpath(\n \"/html/body/div[@class='container']/div[@id='content']/header/div[contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')]//img/@src\")\n if company_logo:\n company_logo = company_logo[0]\n res_item = Job(guid, title, link, author, company_logo, description, pub_date, update_date, categories)\n return res_item\n\n\njob_data_list = (parse_job_item(curr_elem) for curr_elem in job_elems)\n\nwith open('../out/jobs_out.csv', 'w', newline='') as out_file:\n writer = csv.writer(out_file)\n writer.writerow(Job._fields)\n writer.writerows(job_data_list)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T21:00:45.483", "Id": "457676", "Score": "0", "body": "All in all both approaches look quite similar, except for the `namedtuple`. The only reason I would consider setting up a class would be to structure things a bit more if starting to get job entries from additional sources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T23:20:08.243", "Id": "457680", "Score": "1", "body": "@AndreaDodet Yeah, that would make sense. I'm currently trying to to think of the best way to integrate some form of concurrency/parallelism." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T08:22:41.030", "Id": "457809", "Score": "0", "body": "I guess my approach should change to add parallelism: 1. Parse entire xml. 2. Check if new entries are present (threaded). 3. Gather data for new entries 4. Push to db.\nI realize I am checkig for duplicates way too late, it basically just spares the `push_to_db()`call where the real advantage would be to cut the website requests for additional info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:05:28.630", "Id": "457902", "Score": "0", "body": "@AndreaDodet Yes, check for duplicates as early as possible. I'm going to go see what `multiprocessing` has to say about sharing data like this." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T01:49:10.083", "Id": "234014", "ParentId": "233860", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T10:41:44.660", "Id": "233860", "Score": "4", "Tags": [ "python", "web-scraping", "xml", "beautifulsoup" ], "Title": "XML parser + bs4 combo" }
233860
<p>I've implemented the cryptographic method of the Fleissner-grille aka <a href="https://en.wikipedia.org/wiki/Grille_(cryptography)#Turning_grilles" rel="nofollow noreferrer">Turning-grille</a> .</p> <p>Here's the code:</p> <pre class="lang-java prettyprint-override"><code>import java.util.Scanner; import java.util.Random; public class fleissner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Scanner scanner2 = new Scanner(System.in); System.out.println("Enter text without spaces:"); String text = scanner2.nextLine(); /*In case the text has less than 36 characters, the String gets filled up with "x"*/ if(text.length()&lt;36) { while(text.length()&lt;36) { text = text + "x"; } } //Case that text is too long if(text.length() != 36){ text = substring(text, 0, 36); System.out.println("Text too long. The following part of the text will be encrypted: " + text); } char[][] out = encrypt(text); for (int line = 0; line &lt; out.length; line++) { for (int column = 0; column &lt; out[line].length; column++) { System.out.print(out[line][column] + " "); } System.out.println(); } } //This method rotates the "grille" clockwise 45 degrees public static int[][] rotate(int[][] a1) { int[][] rotated = {{a1[5][0],a1[4][0],a1[3][0],a1[2][0],a1[1][0],a1[0][0]}, {a1[5][1],a1[4][1],a1[3][1],a1[2][1],a1[1][1],a1[0][1]}, {a1[5][2],a1[4][2],a1[3][2],a1[2][2],a1[1][2],a1[0][2]}, {a1[5][3],a1[4][3],a1[3][3],a1[2][3],a1[1][3],a1[0][3]}, {a1[5][4],a1[4][4],a1[3][4],a1[2][4],a1[1][4],a1[0][4]}, {a1[5][5],a1[4][5],a1[3][5],a1[2][5],a1[1][5],a1[0][5]} }; return rotated; } //This method creates a random grille public static int[][] creategrille() { int[][] a2 = { {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)}, {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)}, {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)} }; int[][] a3 = { {(a2[2][0])%4+1,(a2[1][0])%4+1,(a2[0][0])%4+1}, {(a2[2][1])%4+1,(a2[1][1])%4+1,(a2[0][1])%4+1}, {(a2[2][2])%4+1,(a2[1][2])%4+1,(a2[0][2])%4+1} }; int[][] a4 = { {(a3[2][0])%4+1,(a3[1][0])%4+1,(a3[0][0])%4+1}, {(a3[2][1])%4+1,(a3[1][1])%4+1,(a3[0][1])%4+1}, {(a3[2][2])%4+1,(a3[1][2])%4+1,(a3[0][2])%4+1} }; int[][] a5 = { {(a4[2][0])%4+1,(a4[1][0])%4+1,(a4[0][0])%4+1}, {(a4[2][1])%4+1,(a4[1][1])%4+1,(a4[0][1])%4+1}, {(a4[2][2])%4+1,(a4[1][2])%4+1,(a4[0][2])%4+1} }; int[][] a1 = { {a2[0][0],a2[0][1],a2[0][2],a3[0][0],a3[0][1],a3[0][2]}, {a2[1][0],a2[1][1],a2[1][2],a3[1][0],a3[1][1],a3[1][2]}, {a2[2][0],a2[2][1],a2[2][2],a3[2][0],a3[2][1],a3[2][2]}, {a5[0][0],a5[0][1],a5[0][2],a4[0][0],a4[0][1],a4[0][2]}, {a5[1][0],a5[1][1],a5[1][2],a4[1][0],a4[1][1],a4[1][2]}, {a5[2][0],a5[2][1],a5[2][2],a4[2][0],a4[2][1],a4[2][2]} }; System.out.println("The grille:"); for (int line = 0; line &lt; a1.length; line++) { for (int column = 0; column &lt; a1[line].length; column++) { System.out.print(a1[line][column] + " "); } System.out.println(); } System.out.println(""); System.out.println("Program is using '1' as holes in the grille."); System.out.println(""); return a1; } public static char[][] encrypt(String text) { int[][] a1 = creategrille(); /*The text now gets split up to substrings with length 9. Then the grille gets filled up with the chars.*/ String text1 = substring(text, 0, 9); int[] ar = {0,9,18,27,36}; char[][] out = new char[6][6]; int i = 0; while(i&lt;4) { int a = 0; int b = 0; int x = 0; while (x &lt; text1.length()) { if(a1[a][b]==1){ out[a][b] = text1.charAt(x); x=x+1; if (b&lt;5){ b=b+1; } else if(a&lt;5){ a=a+1; b=0; } } else if (b&lt;5){ b=b+1; } else if(a&lt;5){ a=a+1; b=0; } } i = i+1; int m = ar[i]; int n = m+9; text1 = substring(text, m, n); a1 = rotate(a1); } return out; } //Method to divide String into smaller substrings. public static String substring(String str, int start, int end) { String out = ""; if (start &gt; end) { return out; } if (start &lt; 0) { start = 0; } if (end &gt; str.length() - 1) { end = str.length(); } while (start &lt; end) { out = out + str.charAt(start); start = start + 1; } return out; } } </code></pre> <p>My question now is: How to improve my code? Especially I am interested in improving the <code>creategrille</code> method, but I would also appreciate suggestions to other parts of the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T00:04:00.087", "Id": "462892", "Score": "0", "body": "This is of course just for practice, but cryptography requires *secure random* numbers, sensibly implemented by the `SecureRandom` class (and underlying implementations) within Java." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T06:21:22.470", "Id": "462907", "Score": "0", "body": "Oh, thanks for the hint. I didn't knew there's an extra class for that." } ]
[ { "body": "<p>1) The variable \"scanner\" is not used.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner scanner = new Scanner(System.in)\n</code></pre>\n\n<p>2) Instead of building a string in a loop (padding), I suggest that you use a <code>java.lang.StringBuilder</code></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> StringBuilder stringBuilder = new StringBuilder(scanner2.nextLine());\n\n /*In case the text has less than 36 characters,\n the String gets filled up with \"x\"*/\n while (stringBuilder.length() &lt; 36) {\n stringBuilder.append('x');\n }\n</code></pre>\n\n<p>3) Instead of concatening a string in the <code>java.io.PrintStream#println(java.lang.String)</code>, you can use <code>java.io.PrintStream#printf(java.lang.String, java.lang.Object...)</code> Instead.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n //Case that text is too long\n if (textLength != 36) {\n text = substring(text, 0, 36);\n System.out.printf(\"Text too long. The following part of the text will be encrypted: %s\\n\", text);\n }\n //[...]\n</code></pre>\n\n<p>4) In the rotate method, you can directly return the array.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //This method rotates the \"grille\" clockwise 45 degrees\n public static int[][] rotate(int[][] a1) {\n\n return new int[][] {\n { a1[5][0], a1[4][0], a1[3][0], a1[2][0], a1[1][0], a1[0][0] }, { a1[5][1], a1[4][1], a1[3][1], a1[2][1], a1[1][1], a1[0][1] },\n { a1[5][2], a1[4][2], a1[3][2], a1[2][2], a1[1][2], a1[0][2] }, { a1[5][3], a1[4][3], a1[3][3], a1[2][3], a1[1][3], a1[0][3] },\n { a1[5][4], a1[4][4], a1[3][4], a1[2][4], a1[1][4], a1[0][4] }, { a1[5][5], a1[4][5], a1[3][5], a1[2][5], a1[1][5], a1[0][5] } };\n }\n\n</code></pre>\n\n<p>5) In the <code>creategrille</code> method, i suggest that you create a method to generate the expression <code>(int) ((Math.random()) * 4 + 1)</code></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\n //This method creates a random grille\n public static int[][] creategrille() {\n //[...]\n int[][] a2 = {\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() },\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() },\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() } };\n\n //[...]\n }\n\n //[...]\n private static int generateRandomTimeFourPlusOne() {\n return (int) ((Math.random()) * 4 + 1);\n }\n //[...]\n</code></pre>\n\n<p>6) In the <code>substring</code> method, the <code>out</code> variable is useless, return directly an empty String in the first check and use a <code>java.lang.StringBuilder</code> in the loop; to build the result.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static String substring(String str, int start, int end) {\n if (start &gt; end) {\n return \"\";\n }\n\n if (start &lt; 0) {\n start = 0;\n }\n\n if (end &gt; str.length() - 1) {\n end = str.length();\n }\n\n StringBuilder out = new StringBuilder();\n\n while (start &lt; end) {\n out.append(str.charAt(start));\n start = start + 1;\n\n }\n\n return out.toString();\n }\n</code></pre>\n\n<p>7) In my opinion, you should rename the method <code>substring</code> to <code>safeSubstring</code>.</p>\n\n<h1>Edited code</h1>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n\n System.out.println(\"Enter text without spaces:\");\n\n StringBuilder stringBuilder = new StringBuilder(scanner.nextLine());\n\n /*In case the text has less than 36 characters,\n the String gets filled up with \"x\"*/\n while (stringBuilder.length() &lt; 36) {\n stringBuilder.append('x');\n }\n\n String text = stringBuilder.toString();\n\n //Case that text is too long\n if (text.length() != 36) {\n text = safeSubstring(text, 0, 36);\n System.out.println(\"Text too long. The following part of the text will be encrypted: \" + text);\n }\n\n char[][] out = encrypt(text);\n\n for (int line = 0; line &lt; out.length; line++) {\n\n for (int column = 0; column &lt; out[line].length; column++) {\n System.out.print(out[line][column] + \" \");\n }\n\n System.out.println();\n }\n\n }\n\n //This method rotates the \"grille\" clockwise 45 degrees\n public static int[][] rotate(int[][] a1) {\n\n return new int[][] {\n { a1[5][0], a1[4][0], a1[3][0], a1[2][0], a1[1][0], a1[0][0] }, { a1[5][1], a1[4][1], a1[3][1], a1[2][1], a1[1][1], a1[0][1] },\n { a1[5][2], a1[4][2], a1[3][2], a1[2][2], a1[1][2], a1[0][2] }, { a1[5][3], a1[4][3], a1[3][3], a1[2][3], a1[1][3], a1[0][3] },\n { a1[5][4], a1[4][4], a1[3][4], a1[2][4], a1[1][4], a1[0][4] }, { a1[5][5], a1[4][5], a1[3][5], a1[2][5], a1[1][5], a1[0][5] } };\n }\n\n //This method creates a random grille\n public static int[][] creategrille() {\n\n int[][] a2 = {\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() },\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() },\n { generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne(), generateRandomTimeFourPlusOne() } };\n\n int[][] a3 = {\n { (a2[2][0]) % 4 + 1, (a2[1][0]) % 4 + 1, (a2[0][0]) % 4 + 1 }, { (a2[2][1]) % 4 + 1, (a2[1][1]) % 4 + 1, (a2[0][1]) % 4 + 1 },\n { (a2[2][2]) % 4 + 1, (a2[1][2]) % 4 + 1, (a2[0][2]) % 4 + 1 } };\n int[][] a4 = {\n { (a3[2][0]) % 4 + 1, (a3[1][0]) % 4 + 1, (a3[0][0]) % 4 + 1 }, { (a3[2][1]) % 4 + 1, (a3[1][1]) % 4 + 1, (a3[0][1]) % 4 + 1 },\n { (a3[2][2]) % 4 + 1, (a3[1][2]) % 4 + 1, (a3[0][2]) % 4 + 1 } };\n int[][] a5 = {\n { (a4[2][0]) % 4 + 1, (a4[1][0]) % 4 + 1, (a4[0][0]) % 4 + 1 }, { (a4[2][1]) % 4 + 1, (a4[1][1]) % 4 + 1, (a4[0][1]) % 4 + 1 },\n { (a4[2][2]) % 4 + 1, (a4[1][2]) % 4 + 1, (a4[0][2]) % 4 + 1 } };\n int[][] a1 = {\n { a2[0][0], a2[0][1], a2[0][2], a3[0][0], a3[0][1], a3[0][2] }, { a2[1][0], a2[1][1], a2[1][2], a3[1][0], a3[1][1], a3[1][2] },\n { a2[2][0], a2[2][1], a2[2][2], a3[2][0], a3[2][1], a3[2][2] }, { a5[0][0], a5[0][1], a5[0][2], a4[0][0], a4[0][1], a4[0][2] },\n { a5[1][0], a5[1][1], a5[1][2], a4[1][0], a4[1][1], a4[1][2] }, { a5[2][0], a5[2][1], a5[2][2], a4[2][0], a4[2][1], a4[2][2] } };\n\n System.out.println(\"The grille:\");\n\n for (int line = 0; line &lt; a1.length; line++) {\n\n for (int column = 0; column &lt; a1[line].length; column++) {\n System.out.print(a1[line][column] + \" \");\n }\n System.out.println();\n }\n\n System.out.println(\"\");\n System.out.println(\"Program is using '1' as holes in the grille.\");\n System.out.println(\"\");\n\n return a1;\n }\n\n private static int generateRandomTimeFourPlusOne() {\n return (int) ((Math.random()) * 4 + 1);\n }\n\n public static char[][] encrypt(String text) {\n int[][] a1 = creategrille();\n /*The text now gets split up to substrings with length 9.\n Then the grille gets filled up with the chars.*/\n\n String text1 = safeSubstring(text, 0, 9);\n\n int[] ar = { 0, 9, 18, 27, 36 };\n char[][] out = new char[6][6];\n\n int i = 0;\n while (i &lt; 4) {\n int a = 0;\n int b = 0;\n int x = 0;\n\n while (x &lt; text1.length()) {\n if (a1[a][b] == 1) {\n out[a][b] = text1.charAt(x);\n x = x + 1;\n if (b &lt; 5) {\n b = b + 1;\n } else if (a &lt; 5) {\n a = a + 1;\n b = 0;\n }\n } else if (b &lt; 5) {\n b = b + 1;\n } else if (a &lt; 5) {\n a = a + 1;\n b = 0;\n }\n\n }\n i = i + 1;\n int m = ar[i];\n int n = m + 9;\n text1 = safeSubstring(text1, m, n);\n a1 = rotate(a1);\n\n }\n\n return out;\n }\n\n //Method to divide String into smaller substrings.\n public static String safeSubstring(String str, int start, int end) {\n if (start &gt; end) {\n return \"\";\n }\n\n if (start &lt; 0) {\n start = 0;\n }\n\n if (end &gt; str.length() - 1) {\n end = str.length();\n }\n\n StringBuilder out = new StringBuilder();\n\n while (start &lt; end) {\n out.append(str.charAt(start));\n start = start + 1;\n\n }\n\n return out.toString();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:01:24.470", "Id": "457250", "Score": "0", "body": "Why should I name it \"safeSubstring\"? Is there a way to make the \"creategrille\"-method shorter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:01:11.033", "Id": "457272", "Score": "0", "body": "In my opinion, `safeSubstring` is a better name; since there's already a substring method `java.lang.String#substring(int)`. Your version adds the overflow checks, so that's why. For your other question, you can extract the arrays into methods. There's probably a way to use a loop, but I didn't have the time to try yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:44:19.213", "Id": "457283", "Score": "0", "body": "Thanks for the clarification. If you have time to try, please let me know your solution!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:38:22.083", "Id": "233871", "ParentId": "233861", "Score": "3" } }, { "body": "<p>Some advice about Java code : </p>\n\n<p>All the Java classes have names beginning with uppercase letter, so instead of <code>fleissner</code> you have to rename your class <code>Fleissner</code>.</p>\n\n<p>The <code>String</code> java class contains a method called <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int-\" rel=\"nofollow noreferrer\">substring</a> so you haven't to redefine it.\nYour method <code>creategrille</code> can be simplified using matrix properties to avoid writing of all elements of matrix, let's start from the begin: you defined the matrix a2 in this way:</p>\n\n<blockquote>\n<pre><code>int[][] a2 = {\n {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)},\n {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)},\n {(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1),(int)((Math.random()) * 4 + 1)}\n};\n</code></pre>\n</blockquote>\n\n<p>This is a matrix that can be rewritten like this:</p>\n\n<pre><code>final int n = 3;\nint[][] a2 = new int[n][n];\nfor (int i = 0; i &lt; n; ++i) {\n for(int j = 0; j &lt; n; ++j) {\n a2[i][j] = (int)((Math.random()) * 4 + 1);\n }\n}\n</code></pre>\n\n<p>I defined a final <code>n</code> variable containing the number of rows that will not change later in the method. You defined three a3, a4, a5 in the following way:</p>\n\n<blockquote>\n<pre><code>int[][] a3 = {\n {(a2[2][0])%4+1,(a2[1][0])%4+1,(a2[0][0])%4+1},\n {(a2[2][1])%4+1,(a2[1][1])%4+1,(a2[0][1])%4+1},\n {(a2[2][2])%4+1,(a2[1][2])%4+1,(a2[0][2])%4+1}\n};\nint[][] a4 = {\n {(a3[2][0])%4+1,(a3[1][0])%4+1,(a3[0][0])%4+1},\n {(a3[2][1])%4+1,(a3[1][1])%4+1,(a3[0][1])%4+1},\n {(a3[2][2])%4+1,(a3[1][2])%4+1,(a3[0][2])%4+1}\n};\nint[][] a5 = {\n {(a4[2][0])%4+1,(a4[1][0])%4+1,(a4[0][0])%4+1},\n {(a4[2][1])%4+1,(a4[1][1])%4+1,(a4[0][1])%4+1},\n {(a4[2][2])%4+1,(a4[1][2])%4+1,(a4[0][2])%4+1}\n};\n</code></pre>\n</blockquote>\n\n<p>Probably you made a cut and paste to define these matrices: the code can be simplified defining an helper function to create matrix and then call the function like the example code below:</p>\n\n<pre><code>private static int[][] getMatrix(int[][] original) {\n final int n = original.length;\n int[][] created = new int[n][n];\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n created[i][j] = original[n - i - 1][i] % 4 + 1;\n }\n }\n return created;\n}\n//inside your creategrille method\nint[][] a3 = getMatrix(a2);\nint[][] a4 = getMatrix(a3);\nint[][] a5 = getMatrix(a4);\n</code></pre>\n\n<p>Finally you can create your matrix <code>a1</code> composed of the four matrices, your code is the following:</p>\n\n<blockquote>\n<pre><code>int[][] a1 = {\n {a2[0][0],a2[0][1],a2[0][2],a3[0][0],a3[0][1],a3[0][2]},\n {a2[1][0],a2[1][1],a2[1][2],a3[1][0],a3[1][1],a3[1][2]},\n {a2[2][0],a2[2][1],a2[2][2],a3[2][0],a3[2][1],a3[2][2]},\n {a5[0][0],a5[0][1],a5[0][2],a4[0][0],a4[0][1],a4[0][2]},\n {a5[1][0],a5[1][1],a5[1][2],a4[1][0],a4[1][1],a4[1][2]},\n {a5[2][0],a5[2][1],a5[2][2],a4[2][0],a4[2][1],a4[2][2]} \n};\n</code></pre>\n</blockquote>\n\n<p>Your matrix is composed like this:</p>\n\n<pre><code>a2 a3\na5 a4 \n</code></pre>\n\n<p>Using an helper function you can generate the four pieces of your matrix and after join them in the final matrix like the code below with an helper function <code>f</code>:</p>\n\n<pre><code>private static void f(int[][] a1, int[][] piece, int x, int y) {\n final int n = piece.length;\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n a1[x + i][y + j] = piece[i][j];\n }\n }\n}\n\n//inside your creategrille method\nint[][]a1 = new int[n * 2][n * 2];\nf(a1, a2, 0, 0);\nf(a1, a3, 0, n);\nf(a1, a5, n, 0);\nf(a1, a4, n, n);\n</code></pre>\n\n<p>Same approach for <code>rotate</code> method, instead of :</p>\n\n<blockquote>\n<pre><code>public static int[][] rotate(int[][] a1) {\n int[][] rotated =\n {{a1[5][0],a1[4][0],a1[3][0],a1[2][0],a1[1][0],a1[0][0]},\n {a1[5][1],a1[4][1],a1[3][1],a1[2][1],a1[1][1],a1[0][1]},\n {a1[5][2],a1[4][2],a1[3][2],a1[2][2],a1[1][2],a1[0][2]},\n {a1[5][3],a1[4][3],a1[3][3],a1[2][3],a1[1][3],a1[0][3]},\n {a1[5][4],a1[4][4],a1[3][4],a1[2][4],a1[1][4],a1[0][4]},\n {a1[5][5],a1[4][5],a1[3][5],a1[2][5],a1[1][5],a1[0][5]}\n };\n return rotated;\n}\n</code></pre>\n</blockquote>\n\n<p>This can be simplified like below:</p>\n\n<pre><code>public static int[][] rotate(int[][] a1) {\n final int n = 6;\n int[][] rotated = new int[n][n];\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n rotated[i][j] = a1[n - j - 1][i];\n }\n }\n return rotated;\n}\n</code></pre>\n\n<p>When you write code, try put spaces between operands and operator , this improves readibility of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T20:54:39.350", "Id": "457302", "Score": "0", "body": "That really helps me to improve the code, especially the creategrille-method. Thanks very much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:12:30.713", "Id": "233889", "ParentId": "233861", "Score": "4" } } ]
{ "AcceptedAnswerId": "233889", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:08:08.367", "Id": "233861", "Score": "4", "Tags": [ "java", "cryptography" ], "Title": "Fleissner-Grille / Turning-Grille in Java" }
233861
<p>My professor told me to optimize my perl code, but he wouldn't tell me what exactly - just make it simpler.</p> <p>I changed some little things but nothing major. Am I missing something?</p> <p>The task was:</p> <blockquote> <p>Perl program that allows the user to simulate the simultaneous throwing of several cubes. The simulation result is then a total number of points, which is the sum of the numbers of the eyes results in single throws. If many of these throws are performed with several cubes, the frequency distribution for the total number of eyes is calculated. This frequency distribution should be in the console window in the form of a table and as a simple overview chart.</p> <p>At the beginning the following entries should be requested by the user:</p> <ul> <li>the number of dice he wants to roll.</li> <li>the number of throws he wants to perform with the selected number of dice.</li> </ul> <p>The frequency distribution for the total number of eye sets should be displayed in two different ways:</p> <ul> <li>Tabular representation as a comparison of the number of points obtained and the associated frequency, both the absolute values ​​of the frequency and the normalized values ​​that result in the division of the absolute values ​​resulting from the total number of throws are issued.</li> <li>Graphic representation as a simple (tilted by 90 degrees) bar chart (e.g. corresponding number of *)</li> </ul> <p>Use subroutines.</p> </blockquote> <pre><code>use warnings; use diagnostics; use GD::Graph::hbars; use GD; use List::Util qw(max); my $number_of_dice = 0; my $number_of_rolls = 0; my $sum_of_throw = 0; my @total_sum_of_eyes; my @single_sum_of_eyes; my @frequency; my %count; my $count =0; my $number =0; print "\n Please insert the number_of_dice: "; chomp($number_of_dice=&lt;STDIN&gt;); print "\n Please instert the number_of_rolls: "; chomp($number_of_rolls=&lt;STDIN&gt;); while ($count&lt; $number_of_rolls) { roll($number_of_dice); push(@total_sum_of_eyes,$sum_of_throw); $count++; } frequency(); representation (); sub roll{ $sum_of_throw = 0; for($i = 0; $i&lt; $number_of_dice; $i++) { $number = int(rand(6) +1); $sum_of_throw+=$number; } } sub frequency{ foreach my $eyes(sort{$a &lt;=&gt; $b} @total_sum_of_eyes){ $count{$eyes}++; } } sub representation{ #Tabular representation print "\n the frequencys-distribution is: \n"; print "\n total_sum_of_eyes\t frequency\t frequencys-distribution in %\n"; foreach my $eyes (sort{$a &lt;=&gt; $b} keys %count){ push(@frequency, $count{$eyes}); #data for the bar chart push(@single_sum_of_eyes, $eyes); #data for the bar chart printf "\n\t $eyes\t\t\t $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100; } print "\n"; #bar chart my $graph = GD::Graph::hbars-&gt;new(1600, 600); $graph-&gt;set( x_label =&gt; 'total_sum_of_eyes', y_label =&gt; 'frequency', title =&gt; 'frequencys-distribution', y_max_value =&gt; max(@frequency)+1, y_min_value =&gt; 0, y_tick_number =&gt; 8, transparent =&gt; 0, bgclr =&gt; 'white', long_ticks =&gt; 1, ) or die $graph-&gt;error; my @data = (\@single_sum_of_eyes,\@frequency); $graph-&gt;set( dclrs =&gt; [ qw(green) ] ); my $gd = $graph-&gt;plot(\@data) or die $graph-&gt;error; open(IMG, '&gt;gd_bars.gif') or die $!; binmode IMG; print IMG $gd-&gt;gif; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:47:51.773", "Id": "457236", "Score": "3", "body": "Welcome to Code Review! I reformatted your question for better readability and also reworded the title in order to state the task the code should accomplish. In the future, you should do this yourself. Have a look at our [ask] page to get some hints how to get there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:42:15.480", "Id": "457366", "Score": "1", "body": "Use smallest possible scope for `my` variables. Also pass variables to functions as arguments, and use `return $var` to return result from functions. This is not perl specific but applies to almost every language. That sort for `$count{$eyes}++` doesn't do anything useful. Use simpler, perl specific loops, `for (1 .. $number_of_rolls)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:44:27.917", "Id": "457367", "Score": "1", "body": "Dont use same variable names for `$count`, and `%count`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:09:44.877", "Id": "457374", "Score": "1", "body": "@mpapec thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:56:46.543", "Id": "457442", "Score": "2", "body": "New versions of code should generally go into a new question. Having the code under review change makes life hard for folks trying to review it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T11:18:34.703", "Id": "233863", "Score": "7", "Tags": [ "performance", "graph", "perl", "dice" ], "Title": "Frequency analysis for simultaneous dice rolls" }
233863
<p>I'm implementing LZ77 compression algorithm. To compress any file type, I use its binary representation and then read it as <code>chars</code> (because 1 <code>char</code> is equal to 1 byte, afaik) to a <code>std::string</code>. Current program version compresses and decompresses files (.txt, .bmp, etc) just fine – size of raw file in bytes matches the size of uncompressed file. </p> <hr> <p>And now for the actual <em>code</em> part. Here's the short info on how LZ77 handles compression: <a href="https://i.stack.imgur.com/Ex4sb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ex4sb.png" alt="Sliding window consists of 2 buffers"></a> <a href="https://i.stack.imgur.com/HeMMJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HeMMJ.png" alt="Example of compression"></a></p> <p>Below are 2 main functions: <em>compress</em> and <em>findLongestMatch</em>:</p> <ul> <li><code>compress</code> moves char data between 2 buffers and saves encoded tuple <em>⟨offset, length, nextchar⟩</em></li> <li><code>findLongestMatch</code> finds the longest match of lookheadBuffer in historyBuffer</li> </ul> <blockquote> <p>So, any way to improve efficiency (time / memory) in general? Search, comparisons? Also, I don't like my loops so much, any thoughts on how to make things more elegant?</p> <p><strong>UPD:</strong> To clarify things, I hope to get code review all in all. </p> <p>Thank you!</p> </blockquote> <p>Code:</p> <hr> <pre><code>LZ77::Triplet LZ77::slidingWindow::findLongestPrefix() { // Minimal tuple (if no match &gt;1 is found) Triplet n(0, 0, lookheadBuffer[0]); size_t lookCurrLen = lookheadBuffer.length() - 1; size_t histCurrLen = historyBuffer.length(); // Increasing the substring (match) length on every iteration for (size_t i = 1; i &lt;= std::min(lookCurrLen, histCurrLen); i++) { // Getting the substring std::string s = lookheadBuffer.substr(0, i); size_t pos = historyBuffer.find(s); if (pos == std::string::npos) break; if ((historyBuffer.compare(histCurrLen - i, i, s) == 0) &amp;&amp; (lookheadBuffer[0] == lookheadBuffer[i])) pos = histCurrLen - i; // check if there are any repeats // following the of current longest substring in lookheadBuffer int extra = 0; if (histCurrLen == pos + i) { // Check for full following repeats while ((lookCurrLen &gt;= i + extra + i) &amp;&amp; (lookheadBuffer.compare(i + extra, i, s) == 0)) extra += i; // Check for partial following repeats int extraextra = i - 1; while (extraextra &gt; 0) { if ((lookCurrLen &gt;= i + extra + extraextra) &amp;&amp; (lookheadBuffer.compare(i + extra, extraextra, s, 0, extraextra) == 0)) break; extraextra--; } extra += extraextra; } // Compare the lengths of matches if (n.length &lt;= i + extra) n = Triplet(histCurrLen - pos, i + extra, lookheadBuffer[i + extra]); } return n; } void LZ77::compress() { do { if ((window.lookheadBuffer.length() &lt; window.lookBufferMax) &amp;&amp; (byteDataString.length() != 0)) { int len = window.lookBufferMax - window.lookheadBuffer.length(); window.lookheadBuffer.append(byteDataString, 0, len); byteDataString.erase(0, len); } LZ77::Triplet tiplet = window.findLongestPrefix(); // Move the used part of lookheadBuffer to historyBuffer window.historyBuffer.append(window.lookheadBuffer, 0, tiplet.length + 1); window.lookheadBuffer.erase(0, tiplet.length + 1); // If historyBuffer's size exceeds max, delete oldest part if (window.historyBuffer.length() &gt; window.histBufferMax) window.historyBuffer.erase(0, window.historyBuffer.length() - window.histBufferMax); encoded.push_back(tiplet); } while (window.lookheadBuffer.length()); } void LZ77::decompress() { for (auto code : encoded) { int length = code.length; if (length) { // Getting the substring std::string s = byteDataString.substr(byteDataString.length() - code.offset, std::min(length, code.offset)); // Considering the repeats while (length) { int repeat = std::min(length, static_cast&lt;int&gt;(s.length())); byteDataString.append(s, 0, repeat); length -= repeat; } } byteDataString.append(1, code.next); } } void LZ77::readFileUncompressed(std::filesystem::path&amp; path) { std::ifstream file(path, std::ios::in | std::ios::binary); if (file.is_open()) { // Building the byte data string byteDataString = std::string(std::istreambuf_iterator&lt;char&gt;(file), {}); file.close(); } else throw std::ios_base::failure("Failed to open the file"); } void LZ77::createFileCompressed(std::filesystem::path&amp; path) { std::ofstream out(path / "packed.lz77", std::ios::out | std::ios::binary); if (out.is_open()) { for (auto triplet : encoded) { intToBytes(out, triplet.offset); out &lt;&lt; triplet.next; intToBytes(out, triplet.length); } out.close(); } else throw std::ios_base::failure("Failed to open the file"); } void LZ77::readFileCompressed(std::filesystem::path&amp; path) { std::ifstream file(path, std::ios::in | std::ios::binary); if (file.is_open()) { Triplet element; while (file.peek() != std::ifstream::traits_type::eof()) { element.offset = intFromBytes(file); file.get(element.next); element.length = intFromBytes(file); encoded.push_back(element); } file.close(); } else throw std::ios_base::failure("Failed to open the file"); } void LZ77::createFileUncompressed(std::filesystem::path&amp; path) { std::ofstream out(path / "unpacked.unlz77", std::ios::out | std::ios::binary); out &lt;&lt; byteDataString; out.close(); } </code></pre> <hr> <p>Header file:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;filesystem&gt; #include &lt;algorithm&gt; class LZ77 { struct Triplet { int offset; int length; char next; Triplet() = default; Triplet(int off, int len, char next) : offset(off), length(len), next(next) {}; ~Triplet() = default; }; struct slidingWindow { // History and lookhead buffer std::string lookheadBuffer; std::string historyBuffer; // Max buffers sizes size_t lookBufferMax; size_t histBufferMax; slidingWindow() = default; slidingWindow(std::string hbf, std::string lhbf) : historyBuffer(hbf), lookheadBuffer(lhbf) {} ~slidingWindow() = default; // Function to get longest match Triplet getLongestPrefix(); }; // Sliding window (2 buffers) LZ77::slidingWindow window; // Byte data string std::string byteDataString; // Vector of encoded tuples &lt;offset, length, next&gt; std::vector&lt;Triplet&gt; encoded; public: void compress(); void decompress(); void readFileUncompressed(std::filesystem::path&amp; pathToFile); void createFileCompressed(std::filesystem::path&amp; pathToFile); void readFileCompressed(std::filesystem::path&amp; pathToFile); void createFileUncompressed(std::filesystem::path&amp; pathToFile); void reset() { encoded.clear(); window.historyBuffer.clear(); window.lookheadBuffer.clear(); byteDataString.clear(); } LZ77(size_t lookBufMaxSize, size_t histBufMaxSize) { window.lookBufferMax = lookBufMaxSize * 1024; window.histBufferMax = histBufMaxSize * 1024; }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T12:56:05.630", "Id": "457240", "Score": "0", "body": "It seems that the compression code is the same as in your previous question https://codereview.stackexchange.com/q/233262/35991, and has already been reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:08:33.577", "Id": "457241", "Score": "0", "body": "In that question I specifically asked, if there was a more efficient way of finding longest common match, and yes, that question was answered. \nNow I hope to get a code review in general. Logic, ways to improve time / memory efficiency overall, not only compression specifically" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:32:25.097", "Id": "457242", "Score": "1", "body": "Adding the header file and a small example showing expected results would greatly improve this question and make it much easier to review." } ]
[ { "body": "<h1>Rework the API</h1>\n\n<p>The main issue with your code is the way you structured your API. It is a bit weird and not generic. If I want to compress a file, I need to write four lines of code:</p>\n\n<pre><code>LZ77 lz77(5, 7);\nlz77.readFileUncompressed(\"somepath\");\nlz77.compress();\nlz77.createFileCompressed(\"somepath\");\n</code></pre>\n\n<p>First of all, what numbers should I specify for <code>lookBufMaxSize</code> and <code>histBufMaxSize</code>? Unless I know the algorithm intimately, I don't have any clue what numbers are good. It would be better to have defaults, and a simple way to set these parameters, similar to how gzip has compression levels from 1 to 9.</p>\n\n<p>Second, why do you have to specify a directory, but not the actual filename that is to be read or written? It would be better if the application can choose the complete filename.</p>\n\n<p>Third, I need to read the file, compress it, and write it back in separate steps. But it is very unlikely that I would ever want to run these steps in a different order. So it would make much more sense to have a single function that does everything in one go, so I could write something like:</p>\n\n<pre><code>LZ77 lz77(...);\nlz77.compress(\"somepath/uncompressed.txt\", \"somepath/compressed.lz77\");\n</code></pre>\n\n<p>But then it would even be better to avoid instantiating a class. What if we could just write:</p>\n\n<pre><code>LZ77::compress(\"somepath/uncompressed.txt\", \"somepath/compressed.lz77\");\n</code></pre>\n\n<p>Perhaps with an optional third parameter to set the compression level.\nThis will make the API much simpler, and prevent mistakes from happening.\nFor example, with your API it is probably not safe to reuse an instance of <code>class LZ77</code> without calling <code>reset()</code> between operations.</p>\n\n<p>By limiting the input and output methods of the class to reading and writing files, you have made your code less general than possible. What if an application already has some data in memory, and wants to send a compressed version of it over the network? Having to write it out to file, then compressing it, writing it to another file, and reading back is hugely inefficient. Also, if the application does want to read and write to files, but already has an open input or output stream, it would be much nicer if you could pass in those.</p>\n\n<p>Having a class keeping state would make more sense if you would support some kind of streaming interface, where an application could feed small amounts of data into the state at a time.</p>\n\n<h1>Avoid large temporary buffers</h1>\n\n<p>One way to improve memory usage is to get rid of the temporary buffers, which you can do if you make the API changes I mentioned above. If you are (de)compressing a file of N bytes, this will save you something in the order of 2*N bytes worth of memory.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T22:39:28.710", "Id": "234296", "ParentId": "233865", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T12:40:51.427", "Id": "233865", "Score": "6", "Tags": [ "c++", "performance", "c++17", "compression" ], "Title": "LZ77 compression algorithm (general code efficiency)" }
233865
<p>Could you review the approach and let me know if there is a better way to implement the same using different java techniques (also performant)? </p> <p><strong>Requirement as follows</strong>:</p> <p>The products that are returned for a request, need to be ranked to offer the most relevant product to the user. we will rank based on <strong>weight</strong> and then on <strong>pricePerWeight</strong>.</p> <p>The products will be <strong>ranked on weight first</strong>, and grouped in the following categories:</p> <pre><code>A: Products with an exact weight match as the request (Best match) B: Products with a weight that is higher than the request (Second best) C: Products with a weight that is lower than the request (Third best) D: Products with a different weight measure than the request (Worst match) </code></pre> <p>After the grouping by weight, <strong>the products in each group are ranked by pricePerWeight</strong>, <strong>ascending</strong>. Products that are a group in a particular group (for example group C) can never score higher than a product from a higher group (for example B).</p> <pre><code> import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Test { public static void main(String[] arrays) { final String unit = "grams"; final double quantity = 500; final Sku sku8 = new Sku("123456", 800, "grams", 4); final Sku sku1 = new Sku("234567", 600, "grams", 5); final Sku sku2 = new Sku("354635", 500, "grams", 7); final Sku sku3 = new Sku("345666", 500, "grams", 4); final Sku sku4 = new Sku("234545", 400, "grams", 5); final Sku sku6 = new Sku("765434", 700, "milliliter", 4); final Sku sku5 = new Sku("765434", 500, "milliliter", 3); final Sku sku7 = new Sku("765434", 600, "milliliter", 5); final List&lt;Sku&gt; skus = Arrays.asList(sku8, sku1, sku2, sku3, sku4, sku5, sku6, sku7); final List&lt;Sku&gt; bestMatch = skus.stream() .filter(sku -&gt; unit.equalsIgnoreCase(sku.getUnit()) &amp;&amp; Double.compare(quantity, sku.getQuantity()) == 0) .sorted(Comparator.comparing(Sku::getPricePerWeight)) .collect(Collectors.toList()); final List&lt;Sku&gt; secondBest = skus.stream() .filter(sku -&gt; unit.equalsIgnoreCase(sku.getUnit()) &amp;&amp; Double.compare(quantity, sku.getQuantity()) == -1) .sorted(Comparator.comparing(Sku::getPricePerWeight)) .collect(Collectors.toList()); final List&lt;Sku&gt; thirdBest = skus.stream() .filter(sku -&gt; unit.equalsIgnoreCase(sku.getUnit()) &amp;&amp; Double.compare(quantity, sku.getQuantity()) == 1) .sorted(Comparator.comparing(Sku::getPricePerWeight)).collect(Collectors.toList()); final List&lt;Sku&gt; worstMatch = skus.stream() .filter(skuToProcess -&gt; !unit.equalsIgnoreCase(skuToProcess.getUnit())) .sorted(Comparator.comparing(Sku::getPricePerWeight)) .collect(Collectors.toList()); final List&lt;Sku&gt; sortedSkus = Stream.of(bestMatch, secondBest, thirdBest, worstMatch) .flatMap(Collection::stream) .collect(Collectors.toList()); System.out.println("******Before sort*****"); skus.forEach(skuToPrint -&gt; System.out.println("ID:" + skuToPrint.getId() + " quantity: " + skuToPrint.getQuantity() + " uom: " + skuToPrint.getUnit() + " price: " + skuToPrint.getPricePerWeight())); System.out.println("******sortedSkus*****"); sortedSkus.forEach(skuToPrint -&gt; System.out.println("ID:" + skuToPrint.getId() + " quantity: " + skuToPrint.getQuantity() + " uom: " + skuToPrint.getUnit() + " price: " + skuToPrint.getPricePerWeight())); } </code></pre> <p>Sku class</p> <pre><code>public class Sku { private String id; private double quantity; private String unit; private double pricePerWeight; public String getId() { return id; } public double getQuantity() { return quantity; } public String getUnit() { return unit; } public double getPricePerWeight() { return pricePerWeight; } public Sku(String id, double quantity, String unit, double pricePerWeight) { this.id = id; this.unit = unit; this.quantity = quantity; this.pricePerWeight = pricePerWeight; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:51:04.770", "Id": "457246", "Score": "0", "body": "I see a variable called `pricePerWeight`, where does weight come in, is it quanity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:50:05.100", "Id": "457255", "Score": "0", "body": "_\"and grouped in the following categories:\"_ is part of your requirements. Does this mean they must be grouped into 4 lists and you cannot use a single sorting method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:42:32.717", "Id": "457280", "Score": "0", "body": "@pacmaninbw: **pricePerWeight** comes from a backend system and this has a different price than the price of the product itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:42:36.373", "Id": "457281", "Score": "0", "body": "@dustytrash, I did try to use a Comparator and that did not succeed, hence I came up with the above solution. Though I did not try using a single list to do all the above actions and retrieve, but if we have a different list, it is clear to understand and read on what is captured on it and sorted after that !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:14:59.443", "Id": "457516", "Score": "0", "body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>1) First I suggest that you extract the commons predicates into methods; theres lots of duplicated code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n final List&lt;Sku&gt; bestMatch = getSkuByWeight(skus.stream(), getSkuFilterPredicateByWeight(unit, quantity, 0));\n final List&lt;Sku&gt; secondBest = getSkuByWeight(skus.stream(), getSkuFilterPredicateByWeight(unit, quantity, -1));\n final List&lt;Sku&gt; thirdBest = getSkuByWeight(skus.stream(), getSkuFilterPredicateByWeight(unit, quantity, 1));\n final List&lt;Sku&gt; worstMatch = getSkuByWeight(skus.stream(), skuToProcess -&gt; !unit.equalsIgnoreCase(skuToProcess.getUnit()));\n //[...]\n\n private static &lt;T&gt; List&lt;Sku&gt; getSkuByWeight(Stream&lt;Sku&gt; stream, Predicate&lt;Sku&gt; predicate) {\n return stream.filter(predicate).sorted(Comparator.comparing(Sku::getPricePerWeight)).collect(Collectors.toList());\n }\n\n private static Predicate&lt;Sku&gt; getSkuFilterPredicateByWeight(String unit, double quantity, int toCompare) {\n return sku -&gt; unit.equalsIgnoreCase(sku.getUnit()) &amp;&amp; Double.compare(quantity, sku.getQuantity()) == toCompare;\n }\n</code></pre>\n\n<p>2) You can reuse the string <code>unit</code> in the creation of the Sku objects.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n final Sku sku8 = new Sku(\"123456\", 800, unit, 4);\n final Sku sku1 = new Sku(\"234567\", 600, unit, 5);\n final Sku sku2 = new Sku(\"354635\", 500, unit, 7);\n final Sku sku3 = new Sku(\"345666\", 500, unit, 4);\n final Sku sku4 = new Sku(\"234545\", 400, unit, 5);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T18:50:15.867", "Id": "457294", "Score": "0", "body": "Thank you for taking the time to review firstly.\nFirst one looks possible with the real implementation. \nSecond one can't, because the unit used there for test purpose." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:57:16.500", "Id": "233886", "ParentId": "233868", "Score": "2" } }, { "body": "<h2>Overriding toString</h2>\n\n<p>Inside your Sku class, to print useful info instead of constructing the information outside of the class:</p>\n\n<pre><code>@Override\npublic String toString() {\n return \"ID:\" + getId() + \" quantity: \" + getQuantity() + \" uom: \" + getUnit() + \" price: \" + getPricePerWeight();\n}\n</code></pre>\n\n<p>Then your print statements would look like:</p>\n\n<pre><code>System.out.println(\"******Before sort*****\");\nskus.forEach(skuToPrint -&gt; System.out.println(skuToPrint));\nSystem.out.println(\"******sortedSkus*****\");\nsortedSkus.forEach(skuToPrint -&gt; System.out.println(skuToPrint));\n</code></pre>\n\n<h2>Change variable name 'arrays'</h2>\n\n<p>'args' is pretty standard for command line arguments. 'Arrays' doesn't make sense anyway since it's 1 array</p>\n\n<pre><code>public static void main(String[] arrays) {\n\n// change to:\npublic static void main(String[] args) {\n</code></pre>\n\n<h2>Take advantage of Junit tests</h2>\n\n<p>It's more clear without running your code &amp; no more manually reading the output:</p>\n\n<pre><code>public class SkuTest {\n @Test\n public void testSkuCompareQuantity() {\n final Sku sku8 = new Sku(\"123456\", 800, \"grams\", 4);\n final Sku sku1 = new Sku(\"234567\", 600, \"grams\", 5);\n final Sku sku2 = new Sku(\"354635\", 500, \"grams\", 7);\n final Sku sku3 = new Sku(\"345666\", 500, \"grams\", 4);\n final Sku sku4 = new Sku(\"234545\", 400, \"grams\", 5);\n final Sku sku6 = new Sku(\"765434\", 700, \"milliliter\", 4);\n final Sku sku5 = new Sku(\"765434\", 500, \"milliliter\", 3);\n final Sku sku7 = new Sku(\"765434\", 600, \"milliliter\", 5);\n\n final List&lt;Sku&gt; expectedBestResults = Arrays.asList(sku2, sku3);\n final List&lt;Sku&gt; expectedSecondBestResults = Arrays.asList(sku1, sku8);\n final List&lt;Sku&gt; expectedThirdBestResults = Arrays.asList(sku4);\n final List&lt;Sku&gt; worstResults = Arrays.asList(sku6, sku5, sku7);\n\n final List&lt;Sku&gt; skus = Arrays.asList(sku8, sku1, sku2, sku3, sku4, sku5, sku6, sku7);\n final List&lt;Sku&gt; sortedSkus = SkuSorter.sortSkuList(skus);\n\n // assert best results\n assertTrue(sortedSkus.containsAll(expectedBestResults));\n\n // assert second best results\n assertTrue(sortedSkus.containsAll(expectedSecondBestResults));\n\n // assert third best results\n assertTrue(sortedSkus.containsAll(expectedThirdBestResults));\n\n // assert worst results\n assertTrue(sortedSkus.containsAll(worstResults));\n\n // sanity check\n assertEquals(skus.size(), sortedSkus.size());\n }\n}\n</code></pre>\n\n<p><em>Note: I separated the logic into another class.</em></p>\n\n<h2>Consider using a Comparator or CompareToBuilder</h2>\n\n<pre><code>import java.util.Comparator;\nimport org.apache.commons.lang3.builder.CompareToBuilder;\n\npublic class SkuComparator implements Comparator&lt;Sku&gt; {\n private final String unit;\n private final double quantity;\n\n public SkuComparator(String unit, double quantity) {\n super();\n\n this.unit = unit;\n this.quantity = quantity;\n }\n\n @Override\n public int compare(Sku sku1, Sku sku2) {\n return new CompareToBuilder().append(unit.equalsIgnoreCase(sku1.getUnit()), unit.equalsIgnoreCase(sku2.getUnit()))\n .append(Double.compare(quantity, sku1.getQuantity()), Double.compare(quantity, sku2.getQuantity()))\n .toComparison();\n }\n}\n</code></pre>\n\n<p><em>Notes: tested using above test, it all passes.</em></p>\n\n<p><em>No need to sort by 'worst match', as that already comes last.</em></p>\n\n<p><em>Using the comparator you can sort using: skus = skus.stream().sorted(new SkuComparator(unit, quantity)).collector(Collectors.toList());</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:38:11.777", "Id": "457508", "Score": "0", "body": "Really appreciate your inputs. But the above solution looks to me like not solving the issue entirely, As the grouping works by weight as per the requirement, but not the price sorting as intended. I did put weight grouping in a code block and the price sorting beneath that block, might be that have caused for you to miss that statement. I will change it to as a code block." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:46:22.393", "Id": "233897", "ParentId": "233868", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T12:58:19.657", "Id": "233868", "Score": "5", "Tags": [ "java" ], "Title": "Custom Ranking algorithm" }
233868
<p>I have this code snippet comparing two slice references:</p> <pre><code> fn compare(&amp;self, a: &amp;[u8], b: &amp;[u8]) -&gt; i64 { let mut p1 = a.as_ptr() as *mut u8; let mut p2 = b.as_ptr() as *mut u8; let mut min_len = cmp::min(a.len(), b.len()); let mut ret = 0; while min_len &gt; 0 { unsafe { if *p1 != *p2 { ret = *p1 as i64 - *p2 as i64; break; } else { p1 = p1.offset(1); p2 = p2.offset(1); } } min_len = min_len - 1; } if ret == 0 { if a.len() &lt; b.len() {ret = -1;} else if a.len() &gt; b.len() {ret = 1;} } return ret; } </code></pre> <p>I think I wrote it down in C style. I would like to write this in Rust style.</p> <p>I could replace 'ret' with <code>std::cmp::Ordering</code>. What else could I do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T00:11:03.190", "Id": "457310", "Score": "0", "body": "What is \"Vec\"? Something in Rust? Or just vector?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T01:14:53.840", "Id": "457318", "Score": "0", "body": "@PeterMortensen [Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html) is a standard struct in Rust. However, this question doesn't actually relate to `Vec`s, and only requires a contiguous [`slice`](https://doc.rust-lang.org/std/primitive.slice.html) of memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-24T23:43:45.430", "Id": "462562", "Score": "0", "body": "this would probably be UB in C. Comparing two pointer that are not from the same source is UB. I don't know for Rust." } ]
[ { "body": "<p>The code is very C-like indeed. But fortunately there is no need to resort to raw pointers in that case. Rust has very useful <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html\" rel=\"noreferrer\"><code>Iterator</code></a>s along with a handy method called <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.zip\" rel=\"noreferrer\"><code>zip(...)</code></a> that can be used here. To quote the relevant documentation:</p>\n\n<blockquote>\n <p><code>zip()</code> returns a new iterator that will iterate over two other\n iterators, returning a tuple where the first element comes from the\n first iterator, and the second element comes from the second iterator.</p>\n</blockquote>\n\n<p>Sounds like a good match for what you're trying to do.</p>\n\n<p>Below is the code rewritten using <code>zip()</code> (I omitted <code>&amp;self</code> to make it compile in the <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=36ef2f78418cb77cd68c8b29d239f51f\" rel=\"noreferrer\">Rust playground</a>).</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn compare(a: &amp;[u8], b: &amp;[u8]) -&gt; i64 {\n\n let mut ret = 0;\n for (p1, p2) in a.iter().zip(b.iter()) {\n if p1 != p2 {\n ret = *p1 as i64 - *p2 as i64;\n break;\n }\n }\n\n if ret == 0 {\n if a.len() &lt; b.len() {\n ret = -1;\n }\n else if a.len() &gt; b.len() {\n ret = 1;\n }\n }\n\n ret\n}\n</code></pre>\n\n<p>Since you did not provide any test vectors, you will have to check yourself if the result is fully as expected in your application, and also if there are any major performance hits if that matters to you.</p>\n\n<p>Also, there are likely even more compact versions to write this, because I'm not really highly experienced in Rust programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:22:49.240", "Id": "233873", "ParentId": "233872", "Score": "5" } }, { "body": "<p>What about this:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn compare(a: &amp;[u8], b: &amp;[u8]) -&gt; cmp::Ordering {\n for (ai, bi) in a.iter().zip(b.iter()) {\n match ai.cmp(&amp;bi) {\n Ordering::Equal =&gt; continue,\n ord =&gt; return ord\n }\n }\n\n /* if every single element was equal, compare length */\n a.len().cmp(&amp;b.len())\n}\n</code></pre>\n\n<p>I've removed the <code>self</code> argument, and used the cmp-module to do the actual comparison and <code>zip()</code> as @alexv already suggested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:03:03.820", "Id": "457257", "Score": "2", "body": "How about `match ai.cmp(&bi) { Ordering::Equal => continue, ord => return ord }`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:03:18.897", "Id": "457258", "Score": "0", "body": "@FrenchBoiethios Let's agree to disagree on \"better\" :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:03:37.780", "Id": "457259", "Score": "0", "body": "@trentcl How is my code less idiomatic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:14:32.510", "Id": "457263", "Score": "1", "body": "@FrenchBoiethios I cannot judge if it's less idiomatic, bit it's a hell of a lot harder to read and to follow (at least for a beginner like me)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:19:19.987", "Id": "457264", "Score": "0", "body": "@AlexV That's a typical way of doing in functional programming. That's just a matter of habit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:04:58.167", "Id": "457268", "Score": "3", "body": "@FrenchBoiethios I didn't say it was unidiomatic, I said it wasn't *better*. Good code is readable code. *Really* good code is code that's so stupid obvious, you don't need two brain cells to rub together in order to understand it. In my opinion, the explicit `return` in the `for` loop is more obvious than the implicit `break` hidden in the `find` in your answer. In a code review I'd prefer to be reading larkey's code rather than yours. But that doesn't mean yours is bad; I upvoted both." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:08:35.407", "Id": "457273", "Score": "1", "body": "@trentcl Thanks for the suggestion, my Rust is a bit rusty and I used this as an exercise to get into the language again :)\nI really need to get used to using match more, it's such a nice tool." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:12:22.167", "Id": "457275", "Score": "1", "body": "@FrenchBoiethios I suppose it comes down to the codebase, if this code is part of eg. a proofing framework, I'd rather use your code as I a) expect the contributers to be \"fluent\" in function programming (styles) and b) it's usually nicer to proof formally. If the code is however part of a low-levelish library or such, I'd use my approach as the people there are usually more comfortable with imperative programming. In the end Rust allows for both and a project needs to decide what they want to emphasize. I've updooted your answer as well, it beautifully shows off Rusts features!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:02:35.797", "Id": "457433", "Score": "0", "body": "I find `Iterator::zip(a.iter(), b.iter())` and `Ord::cmp(ai, bi)` more understandable then calling the method directly, but it's arguably (?) less idiomatic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:15:01.940", "Id": "457447", "Score": "0", "body": "Would it be more efficient to compare the lengths before comparing each element?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:26:14.703", "Id": "457489", "Score": "0", "body": "@cartographer I think that is a totally valid alternative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:27:16.687", "Id": "457490", "Score": "0", "body": "@Ben I've tried to achieve the same results as the original code, that's why the length check is at the end and only computed if one vector is the \"prefix\" of the other." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:54:08.913", "Id": "233876", "ParentId": "233872", "Score": "12" } }, { "body": "<p>I take the idea to return an <code>Ordering</code> from the other answer:</p>\n\n<pre><code>use std::cmp;\n\npub fn compare(a: &amp;[u8], b: &amp;[u8]) -&gt; cmp::Ordering {\n a.iter()\n .zip(b)\n .map(|(x, y)| x.cmp(y))\n .find(|&amp;ord| ord != cmp::Ordering::Equal)\n .unwrap_or(a.len().cmp(&amp;b.len()))\n}\n</code></pre>\n\n<p>You can use the powerful Rust iterators:</p>\n\n<ul>\n<li><code>zip</code> allows to iterate both the slices at once,</li>\n<li><code>map</code> transforms each pair to an enum variant representing the ordering of the 2 numbers</li>\n<li><code>find</code> tries to find a pair that isn't equal</li>\n<li>if nothing is found, I return the difference between the slices sizes.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:18:13.820", "Id": "233878", "ParentId": "233872", "Score": "8" } }, { "body": "<p>Also you may compare two slices without using <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.zip\" rel=\"nofollow noreferrer\"><code>zip()</code></a>, try it on the <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=3dd9b33b20da6f95ab733a0c079e992c\" rel=\"nofollow noreferrer\">Rust Playground</a>: </p>\n\n<pre><code>fn compare&lt;T: Ord&gt;(a: &amp;[T], b: &amp;[T]) -&gt; std::cmp::Ordering {\n let mut iter_b = b.iter();\n for v in a {\n match iter_b.next() {\n Some(w) =&gt; match v.cmp(w) {\n std::cmp::Ordering::Equal =&gt; continue,\n ord =&gt; return ord,\n },\n None =&gt; break,\n }\n }\n return a.len().cmp(&amp;b.len());\n}\n\nfn main() {\n assert_eq!(std::cmp::Ordering::Equal, compare(&amp;[1, 2, 3], &amp;[1, 2, 3]));\n assert_eq!(std::cmp::Ordering::Less, compare(&amp;[1, 0], &amp;[1, 2]));\n assert_eq!(std::cmp::Ordering::Less, compare(&amp;[], &amp;[1, 2, 3]));\n assert_eq!(std::cmp::Ordering::Greater, compare(&amp;[1, 2, 3], &amp;[1, 2]));\n assert_eq!(std::cmp::Ordering::Greater, compare(&amp;[1, 3], &amp;[1, 2]));\n}\n\n</code></pre>\n\n<hr>\n\n<p>Code review: </p>\n\n<ol>\n<li><p>You don't need the <code>&amp;self</code> argument, since you did not use it: <code>self</code> parameter is only allowed in associated functions and not semantically valid as a function parameter. note: associated functions are those in <code>impl</code> or <code>trait</code> definitions</p></li>\n<li><p>You need <code>use std::cmp;</code> otherwise rewrite e.g. this: <code>std::cmp::min(a.len(), b.len());</code> </p></li>\n<li><p>It is not common to return <code>-2</code> for <code>compare(&amp;[1, 0], &amp;[1, 2]))</code></p></li>\n<li><p>Use <code>min_len -= 1;</code> instead of <code>min_len = min_len - 1;</code></p></li>\n<li><p>You may use: <code>ret = a.len() as i64 - b.len() as i64;</code> which returns length diff instead of: </p></li>\n</ol>\n\n<pre><code> if a.len() &lt; b.len() {\n ret = -1;\n } else if a.len() &gt; b.len() {\n ret = 1;\n }\n</code></pre>\n\n<ol start=\"6\">\n<li>You don't need <code>else</code> after <code>break</code> here:</li>\n</ol>\n\n<pre><code>if *p1 != *p2 {\n ret = *p1 as i64 - *p2 as i64;\n break;\n }\n</code></pre>\n\n<ol start=\"7\">\n<li>For simple code you may return instead of break:</li>\n</ol>\n\n<pre><code>fn compare(a: &amp;[u8], b: &amp;[u8]) -&gt; i64 {\n let mut p1 = a.as_ptr() as *mut u8;\n let mut p2 = b.as_ptr() as *mut u8;\n let mut min_len = std::cmp::min(a.len(), b.len());\n while min_len &gt; 0 {\n unsafe {\n if *p1 != *p2 {\n return *p1 as i64 - *p2 as i64;\n }\n p1 = p1.offset(1);\n p2 = p2.offset(1);\n }\n min_len -= 1;\n }\n return a.len() as i64 - b.len() as i64;\n}\n</code></pre>\n\n<ol start=\"8\">\n<li>You may simply avoid using <code>unsafe</code> like the following code: </li>\n</ol>\n\n<pre><code>fn compare(a: &amp;[u8], b: &amp;[u8]) -&gt; i64 {\n let mut p1 = a.iter();\n let mut p2 = b.iter();\n let mut min_len = std::cmp::min(a.len(), b.len());\n while min_len &gt; 0 {\n let v = *p1.next().unwrap();\n let w = *p2.next().unwrap();\n if v != w {\n return v as i64 - w as i64;\n }\n min_len -= 1;\n }\n return a.len() as i64 - b.len() as i64;\n}\n</code></pre>\n\n<ol start=\"9\">\n<li>You may use generics for more code reusability:</li>\n</ol>\n\n<pre><code>fn compare&lt;T: Ord&gt;(a: &amp;[T], b: &amp;[T]) -&gt; std::cmp::Ordering {\n let mut p1 = a.iter();\n let mut p2 = b.iter();\n let mut min_len = std::cmp::min(a.len(), b.len());\n while min_len &gt; 0 {\n let v = p1.next().unwrap();\n let w = p2.next().unwrap();\n if v != w {\n return v.cmp(w);\n }\n min_len -= 1;\n }\n return a.len().cmp(&amp;b.len());\n}\n\nfn main() {\n assert_eq!(std::cmp::Ordering::Equal, compare(&amp;[1, 2, 3], &amp;[1, 2, 3]));\n assert_eq!(std::cmp::Ordering::Less, compare(&amp;[1, 0], &amp;[1, 2]));\n assert_eq!(std::cmp::Ordering::Less, compare(&amp;[], &amp;[1, 2, 3]));\n assert_eq!(std::cmp::Ordering::Greater, compare(&amp;[1, 2, 3], &amp;[1, 2]));\n assert_eq!(std::cmp::Ordering::Greater, compare(&amp;[1, 3], &amp;[1, 2]));\n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T14:57:24.383", "Id": "236653", "ParentId": "233872", "Score": "2" } } ]
{ "AcceptedAnswerId": "233876", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T13:46:49.987", "Id": "233872", "Score": "13", "Tags": [ "rust" ], "Title": "Writing slice compare in a more compact way" }
233872
<p>I needed in my project to import .txt files without knowing their encoding, but knowing, they will most likely be in Czech or Slovak language. Sadly there is bunch of possible encodings so I decided to create code, that will try to detect encoding based on content of this <code>ByteArray</code>. </p> <p>Idea is to:</p> <ul> <li>Convert all characters that have different encoding across charsets to their <code>ByteArray</code> representation (in this case characters with accents in Czech and Slovak language).</li> <li>Count their occurrence in original <code>ByteArray</code> for each <code>Charset</code> and calculate it's own rating based on how many characters were found in <code>ByteArray</code> (and character byte size). </li> <li><code>Charset</code> with biggest rating and priority will be chosen (priority in case some charsets are tied).</li> </ul> <p>My current code looks like this (removed some util conversion functions to focus on important bits):</p> <pre><code>const val CZECH_CHARS_LOWER = "říšžťčýůňúěďáéó" const val CZECH_CHARS_UPPER = "ŘÍŠŽŤČÝŮŇÚĚĎÁÉÓ" const val CZECH_CHARS = CZECH_CHARS_LOWER + CZECH_CHARS_UPPER const val SLOVAK_CHARS = "ÄäÔôĹĽĺ" //'ľ' causes problems - has same as 'ž' in other encoding data class CharCountResult(val charset: Charset, val score: Double, val priority: Int = 0) : Comparable&lt;CharCountResult&gt; { override fun compareTo(other: CharCountResult): Int { return if (this.score == other.score) { other.priority.compareTo(this.priority) } else { other.score.compareTo(this.score) } } } class UTFCharsetCharCounter(text: String, priority: Int = 10) : CharsetCharCounter(charsToDetect = text, charset = UTF_8, priority = priority) { override fun autoReject(text: ByteArray): Boolean { return text.countSubArray(UTF8_INVALID_CHARACTER_BYTES) &gt; 0 } override fun autoAccept(text: ByteArray): Boolean { return text.startsWith(UTF8_BOM) } } fun String.toCharsToBytesMap(charset: Charset): Map&lt;Char, ByteArray&gt; { return this.map { it to charset.encode(it.toCharBuffer()).toByteArray() }.toMap() } open class CharsetCharCounter( val charsToDetect: String = CZECH_CHARS + SLOVAK_CHARS, val charset: Charset, val charsToBytes: Map&lt;Char, ByteArray&gt; = charsToDetect.toCharsToBytesMap(charset), val priority: Int = 0 ) { fun count(text: ByteArray): CharCountResult { if (autoReject(text)) { return CharCountResult(charset, 0.0) } if (autoAccept(text)) { return CharCountResult(charset, 100.0) } return CharCountResult(charset, (100.0 * foundCharacters(text) / text.size), priority = priority) } private fun foundCharacters(text: ByteArray): Int { val result = charsToBytes.values.map { val c: Int = text.countSubArray(it) * it.size c }.sum() return result } open fun autoAccept(text: ByteArray): Boolean { return false } open fun autoReject(text: ByteArray): Boolean { return false } } class CharsetDetector( val charCounters: Array&lt;CharsetCharCounter&gt;, val defaultCharset: Charset = UTF_8 ) { fun detect( rawData: ByteArray ): List&lt;CharCountResult&gt; { return charCounters.map { it.count(rawData) }.sorted() } fun smartRead( rawData: ByteArray ): String { val charset = detect(rawData).firstOrNull()?.charset ?: defaultCharset return String(rawData, charset) } companion object { const val CHARS_TO_DETECT = CZECH_CHARS + SLOVAK_CHARS val CZECH_CHAR_COUNTERS = arrayOf( UTFCharsetCharCounter(CHARS_TO_DETECT), CharsetCharCounter(CHARS_TO_DETECT, charset = CP1250, priority = 5), CharsetCharCounter(CHARS_TO_DETECT, charset = ISO_8859_2, priority = 4), CharsetCharCounter(CHARS_TO_DETECT, charset = IBM852, priority = 3) ) val CZECH_CHARSET_DETECTOR = CharsetDetector( charCounters = CZECH_CHAR_COUNTERS ) } } </code></pre> <p>I tried to wrote in so that anyone can use this class for different group of characters and different set of charsets. My questions are (feel free to answer only ones, you like):</p> <ol> <li>What would you change semantically in code in general?</li> <li>How would you improve algorithm?</li> <li>Disadvantage of this approach is, that you need to load whole byte array and try to convert it into String to detect. That could be issue for big data. I was thinking of trying to create <code>InputStream</code>, that would detect encoding and change it "on the fly". Any points to that?</li> <li>Currently this code is JVM-dependent. How would you approach to make this multiplatform?</li> </ol> <p>You can see full code on github:</p> <p><a href="https://github.com/hovi/kotlintools/blob/6d04a7fcda1d0bddecb89984d8e14a9ff18816be/src/jvmMain/kotlin/com/github/hovi/kotlintools/charset/CharsetDetector.kt" rel="nofollow noreferrer">https://github.com/hovi/kotlintools/blob/6d04a7fcda1d0bddecb89984d8e14a9ff18816be/src/jvmMain/kotlin/com/github/hovi/kotlintools/charset/CharsetDetector.kt</a></p> <p>There is also test class:</p> <p><a href="https://github.com/hovi/kotlintools/blob/6d04a7fcda1d0bddecb89984d8e14a9ff18816be/src/jvmTest/kotlin/com/github/hovi/kotlintools/charset/CharsetDetectorTest.kt" rel="nofollow noreferrer">https://github.com/hovi/kotlintools/blob/6d04a7fcda1d0bddecb89984d8e14a9ff18816be/src/jvmTest/kotlin/com/github/hovi/kotlintools/charset/CharsetDetectorTest.kt</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T17:46:18.007", "Id": "457665", "Score": "0", "body": "Your code doesn't compile. For example, the `Charset` is undeclared, which is easy to fix. But when I load the code into my IDE, it cannot determine any import for `CP1252`. Please post the _complete_ compilable code next time. --- There's a rule on this site that once a question has answers, you must not modify your question anymore, to make sure that the answers stay valid. Since none of the answers has mentioned this so far, I'd say it's ok to add the missing imports." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T03:17:02.327", "Id": "457687", "Score": "1", "body": "As mentioned in my question, I left out some of the code to keep only important pieces of code. I'd have to add imports, some functions and also other kotlin files. Including everything would probably double or triple the code here and I'd expect discourage people from digging into it. I linked source code on github if you want to run it. I think that way it's a lot nicer, but please feel fee to tell me what's standard and I will change accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:36:18.177", "Id": "457707", "Score": "0", "body": "Linking to the source code is fine as well. Could you perhaps change the links to not point to the `master` branch but to a fixed commit? Then it would be perfect. Thanks for adding the links." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:01:48.217", "Id": "457718", "Score": "1", "body": "Links have been there since the beginning, changed them to fixed commit. Thanks for the suggestion, will use that regularly here." } ]
[ { "body": "<p>I had a hard time finding out how to actually call this code, because there is no obvious single entry point.</p>\n\n<p>Instead of starting the code with the character constants, you should start it with the main function to be called.</p>\n\n<p>It Kotlin you can define top-level functions, therefore you should not hide the entry point as a method on a constant.</p>\n\n<pre><code>fun loadAutodetectCharset(file: File): String {\n}\n</code></pre>\n\n<p>The remaining classes should be made <code>private</code>, as far as they are implementation details.</p>\n\n<p>How do you intend that other people can plug their own language and encoding detectors into your framework? If it's only by defining the list of characters, they don't need the complicated API of deriving from an open class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T03:24:33.240", "Id": "457689", "Score": "0", "body": "I take it by \"hard time finding out\" you mean by just looking at the code, without looking at the tests? I never really thought of organizing my code in a way so that public API is first to see. Closes thing to what you would call \"top level\" entry point is probably `CharsetDetector.CZECH_CHARSET_DETECTOR`. I don't like overly restricting visibility, I'd rather make more clear, what is public API, but you mentioned, that it isn't clear, fair point. Plugging their own language and detectors is shown is CharsetDetector companion object, ex `CZECH_CHAR_COUNTERS`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:38:47.940", "Id": "457708", "Score": "0", "body": "Yes, exactly. I first tried to only look at the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:45:44.923", "Id": "234030", "ParentId": "233875", "Score": "2" } }, { "body": "<blockquote>\n <p>What would you change semantically in code in general?</p>\n</blockquote>\n\n<ul>\n<li>I'd use the functionality provided by <code>CharsetEncoder</code> and\n<code>CharsetDecoder</code>, rather than performing a map to characters\nthemselves.</li>\n<li>Adding to that, I would also allow 16 bit encodings such as UTF-16 LE and BE, especially since UTF-16LE (under the stupid class name <code>Unicode</code>) is the stupid default for .NET.</li>\n<li>I'd clearly disallow invalid characters, and quickly\ndecide that <em>this is not the charset</em> when they are present.</li>\n</ul>\n\n<blockquote>\n <p>How would you improve algorithm?</p>\n</blockquote>\n\n<ul>\n<li>I'd use\nsome kind of frequency analysis on top of just looking for\nspecific characters.</li>\n<li>Even if specific characters are detected, I would <em>weigh</em> the characters according to the presence in generic texts.</li>\n</ul>\n\n<blockquote>\n <p>Disadvantage of this approach is, that you need to load whole byte array and try to convert it into String to detect. That could be issue for big data. I was thinking of trying to create <code>InputStream</code>, that would detect encoding and change it \"on the fly\". Any points to that?</p>\n</blockquote>\n\n<p>I guess this is similar to the first point I made. The encoders and decoders use <code>ByteBuffer</code> (and <code>CharBuffer</code> for encoding) and that buffer does not need to cover the whole file (and they have specific methods for handling end of buffer).</p>\n\n<blockquote>\n <p>Currently this code is JVM-dependent. How would you approach to make this multiplatform?</p>\n</blockquote>\n\n<p>That I cannot answer, as it depends on what functionality is present on the other platforms. However, you can always define a generic interface to your methods and then implement &amp; test on whatever platform.</p>\n\n<hr>\n\n<p>As a complete out of the box comment, I'd say that this kind of thing is also a good candidate for machine learning. But I guess that depends on the developer having to understand AI to a rather large extend.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T17:52:46.053", "Id": "457666", "Score": "0", "body": "But note that I don't think the code is that bad either. What it does need is documentation and comments of course. Currently we need to guess the purpose of constructions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T03:20:22.523", "Id": "457688", "Score": "0", "body": "Thank you for suggestions. I will definitely add other Unicode encodings, that's good idea. I am already disallowing (auto-rejecting) based on some invalid characters or auto-accepting based on BOM. I get your point with AI and frequency analysis, but this should be rather be small utility with little dependencies. And by better documentation you need documentation outside of code? I am trying to document mostly by naming things correctly and I have feeling it could be done better here (and I already renamed those classes/method bunch of times)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:11:46.600", "Id": "234031", "ParentId": "233875", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:32:59.647", "Id": "233875", "Score": "6", "Tags": [ "kotlin" ], "Title": "Detect charset from raw bytes in Kotlin" }
233875
<p>I am following <a href="https://www.cis.upenn.edu/~cis194/spring13/lectures.html" rel="noreferrer">CIS 194: Introduction to Haskell (Spring 2013)</a> online to teach myself Haskell. Following is my response to third exercise of <a href="https://www.cis.upenn.edu/~cis194/spring13/hw/03-rec-poly.pdf" rel="noreferrer">Homework 3</a>, namely Histogram.</p> <p>In which ways I could improve this, without getting too much into advanced topics of Haskell?</p> <pre><code>{- For this task, write a function histogram :: [Integer] -&gt; String which takes as input a list of Integers between 0 and 9 (inclusive), and outputs a vertical histogram showing how many of each number were in the input list. You may assume that the input list does not contain any numbers less than zero or greater than 9 (that is, it does not matter what your function does if the input does contain such numbers). Your output must exactly match the output shown in the examples below. -} histogram :: [Integer] -&gt; String histogram numbers = let initialcounts = take 10 (repeat 0) calculatedcounts = histogramcount numbers initialcounts maxheight = maximum calculatedcounts linefunctions = map drawline [maxheight,maxheight-1..1] in unlines ((map ($ calculatedcounts) linefunctions) ++ ["==========","0123456789"]) histogramcount :: [Integer] -&gt; [Int] -&gt; [Int] histogramcount [] counts = counts histogramcount (x:xs) counts = let xint = fromIntegral x newcount = (counts !! xint) + 1 in histogramcount xs (take xint counts ++ [newcount] ++ drop (xint+1) counts) drawline :: Int -&gt; [Int] -&gt; String drawline level = map (\x -&gt; if x &gt;= level then '*' else ' ') main = do putStr $ histogram [1,1,1,5] putStr $ histogram [1,4,5,4,6,6,3,4,2,4,9] </code></pre>
[]
[ { "body": "<p>See below for comments on your overall approach, but taking the approach as a given, here are a few observations:</p>\n\n<p>First, it seems unusual to pass <code>initialcounts</code> to <code>histogramcount</code> instead of making <code>histogramcount</code> self-contained. Also, <code>histogramcount</code> is kind of a long name for such a simple function, and <code>take 10 (repeat 0)</code> is more succinctly written <code>replicate 10 0</code>. Finally, the complex step of actually incrementing the count seems like it deserves its own function, so I might write:</p>\n\n<pre><code>-- |Return counts of integers from 0 to 9\ncount :: [Integer] -&gt; [Int]\ncount = loop (replicate 10 0)\n where loop counts (x:xs) = loop (increment x counts) xs\n loop counts [] = counts\n\n-- |Add one to a given count\nincrement :: Integer -&gt; [Int] -&gt; [Int]\nincrement x counts =\n let xint = fromIntegral x\n newcount = (counts !! xint) + 1\n in take xint counts ++ [newcount] ++ drop (xint+1) counts\n</code></pre>\n\n<p>There's no particular reason to name <code>linefunctions</code>, and if you write:</p>\n\n<pre><code>map ($ calculatedcounts) (map drawline [maxheight,maxheight-1..1])\n</code></pre>\n\n<p>a pair of maps like this simplifies to a single map:</p>\n\n<pre><code>map (\\height -&gt; drawline height calculatedcounts) [maxheigh,maxheight-1..1]\n</code></pre>\n\n<p>which might be more clearly written as a list comprehension anyway:</p>\n\n<pre><code>[drawline h calculatedcounts | h &lt;- [maxheight,maxheight-1..1]]\n</code></pre>\n\n<p>giving:</p>\n\n<pre><code>histogram :: [Integer] -&gt; String\nhistogram numbers =\n unlines $ [drawline h counts | h &lt;- [maxh,maxh-1..1]] ++ footer\n where counts = count numbers\n maxh = maximum counts\n footer = [\"==========\",\"0123456789\"]\n</code></pre>\n\n<p>Note that Haskell code usually uses pretty short names for temporary variables. It's also more common to use a <code>where</code> clause rather than a <code>let</code> clause when the variables being defined are just helpers, secondary to the main expression. (Here, <code>counts</code> is arguable <em>not</em> secondary to the main expression, though that raises the question of whether or not we should separate out the function that graphs a set of 10 counts instead of combining it with the counting itself... hmm...)</p>\n\n<p>The <code>drawline</code> function seems okay. Again, maybe a list comprehension is clearer:</p>\n\n<pre><code>drawline :: Int -&gt; [Int] -&gt; String\ndrawline level counts = [if x &gt;= level then '*' else ' ' | x &lt;- counts]\n</code></pre>\n\n<p>or maybe you want to go the route of being excessively clever:</p>\n\n<pre><code>drawline :: Int -&gt; [Int] -&gt; String\ndrawline level = map (bool ' ' '*' . (&gt;= level))\n</code></pre>\n\n<p>Before doing that, we should revisit <code>increment</code>. It's pretty terrible. The take/drop pair can be replaced with the more efficient <code>splitAt</code> standard function which can simultaneously fetch the current count and get everything prepared to update the count, like so:</p>\n\n<pre><code>-- |Add one to a given count\nincrement :: Integer -&gt; [Int] -&gt; [Int]\nincrement x counts =\n case splitAt (fromIntegral x) counts of\n (a,n:b) -&gt; a ++ (n+1):b\n</code></pre>\n\n<p>That's better, and fairly idiomatic. Note the use of <code>a ++ (n+1):b</code> in place of <code>a ++ [n+1] ++ b</code>, too. That's pretty standard.</p>\n\n<p>After you complete next week's lesson, you may discover that <code>count</code> is a fold and rewrite it as:</p>\n\n<pre><code>count :: [Integer] -&gt; [Int]\ncount = foldr increment (replicate 10 0)\n</code></pre>\n\n<p>Further down the line, you may become concerned about whether a left fold would have been better for efficiency purposes, but there's not much point in worrying about that now.</p>\n\n<p>Putting it all together, including breaking <code>histogram</code> up into the counting and the plotting and pulling the <code>drawline</code> helper function into the <code>plot</code> function, I might rewrite your program as:</p>\n\n<pre><code>-- |Plot histogram of counts\nhistogram :: [Integer] -&gt; String\nhistogram = plot . count\n\n-- |Return counts of integers from 0 to 9\ncount :: [Integer] -&gt; [Int]\ncount = foldl (flip increment) (replicate 10 0)\n\n-- |Add one to a given count\nincrement :: Integer -&gt; [Int] -&gt; [Int]\nincrement x counts =\n case splitAt (fromIntegral x) counts of\n (a,n:b) -&gt; a ++ (n+1):b\n\n-- |Plot a vertical bar chart of counts\nplot :: [Int] -&gt; String\nplot counts =\n unlines $ [drawline h | h &lt;- [maxh,maxh-1..1]] ++ footer\n where drawline level = [if x &gt;= level then '*' else ' ' | x &lt;- counts]\n maxh = maximum counts\n footer = [\"==========\",\"0123456789\"]\n\nmain = do\n putStr $ histogram [1,1,1,5]\n putStr $ histogram [1,4,5,4,6,6,3,4,2,4,9]\n</code></pre>\n\n<p>Finally, I'd run <code>hlint</code> on it. It gives \"No hints\", but if I'd run it earlier, it would have mentioned <code>replicate 10 0</code> and recommended a <code>foldl</code> for the <code>count</code> version that used recursive <code>loop</code> calls.</p>\n\n<p>Is this better than your original? Well, I think so, of course, or I wouldn't be writing this. I think the main improvements are:</p>\n\n<ul>\n<li>removing long names for things that aren't very important, like <code>linefunctions</code> or <code>initialcounts</code></li>\n<li>giving top-level names to self-contained actions like <code>count</code>, <code>increment</code>, and <code>plot</code> that perform more well-defined operations than your original \"histogramcount\" and \"drawline\"</li>\n</ul>\n\n<p>Now, let's get back to your overall approach. The main criticism I have is that, like many new Haskell programmers, you're still trying to get over the tendency to use Haskell as an alternate syntax for writing Python (or any other imperative programming language of your choice). You've started with an array of counts:</p>\n\n<pre><code>counts = [0] * 10 # Python syntax!\n</code></pre>\n\n<p>and you've looped over the input data, updating each count as you go:</p>\n\n<pre><code>for c in data:\n counts[c] += 1\n</code></pre>\n\n<p>Unfortunately, Haskell isn't Python, so you've had to represent your running counts as a list. It has to be passed around as an extra argument, and it not only provides inefficient <code>O(n)</code> access to individual elements but also requires creating an updated immutable copy for every processed data point using the abominable expression:</p>\n\n<pre><code>take xint counts ++ [newcount] ++ drop (xint+1) counts\n</code></pre>\n\n<p>or its equally hideous cousin:</p>\n\n<pre><code>case splitAt (fromIntegral x) counts of (a,n:b) -&gt; a ++ (n+1):b\n</code></pre>\n\n<p>Now, one \"improvement\" would be to switch from inefficient lists to an efficient <code>Vector</code> type to hold your counts. Honestly, though, the resulting program would still be designed around your original imperative solution, and we aren't seriously concerned with efficiency here anyway. If we need to process a few million data points, the fact that counting is slow isn't really the biggest issue as we try to generate hundreds of thousands of lines of vertical histogram output.</p>\n\n<p>Instead, to really get a feeling for how Haskell programming is supposed to work, I'd suggest that you take a careful look at <code>Data.List</code> and try to imagine using the functions there as a pipeline of transformations on your data that gradual convert it from <code>[Integer]</code> to <code>String</code>. See if you can do it without keeping track of any intermediate state, like counts or the current line \"level\" or anything like that. As a hint, note that if you were to <code>sort</code> your data and then <code>group</code> it, you'd be close to having a set of required counts.</p>\n\n<h2>SPOILERS</h2>\n\n<p>Here's a super Haskelly solution to this problem. Note how its just a pipeline of functional transformations composed together. Read the pipeline from the bottom-up to understand how it works:</p>\n\n<pre><code>haskellHistogram :: [Integer] -&gt; String\nhaskellHistogram =\n unlines -- and print it as lines\n . reverse -- flip it upside down\n . (['0'..'9']:) . (replicate 10 '-':) -- add the header rows\n . takeWhile (any (=='*')) -- take rows until we run out of stars\n . transpose -- switch from horizontal rows of stars to vertical columns\n . map ( (++ repeat ' ') -- extend with (infinite) spaces\n . flip replicate '*' -- represent count as stars\n . (subtract 1) -- drop the extra number we added\n . length -- get the count\n ) -- for each group\n . group -- group into 0s, 1s, 2s, etc.\n . sort -- sort the input\n . ([0..9]++) -- add one of each to ensure non-zero counts\n</code></pre>\n\n<p>I wrote that in one go, starting at the end of the pipeline and working my way backward, in about 5 minutes. After it type checked and I tested it, I found I'd forgotten the <code>unlines</code> (because my type signature was wrong!) and the <code>subtract 1</code>, but it otherwise worked correctly. That's what makes Haskell programming so much fun.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T23:13:26.823", "Id": "233892", "ParentId": "233877", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:01:59.533", "Id": "233877", "Score": "8", "Tags": [ "beginner", "haskell", "homework" ], "Title": "Cis 194: Homework 3 (Histogram)" }
233877
<p>As you know there is an algorithm in C++ standard library called <code>std::merge</code>, that merges two sorted ranges into another range. I try to write another merge (called <code>multi_merge</code>) that gets multiple sorted ranges (one or more), and merged them in one. The code is as follows:</p> <pre><code>#include &lt;utility&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; template&lt;typename I&gt; using range = std::pair&lt;I, I&gt;; template&lt;typename I&gt; struct is_empty_range { bool operator()(const range&lt;I&gt;&amp; x) const { return x.first == x.second; } }; template&lt;typename I, typename Compare&gt; struct range_compare { range_compare(Compare comp) : comp_{ comp } {} bool operator()(const range&lt;I&gt;&amp; x, const range&lt;I&gt;&amp; y) const { return comp_(*x.first, *y.first); } Compare comp_; }; template&lt;typename I, typename O, typename Compare&gt; O multi_merge(std::vector&lt;range&lt;I&gt;&gt; inputs, O output, Compare comp) { inputs.erase(std::remove_if(std::begin(inputs), std::end(inputs), is_empty_range&lt;I&gt;{}), std::end(inputs)); if (inputs.empty()) return output; while (inputs.size() != 1) { auto min = std::min_element(std::begin(inputs), std::end(inputs), range_compare&lt;I, Compare&gt;{comp}); if (min-&gt;first != min-&gt;second) { *output = *min-&gt;first; ++min-&gt;first; ++output; } else { inputs.erase(min); } } return std::copy(inputs[0].first, inputs[0].second, output); } template&lt;typename I, typename O&gt; O multi_merge(std::vector&lt;range&lt;I&gt;&gt; inputs, O output) { return multi_merge(inputs, output, std::less&lt;typename std::iterator_traits&lt;I&gt;::value_type&gt;{}); } </code></pre> <p>I want to know your opinions about this code, especially the way I'm passing list of ranges (a <code>vector</code> of <code>pair</code>s of iterators) to the algorithm. Do you recommend a more general way?</p> <p>Here is a simple piece of code to test the algorithm:</p> <pre><code>#include &lt;numeric&gt; #include &lt;iostream&gt; int main() { constexpr size_t count = 10000; std::vector&lt;int&gt; v(count); std::iota(v.begin(), v.end(), 0); std::random_shuffle(v.begin(), v.end()); using it_t = std::vector&lt;int&gt;::iterator; std::vector&lt;range&lt;it_t&gt;&gt; inputs; for (auto part = 0u; part &lt;= count - 1000; part += 1000) inputs.emplace_back(v.begin() + part, v.begin() + part + 1000); for (auto r : inputs) std::sort(r.first, r.second); std::vector&lt;int&gt; output; output.reserve(count); multi_merge(inputs, std::back_inserter(output)); std::cout &lt;&lt; std::boolalpha &lt;&lt; "output size is correct: " &lt;&lt; (output.size() == count) &lt;&lt; '\n'; std::cout &lt;&lt; std::boolalpha &lt;&lt; "output is sorted: " &lt;&lt; std::is_sorted(output.begin(), output.end()) &lt;&lt; '\n'; } </code></pre> <p> <a href="https://godbolt.org/z/o3d2zw" rel="noreferrer">Godbolt Link</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:47:21.687", "Id": "457270", "Score": "0", "body": "It might be helpful if you copied the test from the link to here. You leave the link, but links may break." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:54:49.510", "Id": "457271", "Score": "1", "body": "@pacmaninbw Added!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:38:24.547", "Id": "457376", "Score": "0", "body": "Can't you just iterate `std::merge` on the ranges? Just pick an optimal order so at each iteration you merge two similarly sized ranges. I think it will be faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:12:11.683", "Id": "457382", "Score": "0", "body": "@ALX23z It depends. Suppose that you are merging several streams (files, ...)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:43:20.300", "Id": "457408", "Score": "0", "body": "@E.Vakili with slow streams (like network) of unclear size you'd better make a multi threaded version that performs pair merging. But it requires synchronization procedures as well as \"try_read\" instructions - so current interface doesn't fit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T03:54:22.110", "Id": "457473", "Score": "0", "body": "@ALX23z Parallelizing such algorithms is another topic that is also true about `std::merge`. But what about file merging? Although for normal ranges, using `std::merge` requires more memory as temp storage for intermediate merges, and more time because of iterating over each element times and times again. In the above algorithm each element in each range only visited once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:35:55.503", "Id": "457513", "Score": "1", "body": "@E.Vakili no in the above algo you visit each element multiple times - too many times if there are many ranges - which is why it is inefficient for sorting multiple vectors. If you sort file streams bigger bottleneck is reading the files - and if you read multiple files they might slow each other. So I advise more thought into such matters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:36:23.403", "Id": "457550", "Score": "0", "body": "@ALX23z Thanks. I think I missed the point and should do some measurements. I find your notes are at least as better as other answers below." } ]
[ { "body": "<p>It could be my very old eyes, but it seems like this is just a copy rather than a merge, or at least the test is, I don't see where <code>output</code> is being filled with any content prior to the merge.</p>\n<h2>Obsolete C++</h2>\n<p>In the <code>main()</code> function the code is using <code>std::random_shuffle(v.begin(), v.end());</code>, this was <a href=\"https://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow noreferrer\">depreciated in C++14 and removed from C++17</a>.</p>\n<h2>Good Habit in C++ and C</h2>\n<p>Mostly for code maintenance reasons, but also for readability, it is a good habit to wrap the code in if statement or loops in braces (<code>{}</code>) even if the code is only a single statement. This makes it easier to modify the code in the future, and prevents the insertion of bugs in the future when the maintainer is in a rush. Lots of bugs have been caused have been caused by coders adding a single line of code in an if statement or loop.</p>\n<pre><code> if (inputs.empty())\n return output;\n</code></pre>\n<p>is not as maintainable as:</p>\n<pre><code> if (inputs.empty())\n {\n return output;\n }\n</code></pre>\n<p><em>Note <code>multi_merge(std::vector&lt;range&lt;I&gt;&gt; inputs, O output, Compare comp)</code> is inconsistent in the use of braces.</em></p>\n<h2>Avoid Magic Numbers</h2>\n<p>In <code>main()</code> a symbolic constant is created for <code>count</code>, which is 10000, but no symbolic constant is defined for 1000. It would make the code easier to read if it was consistent and there was a symbolic constant for 1000 as well</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:39:39.393", "Id": "457296", "Score": "0", "body": "Thanks, but the test code is only here as a sample for usage of `multi_merge`. I want your thoughts on the algorithm itself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:43:51.517", "Id": "233884", "ParentId": "233879", "Score": "1" } }, { "body": "<ul>\n<li><p><strong>Efficiency</strong></p>\n\n<p>The algorithm is suboptimal. Selecting a <code>min</code> is linear in the number of ranges. Arranging them in a priority queue would make it logarithmic.</p></li>\n<li><p><strong>Correctness</strong></p>\n\n<p>Testing for <code>(min-&gt;first != min-&gt;second)</code> is done too late. <code>min-&gt;first == min-&gt;second</code> means that the empty range participated in the comparison. Which in turn means that the end of that range was dereferenced. UB is imminent.</p>\n\n<p>Since</p>\n\n<pre><code>inputs.erase(std::remove_if(std::begin(inputs), std::end(inputs), is_empty_range&lt;I&gt;{}),\nstd::end(inputs));\n</code></pre>\n\n<p>guarantees that there are no empty ranges at the beginning, I recommend to rewrite the loop as</p>\n\n<pre><code>while (inputs.size() != 1) {\n auto min = std::min_element(std::begin(inputs), std::end(inputs), range_compare&lt;I, Compare&gt;{comp});\n *output = *min-&gt;first;\n ++min-&gt;first;\n ++output;\n\n if (min-&gt;first != min-&gt;second) {\n inputs.erase(min);\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T04:01:05.043", "Id": "457474", "Score": "0", "body": "Thanks. Could you explain more about usage of priority queues?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:33:47.460", "Id": "233904", "ParentId": "233879", "Score": "4" } }, { "body": "<p>I think the algorithm is a bit inefficient (especially when you get a large number of input ranges). Each time around the while loop you are finding the min value you are checking all the ranges.</p>\n\n<p>Rather than doing this I would build a heap. Then extract the top value from the heap each iteration. The value that was extracted (should be value and original range) you can then pull the next value from the original range and add it to the heap. Rince and repeat.</p>\n\n<p>This converts your <code>O(n.m)</code> to <code>O(n.log(m))</code> (n assume each sorted list has n elements and there are m lists).</p>\n\n<pre><code>std::vector&lt;Range&lt;I&gt;&gt; topOfEachHeap;\nfor(auto r: input) {\n topOfEachHeap.emplace_back(r);\n std::push_heap(std::begin(topOfEachHeap), std::end(topOfEachHeap), comp);\n}\n\nwhile (!topOfEachHeap.empty()) {\n std::pop_heap(std::begin(topOfEachHeap), std::end(topOfEachHeap), comp);\n *output = *(topOfEachHeap.back().first);\n\n ++topOfEachHeap.back().first;\n ++output;\n\n if (topOfEachHeap.back().empty()) {\n topOfEachHeap.pop_back();\n }\n else {\n std::push_heap(std::begin(topOfEachHeap), std::end(topOfEachHeap), comp);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T06:17:43.790", "Id": "233959", "ParentId": "233879", "Score": "1" } }, { "body": "<p>The standard library algorithms use, by default, the <code>&lt;</code> operator to compare values, instead of <code>std::less&lt;T&gt;</code>, which can be specialized for different types with different meanings, with pointers being a case in point. Interestingly, <code>std::less&lt;&gt;</code> (which is equivalent to <code>std::less&lt;void&gt;</code>) is specially defined to provide transparent comparison semantics with the <code>&lt;</code> operator. Therefore, this:</p>\n\n<pre><code>template&lt;typename I, typename O&gt;\nO multi_merge(std::vector&lt;range&lt;I&gt;&gt; inputs, O output) {\n return multi_merge(inputs, output, std::less&lt;typename std::iterator_traits&lt;I&gt;::value_type&gt;{});\n}\n</code></pre>\n\n<p>Should be changed to</p>\n\n<pre><code>template&lt;typename I, typename O&gt;\nO multi_merge(std::vector&lt;range&lt;I&gt;&gt; inputs, O output) {\n return multi_merge(inputs, output, std::less&lt;&gt;{});\n}\n</code></pre>\n\n<p>To keep consistent with the standard library conventions. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T07:13:29.573", "Id": "457697", "Score": "0", "body": "You are true but then it can be used with C++14 and above. The original code is tested against C++11." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T07:40:37.417", "Id": "457700", "Score": "0", "body": "@E.Vakili Roll our your own then. It’s no longer than 5 lines." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T00:41:47.543", "Id": "234052", "ParentId": "233879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:46:12.863", "Id": "233879", "Score": "8", "Tags": [ "c++", "algorithm", "generics" ], "Title": "Multi-merge algorithm in C++" }
233879