body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I solved <a href="https://leetcode.com/problems/merge-two-sorted-lists/" rel="nofollow noreferrer">this problem</a>:</p> <blockquote> <p>Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.</p> </blockquote> <p>How can I improve its execution time and also, if there is any better way of doing it?</p> <pre><code>public ListNode mergeTwoLists(ListNode listNode1, ListNode listNode2) { ListNode headNode = new ListNode(0); ListNode node = headNode; while (null != listNode1 &amp;&amp; null != listNode2) { if (listNode1.val &lt; listNode2.val) { node.next = listNode1; listNode1 = listNode1.next; } else { node.next = listNode2; listNode2 = listNode2.next; } node = node.next; } if(null != listNode1) { node.next = listNode1; } if(null != listNode2) { node.next = listNode2; } return headNode.next; } </code></pre>
[]
[ { "body": "<p><strong>LGTM</strong>.</p>\n\n<p>Still a couple of notes:</p>\n\n<ul>\n<li><p>A <code>null</code> in a conditional context evaluates to <code>false</code>. It is safe to omit an explicit comparison to <code>null</code>, along the lines of</p>\n\n<pre><code> while (listNode1 &amp;&amp; listNode2) {\n</code></pre>\n\n<p>Ditto for <code>if (listNode1)</code> and <code>if (listNode2)</code>.</p></li>\n<li><p>Mandatory <em>stability loss</em> notice. The <code>if (listNode1.val &lt; listNode2.val)</code> test loses stability: when the values compare equal, an element from the second list is merged first.</p>\n\n<p>The stability of merge is not required by the problem statement, and doesn't matter for integers. Just be aware.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T13:56:52.413", "Id": "447006", "Score": "1", "body": "`A null in a conditional context evaluates to false` This is not correct. It's a syntax error in Java to not have an explicit test." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-24T23:37:48.393", "Id": "210289", "ParentId": "210287", "Score": "3" } }, { "body": "<p>Scenario will fail if first value is negative and if one list is empty then it wil give error\nBelow is my working code</p>\n\n<pre><code>public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n ListNode first;\n ListNode second;\n if(l1!=null &amp;&amp; l2 !=null) {\n if(l1.val&lt;=l2.val) {\n first = l1;\n l1 =l1.next;\n } else {\n first = l2;\n l2 =l2.next;\n }\n second = first;\n while(l1!=null &amp;&amp; l2!=null) {\n if(l1.val&lt;=l2.val) {\n first.next = l1;\n l1 = l1.next;\n\n } else {\n first.next = l2;\n l2 = l2.next;\n }\n first = first.next;\n }\n if(null != l1) {\n first.next = l1;\n }\n if(null != l2) {\n first.next = l2;\n }\n return second;\n } else {\n if(l2 == null) {\n return l1;\n } else if(l1==null) {\n return l2;\n } else {\n return l1;\n }\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T08:43:33.840", "Id": "446959", "Score": "2", "body": "When providing an alternative offer, it's expected you also review the original code. Could you edit your answer?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T08:40:01.587", "Id": "229687", "ParentId": "210287", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-24T22:06:41.427", "Id": "210287", "Score": "2", "Tags": [ "java", "performance", "programming-challenge" ], "Title": "Merge Two Sorted Lists by splicing together the nodes of the first two lists" }
210287
<h2>Introduction</h2> <p>I'm doing an <strong>OpenGL program in C</strong>. As of now I'm working on the 3D camera system and got the control right. Now I'm working on the mouse control. It works, but I have used two different ways to do it.</p> <h2>The problem</h2> <p>The two different ways are using a global variable and callback, and just using a local variable and function.</p> <p>I don't know which one is better. One seems to loop over itself every time and the other only when the mouse moves, but uses a global variable.</p> <p>For all the following code you will see that the <code>Camera</code> struct is defined as:</p> <pre><code>Camera camera = { .view = GLM_MAT4_IDENTITY_INIT, .pos = { 0.f,0.f,3.f }, .target = { 0.f, 0.f, 0.f }, .upAxe = { 0.0f, 1.0f, 0.0f }, .front = { 0.0f, 0.0f, -1.0 }, .yaw = -90.f, .pitch = 0.f, .lastX = SCR_HEIGHT / 2, .lastY = SCR_WIDTH / 2, .lastFrame = 0.0f, .deltaTime = 0.0f }; </code></pre> <h2>The code</h2> <p><strong>First the "global" way:</strong></p> <p>I have only shown the intended part of the code; other code is not pertinent.</p> <p><code>main.c</code>:</p> <pre><code>void mouseCallBack(GLFWwindow * window, double xpos, double ypos); Camera camera = { .view = GLM_MAT4_IDENTITY_INIT, .pos = { 0.f,0.f,3.f }, .target = { 0.f, 0.f, 0.f }, .upAxe = { 0.0f, 1.0f, 0.0f }, .front = { 0.0f, 0.0f, -1.0 }, .yaw = -90.f, .pitch = 0.f, .lastX = SCR_HEIGHT / 2, .lastY = SCR_WIDTH / 2, .lastFrame = 0.0f, .deltaTime = 0.0f }; int main() { glfwSetCursorPosCallback(window, mouseCallBack); while (!glfwWindowShouldClose(window)) { } } void mouseCallBack(GLFWwindow * window, double xpos, double ypos) { float xoffset = xpos - camera.lastX; float yoffset = camera.lastY - ypos; camera.lastX = xpos; camera.lastY = ypos; float sensivity = 0.05f; xoffset *= sensivity; yoffset *= sensivity; camera.yaw += xoffset; camera.pitch += yoffset; if (camera.pitch &gt; 89.f) camera.pitch = 89.f; if (camera.pitch &lt; -89.f) camera.pitch = -89.f; vec3 front; front[0] = cos(glm_rad(camera.yaw)) * cos(glm_rad(camera.pitch)); front[1] = sin(glm_rad(camera.pitch)); front[2] = sin(glm_rad(camera.yaw)) * cos(glm_rad(camera.pitch)); glm_normalize_to(front, camera.front); } </code></pre> <p><strong>The function and local way:</strong></p> <pre><code>int main() { Camera camera = { .view = GLM_MAT4_IDENTITY_INIT, .pos = { 0.f,0.f,3.f }, .target = { 0.f, 0.f, 0.f }, .upAxe = { 0.0f, 1.0f, 0.0f }, .front = { 0.0f, 0.0f, -1.0 } }; camera.yaw = 0.f; camera.pitch = 0.f; camera.lastX = SCR_HEIGHT / 2; camera.lastY = SCR_WIDTH / 2; camera.lastFrame = 0.0f; camera.deltaTime = 0.0f; while (!glfwWindowShouldClose(window)) { //input processMouse(window, &amp;camera); } } </code></pre> <p>and in <code>GLFWfunction.c</code>:</p> <pre><code>void processMouse(GLFWwindow * window, Camera * camera) { double xpos; double ypos; glfwGetCursorPos(window, &amp;xpos, &amp;ypos); if (xpos != camera-&gt;lastX || ypos != camera-&gt;lastY) { float xoffset = xpos - camera-&gt;lastX; float yoffset = camera-&gt;lastY - ypos; float sensivity = 0.1f; xoffset *= sensivity; yoffset *= sensivity; camera-&gt;yaw += xoffset; camera-&gt;pitch += yoffset; if (camera-&gt;pitch &gt; 89.0f) camera-&gt;pitch = 89.f; if (camera-&gt;pitch &lt; -89.0f) camera-&gt;pitch = -89.f; vec3 front; front[0] = cos(glm_rad(camera-&gt;pitch)) * cos(glm_rad(camera-&gt;yaw)); front[1] = sin(glm_rad(camera-&gt;pitch)); front[2] = sin(glm_rad(camera-&gt;yaw)) * cos(glm_rad(camera-&gt;pitch)); glm_normalize_to(front, camera-&gt;front); camera-&gt;lastX = xpos; camera-&gt;lastY = ypos; } } </code></pre> <p>What would you choose? My eyes tell me that the global alternative is good and clean, but contradict a bit of the C logic whereas the function one is good but is poorly written.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T03:26:03.257", "Id": "406466", "Score": "0", "body": "Why is \"the function one is good but is poorly written?\" They seem identical save for the call to `glfwGetCursorPos()`." } ]
[ { "body": "<p>Is the camera a global entity? Will the only ever be just one?</p>\n\n<p>Perhaps, but perhaps not. You can have two or more viewpoints shown in multiple viewports. You might use shadow mapping, which positions a camera at a light source for rendering a shadow map.</p>\n\n<p>If you are thinking of a generic “mouse controller” for a camera, which you can reuse in multiple applications, I’d shy away from the global camera. </p>\n\n<p>If you are working on a one of a kind application, have no intention of reusing the code, will only ever use one point-of-view, and needs the minuscule speed gain and reduction of complexity of not passing a pointer to the camera around to functions as required, a global camera is fine. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T05:21:12.110", "Id": "210297", "ParentId": "210291", "Score": "4" } } ]
{ "AcceptedAnswerId": "210297", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-24T23:58:22.147", "Id": "210291", "Score": "5", "Tags": [ "c", "comparative-review", "event-handling", "opengl" ], "Title": "Mouse control of a camera in an OpenGL program" }
210291
<blockquote> <h1>The task:</h1> <p>You will receive several input lines in one of the following formats:</p> <ul> <li><code>"{card} - {sport} - {price}"</code></li> <li><code>"check {card}"</code></li> </ul> <p>The card and sport are strings. Price will be a floating point number. You need to keep track of every card. When you receive a card, a sport and a price, register the card in the database if it isn't present, otherwise add the sport and the price. If the card already contains the sport, you need to overwrite the price. If you receive <code>"check {card}"</code> you need to check if the card is available or not and print it on the console in the format: </p> <p><code>"{card} is available!"</code> if the card is present and</p> <p><code>"{card} is not available!"</code> if the card is not present </p> <p>You should end your program when you receive the command <code>"end"</code>. At that point you should print the cards, ordered by sports’ count in desecending order. Foreach card print their sport and price ordered by sports’ name.</p> </blockquote> <h2><a href="https://i.stack.imgur.com/6dKfr.png" rel="nofollow noreferrer">Examples</a></h2> <h3>My Solution</h3> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; class Program { class Card { public Card(string n, string s, double p) { name = n; addSport(s, p); } public void addSport(string sportName, double price) { if (sportPriceInfo.ContainsKey(sportName)) { sportPriceInfo[sportName] = price; } else { sportCount++; sportPriceInfo.Add(sportName, price); } } public string name; public int sportCount = 0; Dictionary&lt;string, double&gt; sportPriceInfo = new Dictionary&lt;string, double&gt;(); public void showInfo() { Console.WriteLine(name + ':'); var sortedDictionary = from pair in sportPriceInfo orderby pair.Key ascending select pair; foreach (var item in sortedDictionary) { Console.WriteLine(" -{0} - {1:0.00}", item.Key, item.Value); } } } class Database { List&lt;Card&gt; allCards = new List&lt;Card&gt;(); public void addCard(string n, string s, double p) { int cardIndex = isCardPresent(n); if (cardIndex &gt;= 0) { allCards[cardIndex].addSport(s, p); } else { allCards.Add(new Card(n, s, p)); } } public void checkCard(string n) { if (isCardPresent(n) &gt;= 0) { Console.WriteLine(n + " is available!"); } else { Console.WriteLine(n + " is not available!"); } } private int isCardPresent(string n) { //returns the index of the matched item, otherwise returns -1 int cardIndex = -1; for (int i = 0; i &lt; allCards.Count; i++) { if (allCards[i].name == n) { cardIndex = i; break; } } return cardIndex; } public void showDataBase() { List&lt;Card&gt; sortedCards = allCards.OrderByDescending(o =&gt; o.sportCount).ToList(); foreach (var card in sortedCards) { card.showInfo(); } } } static void Main() { string line; Database db = new Database(); Match lineSplit; while ((line = Console.ReadLine()) != "end") { if (Regex.IsMatch(line, @"^(\w+) - (\w+) - (\d+.\d+)\b$")) { lineSplit = Regex.Match(line, @"^(\w+) - (\w+) - (\d+.\d+)\b$"); string inputName = lineSplit.Groups[1].Value; string inputSport = lineSplit.Groups[2].Value; double inputPrice = double.Parse(lineSplit.Groups[3].Value); db.addCard(inputName, inputSport, inputPrice); } else { lineSplit = Regex.Match(line, @"^check (\w+)\b$"); db.checkCard(lineSplit.Groups[1].Value); } } db.showDataBase(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T03:40:30.483", "Id": "406646", "Score": "0", "body": "Give your code a bit of breathing room. It's a bit difficult to see where elements begin and end. Microsoft has guidelines: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions#layout-conventions" } ]
[ { "body": "<blockquote>\n<pre><code> public void addSport(string sportName, double price)\n {\n ...\n</code></pre>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n<pre><code> public string name;\n</code></pre>\n</blockquote>\n\n<p>In general the convention in C# is that all public members are named with PascalCase:</p>\n\n<pre><code>public void AddSport(..)\n</code></pre>\n\n<p>and </p>\n\n<pre><code>public string Name;\n</code></pre>\n\n<p>Where private members or local variables are named with camelCase:</p>\n\n<pre><code>private int sportCount = 0;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public int sportCount = 0;\n</code></pre>\n</blockquote>\n\n<p>Counting the sports with a separate variable is unnecessary and error prone. Instead rely on the <code>Count</code> member of the <code>sportPriceInfo</code> <code>Dictionary</code>:</p>\n\n<pre><code>public int Count =&gt; sportPriceInfo.Count;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public void showInfo()\n {\n Console.WriteLine(name + ':');\n var sortedDictionary = from pair in sportPriceInfo\n orderby pair.Key ascending\n select pair;\n foreach (var item in sortedDictionary)\n {\n Console.WriteLine(\" -{0} - {1:0.00}\", item.Key, item.Value);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>In general avoid writing to the console from your model. If you want a model class to be able to write itself then inject a delegate with the appropriate signature:</p>\n\n<pre><code>public delegate void LineWriter(string format, params object[] parameters);\n</code></pre>\n\n<p>and use it like this:</p>\n\n<pre><code> public void showInfo(LineWriter lineWriter)\n {\n lineWriter(\"{0}: \", name);\n var sortedDictionary = from pair in sportPriceInfo\n orderby pair.Key ascending\n select pair;\n foreach (var item in sortedDictionary)\n {\n lineWriter(\" -{0} - {1:0.00}\", item.Key, item.Value);\n }\n }\n</code></pre>\n\n<p>The you can call the method like:</p>\n\n<pre><code>card.showInfo(Console.WriteLine);\n</code></pre>\n\n<p>It is more flexible this way, if you for instance want to write to a log or use <code>Debug.WriteLine</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void addSport(string sportName, double price)\n {\n if (sportPriceInfo.ContainsKey(sportName))\n {\n sportPriceInfo[sportName] = price;\n }\n else\n {\n sportCount++;\n sportPriceInfo.Add(sportName, price);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Here the rule says that a second sport with the same name replaces an existing one, so no need to search for it:</p>\n\n<pre><code>public void addSport(string sportName, double price)\n{\n sportPriceInfo[sportName] = price;\n}\n</code></pre>\n\n<p>this will either replace or add the new sport.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>class Database\n{\n List&lt;Card&gt; allCards = new List&lt;Card&gt;();\n</code></pre>\n</blockquote>\n\n<p>Instead of a <code>List&lt;Card&gt;</code> I would use a <code>Dictionary&lt;string, Card&gt;</code> instance as collection for the cards. It will make the maintenance easier:</p>\n\n<pre><code> public void addCard(string n, string s, double p)\n {\n if (!allCards.TryGetValue(n, out Card card))\n {\n card = new Card(n, s, p);\n allCards[n] = card;\n }\n else\n {\n card.addSport(s, p);\n }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> public bool checkCard(string n) =&gt; allCards.ContainsKey(n); // see below\n</code></pre>\n\n<hr>\n\n<p>BTW: avoid using abbreviated names for method arguments. Instead of <code>n</code>, <code>s</code> and <code>p</code> - <code>name</code>, <code>sport</code> and <code>price</code> would be more informative. Remember that arguments are the \"interface\" that a consumer must rely on - without necessarily knowing about the objects internal behavior.</p>\n\n<p>Again: the name <code>allCards</code> is too \"verbose\". Why not just <code>cards</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void checkCard(string n)\n {\n if (isCardPresent(n) &gt;= 0)\n {\n Console.WriteLine(n + \" is available!\");\n }\n else\n {\n Console.WriteLine(n + \" is not available!\");\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Here again: don't write to the console from your models. Instead return a flag and let the client react accordingly to that:</p>\n\n<pre><code>public bool HasCard(string name) =&gt; allCards.ContainsKey.(name); // If using a dictionary instead of a list.\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> if (Regex.IsMatch(line, @\"^(\\w+) - (\\w+) - (\\d+.\\d+)\\b$\"))\n {\n lineSplit = Regex.Match(line, @\"^(\\w+) - (\\w+) - (\\d+.\\d+)\\b$\");\n</code></pre>\n</blockquote>\n\n<p>Here you parse the string two times with the same pattern. It is unnecessary because you can use the <code>Success</code> property of the returned <code>Match</code> object from <code>Regex.Match()</code>:</p>\n\n<pre><code>Match match = Regex.Match(line, @\"^(\\w+) - (\\w+) - (\\d+.\\d+)\\b$\");\n\nif (match.Success)\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>About the pattern <code>@\"^(\\w+) - (\\w+) - (\\d+.\\d+)\\b$\"</code>:</p>\n\n<p>It doesn't catch names with two or more words or with hyphens or the like.</p>\n\n<p>And if you take a careful look at the input examples in the image, you'll see that the hyphens aren't of equal length, so you'll have to handle both dashes and hyphens.</p>\n\n<p>All in all that could be done with a pattern like:</p>\n\n<pre><code>@\"^(?&lt;card&gt;.+) [-–] (?&lt;sport&gt;.+) [-–] (?&lt;price&gt;\\d+.\\d+)$\"\n</code></pre>\n\n<p>Here I also name the subexpressions so it is possible to query the <code>match</code> object like:</p>\n\n<pre><code> string inputName = lineSplit.Groups[\"card\"].Value;\n string inputSport = lineSplit.Groups[\"sport\"].Value;\n double inputPrice = double.Parse(lineSplit.Groups[\"price\"].Value);\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>double.Parse(lineSplit.Groups[\"price\"].Value)</code></p>\n</blockquote>\n\n<p>When you parse a numeric string you'll have to consider the current locale. So if the input number always uses <code>'.'</code> as decimal separator, you should parse with a <code>IFormatProvider</code> argument:</p>\n\n<pre><code>double.Parse(lineSplit.Groups[\"price\"].Value, CultureInfo.InvariantCulture);\n</code></pre>\n\n<p>Otherwise the parser may interpret the price differently, if the current culture for instance uses <code>','</code> as separator.</p>\n\n<p>If the price is in an invalid format, <code>double.Parse</code> will fail with an exception. You should handle that in a <code>try...catch</code> block, or use <code>double.TryParse(...)</code> instead and handle a false return from that appropriately.</p>\n\n<hr>\n\n<p>When it comes to prices and currency, it is by the way common to use the <code>decimal</code> type instead of <code>double</code>.</p>\n\n<hr>\n\n<p>When I try your method with the two provided input examples it prints <code>\" is not available!\"</code> near the top in both examples?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T18:54:00.687", "Id": "210382", "ParentId": "210295", "Score": "6" } } ]
{ "AcceptedAnswerId": "210382", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T02:48:48.337", "Id": "210295", "Score": "4", "Tags": [ "c#", "performance", "programming-challenge" ], "Title": "Sport Cards Task" }
210295
<p>I am working on an application in C# WPF which reads a large file containing a number of HL7 formatted reports. My application takes in the file, reads and extracts any lines that starts with OBX and stores it into a List. It then tries to extract report headers from the each line, if one exists, based on a handle-full of rules:</p> <ol> <li>Ends with a ':'</li> <li>Is in all caps</li> <li>Is less then 6 words (not include words in brackets)</li> <li>Contains more 4 characters</li> <li>May be on its own in a line or embedded into the content of the string (always at the start)</li> </ol> <p>I have the algorithm down and it works, but I am dealing with files which can contain an upward of a million lines. My initial design took about 10-15 minutes to read and process around 1 million lines. Through hours of research, I was able to optimize the code a bit, bring it to about a few minutes. However, I am hoping to optimize it even further in order to reduce the time it takes for the app to process the lines. This is where I need some help as I do not know what I can do further improve the performance of my code.</p> <p>I was able to narrow down the bottleneck to this method which does the header extraction from the string collected. Below is the most recent version of my method and is as optimized as I can get it (hopefully it will be better with your help):</p> <pre><code> private List&lt;string&gt; GetHeader(List&lt;string&gt; FileLines) { List&lt;string&gt; headers = new List&lt;string&gt;(); foreach (string line in FileLines) { string header = string.Empty; //Checks if there is a ':' and assumes that anything before that is the header except if it contains a date or a report id if(Regex.IsMatch(header, @"\w{2,4}[/\-]\w{2,3}[/\-]\w{2,4}", RegexOptions.Compiled) || Regex.IsMatch(header, @"^\w+, \w{2} \d{5}-{0,1}\d{0,5}", RegexOptions.Compiled)) { continue; } string nobrackets = Regex.Replace(line, @".*?\(.*?\)", string.Empty, RegexOptions.Compiled); if (line.IndexOf(':') != -1) { string nobracks = Regex.Replace(line.Substring(0, line.IndexOf(':') + 1), @"\(.*?\)", string.Empty, RegexOptions.Compiled); if (nobracks.Split(' ').Length &lt; 5 &amp;&amp; nobracks.Length &gt; 6) { headers.Add(line.Substring(0, line.IndexOf(':') + 1)); continue; } } //Checks if a string is larger then 5 words (not including brackets) if (!(nobrackets.Split(' ').Length &lt; 5 &amp;&amp; nobrackets.Length &gt; 6)) continue; //Checks if the string is in all CAPS char[] letter = nobrackets.ToCharArray(); if(letter.All(l =&gt; char.IsUpper(l))){ headers.Add(line); continue; } //Checks if the string is 5 words or less string temp = Regex.Replace(line, @"\(.*?\)", string.Empty, RegexOptions.Compiled); if (temp.Split(' ').Length &lt; 6) { headers.Add(line); } //Checks for an all caps header embedded in a string bool caps = true; string[] word = line.Split(' '); int lastCapWordIndex = 0; for (int i = 0; i &lt; word.Length &amp;&amp; caps; i++) { char[] char_array = word[i].ToCharArray(); if (!letter.All(l =&gt; char.IsUpper(l))) { caps = false; continue; } if (caps) lastCapWordIndex++; } if (lastCapWordIndex &gt; 0) { for (int i = 0; i &lt; lastCapWordIndex; i++) { header += " " + word[i]; } headers.Add(header.Trim()); continue; } } //final check for string with less then 4 characters string[] tempH = headers.ToArray(); headers = new List&lt;string&gt;(); foreach (string h in tempH) { if (h.Length &gt; 4) { headers.Add(h); } } return headers; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T09:54:32.017", "Id": "406475", "Score": "0", "body": "You have many things you can improve here,, most of them with a marginal impacts on performance but one thing catched my eyes: all those regex. Can't you create a single static regex and use it for them all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T12:01:30.393", "Id": "406479", "Score": "0", "body": "It would be great, if you could provide some typical example lines and the expected output for each of them - both valid an invalid formats. Further we need to see, how you actually calls the method - in other words: we need some context in order to fully understand what you are doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T20:14:49.460", "Id": "406500", "Score": "0", "body": "@AdrianoRepetti I initially had one large regex which used OR to determine if it matched on case or another. But I found that it ran slower then using many smaller regex. Maybe I was doing something wrong? For example, I would have @\"\\w{2,4}[/\\-]\\w{2,3}[/\\-]\\w{2,4}|^\\w+, \\w{2} \\d{5}-{0,1}\\d{0,5}\". But this ran a lot slower then making it two regex." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T20:16:46.220", "Id": "406501", "Score": "0", "body": "@HenrikHansen I have added an example to my question, please see the edit at the bottom. Hopefully this helps." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T06:27:01.447", "Id": "406519", "Score": "0", "body": "@k-Rocker: I don't see the change?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T09:21:02.893", "Id": "406531", "Score": "0", "body": "@k I see 5 regex (match/replace), few IndexOf and ToUpper comparisons. All of them should easily fit into one regex for matching and extracting groups. Should, of course, benchmark this but whole code should be a bunch of lines. I don't see usage but you might even yield return if caller performs extra processing (or just consume enumeration). This is also the perfect candidate for async enumerations (if you're targeting next C#)" } ]
[ { "body": "<p>Let us first check the overall style of that method. </p>\n\n<ul>\n<li>The name of the method doesn't match the return type. The method is named <code>GetHeader</code> but it returns a <code>List&lt;string&gt;</code> hence <code>GetHeaders</code> would be a better name. </li>\n<li>Based on the <a href=\"https://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow noreferrer\">.NET Naming Guidelines</a> method-parameters should be named using <code>camelCase</code> casing hence <code>FileLines</code> should be <code>fileLines</code>. </li>\n<li>If the type of the right-hand-side of an assignment is obvious one should use <code>var</code> instead of the concrete type. </li>\n<li><strong>Stick to one coding style</strong>. Currently you are mixing styles in that method. <strong>Sometimes</strong> you place the opening braces <code>{</code> on the next line and sometimes you place it on the same line. <strong>Sometimes</strong> you use braces <code>{}</code> for single-line <code>if</code> statements and sometimes you don't. Omitting braces for single-line <code>if</code> statements should be avoided. Omitting barces can lead to hidden and therefor hard to find bugs. </li>\n</ul>\n\n<hr>\n\n<p>Now let's dig into the code. </p>\n\n<p>This</p>\n\n<blockquote>\n<pre><code>//Checks if there is a ':' and assumes that anything before that is the header except if it contains a date or a report id\nif(Regex.IsMatch(header, @\"\\w{2,4}[/\\-]\\w{2,3}[/\\-]\\w{2,4}\", RegexOptions.Compiled) || Regex.IsMatch(header, @\"^\\w+, \\w{2}\\d{5}-{0,1}\\d{0,5}\", RegexOptions.Compiled))\n{\n continue;\n} \n</code></pre>\n</blockquote>\n\n<p>can be removed completely because it will always evaluate to <code>false</code>. </p>\n\n<hr>\n\n<p>The regexes you use for replacements and matching should be extracted to <code>private static</code> fields like e.g </p>\n\n<pre><code>private static Regex noBracketsRegex = new Regex(@\".*?\\(.*?\\)\", RegexOptions.Compiled);\n</code></pre>\n\n<p>and used like so </p>\n\n<pre><code>string nobrackets = noBracketsRegex.Replace(line, string.Empty);\n</code></pre>\n\n<hr>\n\n<p>This </p>\n\n<blockquote>\n<pre><code>string nobrackets = Regex.Replace(line, @\".*?\\(.*?\\)\", string.Empty, RegexOptions.Compiled);\nif (line.IndexOf(':') != -1)\n{\n string nobracks = Regex.Replace(line.Substring(0, line.IndexOf(':') + 1), @\"\\(.*?\\)\", string.Empty, RegexOptions.Compiled);\n if (nobracks.Split(' ').Length &lt; 5 &amp;&amp; nobracks.Length &gt; 6)\n {\n headers.Add(line.Substring(0, line.IndexOf(':') + 1));\n continue;\n }\n}\n\n//Checks if a string is larger then 5 words (not including brackets)\nif (!(nobrackets.Split(' ').Length &lt; 5 &amp;&amp; nobrackets.Length &gt; 6))\n continue;\n</code></pre>\n</blockquote>\n\n<p>should be reorderd. You do the <code>Regex.Replace()</code> althought it could be possible that the most inner <code>if</code> condition could be <code>true</code>. You should store the result of <code>line.IndexOf(':')</code> in a variable otherwise if <code>line</code> contains a <code>:</code> you are calling <code>IndexOf()</code> twice and if the most inner <code>if</code> returns <code>true</code> you call it three times. Switching the most inner condition to evaluating the fastest condition should be done as well.</p>\n\n<hr>\n\n<p>This </p>\n\n<blockquote>\n<pre><code>string[] word = line.Split(' ');\n</code></pre>\n</blockquote>\n\n<p>should be renamed to <code>words</code>. </p>\n\n<hr>\n\n<p>This </p>\n\n<blockquote>\n<pre><code>for (int i = 0; i &lt; word.Length &amp;&amp; caps; i++)\n{\n char[] char_array = word[i].ToCharArray();\n\n if (!letter.All(l =&gt; char.IsUpper(l)))\n {\n caps = false;\n continue;\n }\n if (caps)\n lastCapWordIndex++;\n} \n</code></pre>\n</blockquote>\n\n<p>doesn't buy you anything. You already checked <code>letter.All(l =&gt; char.IsUpper(l))</code> some lines above and if it returned <code>true</code> you <code>continue;</code> the moste outer loop. Hence it will return in this loop always <code>true</code> hence <code>lastCapWordIndex</code> will always be <code>0</code>. In addition a simple <code>break;</code> would be sufficiant because looping condition checks for <code>caps</code> being <code>true</code>. </p>\n\n<p>The following </p>\n\n<blockquote>\n<pre><code>if (lastCapWordIndex &gt; 0)\n{\n for (int i = 0; i &lt; lastCapWordIndex; i++)\n {\n header += \" \" + word[i];\n }\n headers.Add(header.Trim());\n continue;\n} \n</code></pre>\n</blockquote>\n\n<p>can be removed as well because <code>lastCapWordIndex</code> won't ever be <code>true</code> like stated above.</p>\n\n<hr>\n\n<p>This </p>\n\n<blockquote>\n<pre><code>//final check for string with less then 4 characters\nstring[] tempH = headers.ToArray();\nheaders = new List&lt;string&gt;();\nforeach (string h in tempH)\n{\n if (h.Length &gt; 4)\n {\n headers.Add(h);\n }\n}\nreturn headers; \n</code></pre>\n</blockquote>\n\n<p>can be simplified by using a little bit of Linq like so </p>\n\n<pre><code>return new List&lt;string&gt;(headers.Where(s =&gt; s.Length &gt; 4)); \n</code></pre>\n\n<p>In addition the comment you placed above is lying because you check for strings which are less then 5 characters. </p>\n\n<hr>\n\n<p>Implementing the mentioned points will lead to </p>\n\n<pre><code>private static Regex noBracketsRegex = new Regex(@\".*?\\(.*?\\)\", RegexOptions.Compiled);\nprivate static Regex noBracksRegex = new Regex(@\"\\(.*?\\)\", RegexOptions.Compiled);\nprivate List&lt;string&gt; GetHeaders(List&lt;string&gt; fileLines)\n{\n var headers = new List&lt;string&gt;();\n foreach (string line in fileLines)\n {\n string header = string.Empty;\n\n int colonIndex = line.IndexOf(':');\n if (colonIndex != -1)\n {\n string nobracks = noBracksRegex.Replace(line.Substring(0, colonIndex + 1), string.Empty);\n if (nobracks.Length &gt; 6 &amp;&amp; nobracks.Split(' ').Length &lt; 5)\n {\n headers.Add(line.Substring(0, colonIndex + 1));\n continue;\n }\n }\n\n string removedBracketsLine = noBracketsRegex.Replace(line, string.Empty);\n //Checks if a string is larger then 5 words (not including brackets)\n if (!(removedBracketsLine.Length &gt; 6 &amp;&amp; removedBracketsLine.Split(' ').Length &lt; 5))\n {\n continue;\n }\n\n //Checks if the string is in all CAPS\n char[] letters = removedBracketsLine.ToCharArray();\n if (letters.All(l =&gt; char.IsUpper(l)))\n {\n headers.Add(line);\n continue;\n }\n\n //Checks if the string is 5 words or less\n string temp = noBracksRegex.Replace(line, string.Empty);\n if (temp.Split(' ').Length &lt; 6)\n {\n headers.Add(line);\n }\n\n }\n return new List&lt;string&gt;(headers.Where(s =&gt; s.Length &gt; 4));\n}\n</code></pre>\n\n<p>The naming of the <code>Regex</code> could use a facelift but you should do it yourself because you know the meaning of them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T09:30:03.050", "Id": "210411", "ParentId": "210298", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T05:37:57.237", "Id": "210298", "Score": "3", "Tags": [ "c#", "performance", "regex", "wpf" ], "Title": "Processing a large list of strings" }
210298
<p>I've been studying more C using <em>C Programming: A Modern Approach: A Modern Approach</em> 2nd Edition by K.N. King as well as reading the <a href="http://c-faq.com" rel="nofollow noreferrer">comp.lang.c FAQ</a> and the Code Review section here on Stack Exchange to improve my C skills. I would like your feedback on this recent program I wrote to calculate the volume of a box. It uses ncurses, currently just featuring text input/output but I am planning on expanding on that as I learn more about how to use ncurses.</p> <p>Specifically, I would like to know thoughts on the following:</p> <ol> <li><p>I am currently using an approach of <code>getnstr(*str, n)</code> → temporary buffer → conversion to <code>uint64_t</code>. I have implemented this to prevent buffer overflow attacks. Is my approach a good way to check this? From what I've read, I saw that <code>scanf()</code> family of functions isn't the best choice for scanning input, so I have used advice I previously received here to implement a solution.</p></li> <li><p>Is my approach to "error handling" a good one? Besides gracefully asking again for input upon failure (I know that would be a better approach), is this errno assignment a good practice, or is there a preferred way to do this in C? I saw a few examples online when I searched this, most people used something similar yet others used raise and some used <code>longjmp</code>/<code>setjmp</code>. I know there may be multiple right ways of doing this, but what would be preferred?</p></li> <li><p><code>my_strto64</code> is implemented for conversion to <code>uint64_t</code>. Is this function safe? Can it be improved in any way? This function is a slightly modified version of one I received as feedback from previous code which I had received as an answer to a previous Code Review on here.</p></li> <li><p>Currently I'm just checking the return value of <code>sprintf</code> - I would like to have some way to indicate to the user if the supplied values are not outputting the correct result due to the handling of overflow during multiplication. I know this is quite a simple program as it is, but this is something I was thinking about and I did think of checking the length of each string but couldn't think of a clean way to check proactively on this scenario as the lengths of individual strings aren't enough to ensure the right result after multiplication. It is something I definitely want to learn. I would appreciate any advice on this. I was thinking maybe something like dividing the maximum possible <code>uint64_t</code> value by one of the numbers and then multiplying the other two numbers and comparing results to see the possiblity of overflow.</p></li> <li><p>Should <code>calloc</code>/<code>malloc</code> be used, or a stack-based allocation such as <code>malloca</code>? I have seen some people say it's better to use <code>malloca</code> or an array-based creation for strings on the stack instead of allocating memory on the heap, due to stack memory automatically freeing at the end of a function. Which is a better choice in this scenario?</p></li> </ol> <p>Would appreciate your feedback on the points above and/or anything else you find that can be improved in my code. I always learn a lot from all of you knowledgeable folks here.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;ncurses.h&gt; #include &lt;stdint.h&gt; #include &lt;inttypes.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;limits.h&gt; #define DECSTR_UINT64_MAX_LENGTH 20 int my_strto64(uint64_t *dest, const char *input_str); int main(void) { char tmp_str[DECSTR_UINT64_MAX_LENGTH + 1]; // for input prior to parsing (+1 for NUL) uint64_t height, width, length; // length + 1 (NUL character) char* total_string = calloc(DECSTR_UINT64_MAX_LENGTH + 1, 1); if (!total_string) { errno = ENOMEM; perror("Unable to allocate memory"); return errno; } initscr(); printw("--- Volume Calculator --\n"); printw("Enter length: "); getnstr(tmp_str, DECSTR_UINT64_MAX_LENGTH); if(!my_strto64(&amp;length, tmp_str)) { errno = EIO; perror("Unable to scan length"); return errno; } printw("Enter width: "); getnstr(tmp_str, DECSTR_UINT64_MAX_LENGTH); if(!my_strto64(&amp;width, tmp_str)) { errno = EIO; perror("Unable to scan length"); return errno; } printw("Enter height: "); getnstr(tmp_str, DECSTR_UINT64_MAX_LENGTH); if(!my_strto64(&amp;height, tmp_str)) { errno = EIO; perror("Unable to scan length"); return errno; } int return_value = sprintf(total_string, "Total: %" PRIu64, height * length * width); // sprintf returns a negative value if it fails, so check it if (return_value &lt; 0) { errno = EIO; perror("Cannot multiply height * length * width"); return errno; } printw(total_string); free(total_string); refresh(); getch(); endwin(); return 0; } /** * Converts input_str to uint64_t -&gt; returns 0 on success * Adapted from: https://codereview.stackexchange.com/a/206773/78786 */ int my_strto64(uint64_t *dest, const char *input_str) { char *endptr; errno = 0; unsigned long long parsed_long_long = strtoull(input_str, &amp;endptr, 10); #if ULLONG_MAX &gt; UINT64_MAX if (y &gt; UINT64_MAX) { uint64_t *dest = UINT64_MAX; errno = ERANGE; return errno; } #endif *dest = (uint64_t) parsed_long_long; if (errno == ERANGE) { return errno; } // `strtou...()` function wraps with `-` // lets return an error if its negative if (*dest &amp;&amp; strchr(input_str, '-')) { *dest = 0; errno = ERANGE; return errno; // negative, we don't want it } if (input_str == endptr) { errno = EDOM; return errno; // unsuccessful at converting, still *char } while (isspace((unsigned char) *endptr)) endptr++; if (*endptr) { errno = EIO; return errno; // contains invalid characters } return (int) parsed_long_long; } </code></pre>
[]
[ { "body": "<h2>Error handling</h2>\n\n<p><code>unsigned long long</code> is guaranteed to hold at least 64 bits. If you are using <code>strtoull()</code>, then limiting yourself to <code>uint64_t</code> is just asking for trouble with no benefit. In fact, your conditional code in <code>#if ULLONG_MAX &gt; UINT64_MAX</code> doesn't even compile: there is no such variable <code>y</code>.</p>\n\n<p><strong>What does the return value of <code>my_strto64()</code> represent?</strong> Sometimes, it's an error code. But if there was no error, then it's the <code>parsed_long_long</code>‽ And the <code>parsed_long_long</code> is cast as an <code>int</code> for some reason? That doesn't make sense at all.</p>\n\n<p>In the <code>main()</code> function, if any of the calls to <code>my_strto64()</code> fails, then you terminate the program without calling <code>endwin()</code>, <strong>leaving the terminal in a bad state</strong>.</p>\n\n<p>Realistically, <code>sprintf()</code> is not going to fail in a way that would result in a negative return value. What could possibly go wrong with writing some string to a buffer that has already been allocated? If it's buffer overflow — and <strong>you do have a buffer overflow problem</strong>, because your <code>total_string</code> doesn't have enough space to contain <code>\"Total: \"</code> —, then it's likely to either segfault or fail silently. (To guard against the segfault, you could use <code>snprintf()</code>, but a full buffer would result in a <em>positive</em>, not negative, return value.) If it's integer overflow from the multiplication, then it won't detect it either, since the multiplication is simply done modulo 2<sup>64</sup>. (Unlike <code>sprintf()</code>, <code>printf()</code> might fail, if it tries to write to <code>STDOUT</code> and it is closed. I suppose that <code>printw()</code> could fail too, but you never check for those errors — and I wouldn't bother either.)</p>\n\n<h2>Miscellaneous</h2>\n\n<p>Labelling the output as a \"total\" is a bit weird to me, since it implies that it's a sum rather than a product of the inputs. (Airline luggage rules often place a limit on the length + width + height of an item, for example.)</p>\n\n<p>It is customary to put <code>main()</code> at the end, to avoid needing to write forward declarations.</p>\n\n<p>I suggest putting the <code>#include</code>s in alphabetical order.</p>\n\n<p>The code for reading the three dimensions is <strong>repetitive</strong>. Furthermore, it looks like you have a <strong>copy-and-paste</strong> error, since all three error messages are the same. You should define a helper function.</p>\n\n<p>Using <code>calloc()</code> to allocate a string of a short, limited length is not worth the trouble. Putting it on the stack would be fine. But I wouldn't bother with composing <code>total_string</code> at all — just have <code>printw()</code> format the string for you.</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;limits.h&gt;\n#include &lt;ncurses.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n// Generous estimate of the maximum number of digits\n// https://stackoverflow.com/a/10536254\n#define ULL_DIGITS (3 * sizeof(unsigned long long))\n\n/**\n * Prints a prompt then reads an unsigned long long, using ncurses.\n * Returns 1 on success. Returns 0 on failure, with errno set to\n * ERANGE, EDOM, or EIO.\n */\nint ask_ull(unsigned long long* result, const char *prompt) {\n char buf[ULL_DIGITS + 1];\n char *endptr;\n printw(\"%s\", prompt);\n getnstr(buf, ULL_DIGITS);\n *result = strtoull(buf, &amp;endptr, 10);\n if (errno == ERANGE) { // Overflow or underflow\n return 0;\n }\n if (endptr == buf || strchr(buf, '-')) { // Unsuccessful conversion\n errno = EDOM;\n return 0;\n }\n while (isspace(*endptr)) endptr++;\n if (*endptr) { // Trailing junk\n errno = EIO;\n return 0;\n }\n errno = 0;\n return 1;\n}\n\nint main(void) {\n unsigned long long height, width, length;\n char *errmsg = NULL;\n\n initscr();\n printw(\"--- Volume Calculator --\\n\");\n\n if (!errmsg &amp;&amp; !ask_ull(&amp;length, \"Enter length: \")) {\n errmsg = \"Unable to scan length\";\n }\n if (!errmsg &amp;&amp; !ask_ull(&amp;width, \"Enter width: \")) {\n errmsg = \"Unable to scan width\";\n }\n if (!errmsg &amp;&amp; !ask_ull(&amp;height, \"Enter height: \")) {\n errmsg = \"Unable to scan height\";\n }\n if (errmsg) {\n refresh();\n endwin();\n perror(errmsg);\n return 1;\n }\n\n unsigned long long volume = length * width * height;\n printw(\"Volume: %llu\", volume);\n\n refresh();\n getch();\n endwin();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T13:50:38.947", "Id": "406481", "Score": "0", "body": "Thank you for the in depth answer, I learned a lot. One question I have is why does the function return 0 on errors? Isn't 0 supposed to be indictive of success and any non-zero code failure,? I see you're doing if(!ask_ull), would this work if the function returns an error? Since 0 (success) would skip over the if statement wouldn't it? Is returning errno a better idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T14:17:32.287", "Id": "406483", "Score": "0", "body": "Also is this conversation that I did from string to unsigned long long best practice? Or is there another method that's included in the standard library or a vetted open source library to accomplish this which I should choose instead?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T08:34:55.983", "Id": "210304", "ParentId": "210300", "Score": "3" } } ]
{ "AcceptedAnswerId": "210304", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T06:24:35.517", "Id": "210300", "Score": "0", "Tags": [ "c", "calculator", "integer", "curses" ], "Title": "Calculating the volume of a box" }
210300
<p>I'm trying to solve the Hackerrank's <a href="https://www.hackerrank.com/challenges/insertion-sort/problem" rel="nofollow noreferrer">Insertion Sort Advanced Analysis</a> problem using BST (similar to this <a href="https://stackoverflow.com/q/19945471/244297">question</a> on SO). As I put items in the tree, I need to find out the number of items greater than it (the <code>get_rank()</code> method in the code):</p> <pre><code>class Node: def __init__(self, data): self.left = None self.right = None self.data = data self.num_left_children = 0 self.num_right_children = 0 def insert(self, data): if data &lt;= self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) self.num_left_children += 1 else: if self.right is None: self.right = Node(data) else: self.right.insert(data) self.num_right_children += 1 def get_rank(self, data): if data &lt; self.data: return self.num_right_children + self.left.get_rank(data) + 1 elif data &gt; self.data: return self.right.get_rank(data) else: return self.num_right_children </code></pre> <p>How can I improve the performance of this code (e.g. in case multiple identical items are put into the tree) ?</p>
[]
[ { "body": "<p>Answering my own question, I made these improvements to the code which allowed me to solve the HR problem:</p>\n\n<ul>\n<li><p>Instead of representing duplicate values as separate nodes use a counter of occurrences of the value.</p></li>\n<li><p>Since we need to get the rank of a value immediately after inserting it, we can combine the <code>insert()</code> and <code>get_rank()</code> methods.</p></li>\n<li><p>Turn recursion into iteration.</p></li>\n</ul>\n\n<p>The final code:</p>\n\n<pre><code>class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n self.num_right_children = 0\n self.occurrences = 1\n\n def insert(self, data):\n current_node = self\n rank = 0\n\n while True:\n if data &lt; current_node.data:\n rank += current_node.num_right_children + current_node.occurrences\n if current_node.left is None:\n current_node.left = Node(data)\n break\n current_node = current_node.left\n elif data &gt; current_node.data:\n current_node.num_right_children += 1\n if current_node.right is None:\n current_node.right = Node(data)\n break\n current_node = current_node.right\n else:\n current_node.occurrences += 1\n rank += current_node.num_right_children\n break\n return rank\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T12:50:11.340", "Id": "210551", "ParentId": "210303", "Score": "0" } } ]
{ "AcceptedAnswerId": "210551", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T07:37:41.690", "Id": "210303", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "time-limit-exceeded", "tree" ], "Title": "Find the number of elements larger than a given element in BST" }
210303
<p>I'm writing a byte array at the end of file. The code works fine, but can you please suggest performance improvements?</p> <pre><code>static void Main(string[] args) { string PathToFile = "C:\\myfile.m4a"; WriteAaray(PathToFile, GetMyList()); } public static List&lt;float&gt; GetMyList() { // This list is dynamically generated can go upto 5000 points var mylist = new List&lt;float&gt; { 4, 90, 54, 6, 5324, 423, 432, 4353, 463, 5, 24, 32, 4, 32, 43, 3, 56, 3 }; return mylist; } public static bool WriteAaray(string originalFile, List&lt;float&gt; myFloatPoints) { FileStream inputFileStream = null; inputFileStream = new FileStream(originalFile, FileMode.Open); var length = inputFileStream.Length; inputFileStream.Seek(length, SeekOrigin.Begin); StringBuilder mystring = new StringBuilder(); string myImpPoints = "[MYIMPPOINTS]"; mystring.Append(myImpPoints); var points = string.Join(",", myFloatPoints.Select(f =&gt; f.ToString())); mystring.Append(points); byte[] byteArray = Encoding.ASCII.GetBytes(mystring.ToString()); inputFileStream.Write(byteArray, 0, byteArray.Length); inputFileStream?.Close(); return true; } </code></pre>
[]
[ { "body": "<h3>Code analysis</h3>\n\n<p>Let's run through your code bit by bit.</p>\n\n<p>First a note about paths: use verbatim strings to disable escape sequences, so you don't need to escape those slashes: <code>@\"C:\\myfile.m4a\"</code> instead of <code>\"C:\\\\myfile.m4a\"</code>.</p>\n\n<hr>\n\n<pre><code>public static bool WriteAaray(string originalFile, List&lt;float&gt; myFloatPoints)\n{\n</code></pre>\n\n<ul>\n<li><code>originalFile</code> is a path, not a file (stream), and I'm not sure why it's called 'original', so I would rename it to <code>filePath</code>.</li>\n<li>I'd also fix the typo in <code>Aaray</code>.</li>\n</ul>\n\n<hr>\n\n<pre><code> FileStream inputFileStream = null;\n inputFileStream = new FileStream(originalFile, FileMode.Open);\n</code></pre>\n\n<ul>\n<li>The 'input' in <code>inputFileStream</code> is misleading: you're not reading from this file, you're writing to it. I'd rename it to just <code>file</code>.</li>\n<li>There's no need for that first line: just write <code>var file = new ...</code> instead.</li>\n<li>File streams are disposable, so it's better to use a <code>using</code> statement here.</li>\n<li>Note that the <code>File</code> class contains several useful methods, such as <code>File.Open</code>, or the very convenient <code>File.AppendAllText</code>.</li>\n</ul>\n\n<hr>\n\n<pre><code> var length = inputFileStream.Length;\n inputFileStream.Seek(length, SeekOrigin.Begin);\n</code></pre>\n\n<ul>\n<li>There's no need for that local variable (<code>length</code>): just pass <code>file.Length</code> directly into <code>Seek</code>.</li>\n<li>Instead of manually seeking, consider opening the file with <code>FileMode.Append</code>. Not only does that seek to the end for you, it also creates the file if it doesn't exist yet (in your code that'll throw an exception, which will crash your program because you're not catching it).</li>\n</ul>\n\n<hr>\n\n<pre><code> StringBuilder mystring = new StringBuilder();\n string myImpPoints = \"[MYIMPPOINTS]\";\n mystring.Append(myImpPoints);\n</code></pre>\n\n<ul>\n<li>While string builders are often more efficient than string concatenation, in this case you're only concatenating two strings (this header and the result of that <code>string.Join</code> call), so a string builder won't help here - it might even be less efficient. Note that <code>string.Join</code> uses a string builder internally, and with 5000 floats it certainly is useful there.</li>\n<li>Again, no need for a local variable (<code>myImpPoints</code>) - just pass it into <code>Append</code> directly.</li>\n</ul>\n\n<hr>\n\n<pre><code> var points = string.Join(\",\", myFloatPoints.Select(f =&gt; f.ToString()));\n mystring.Append(points);\n</code></pre>\n\n<ul>\n<li>There's no need for that <code>Select</code> call - one of the overloads of <code>string.Join</code> takes an <code>IEnumerable&lt;T&gt;</code>, so you can pass your list of floats in directly.</li>\n<li>On the other hand, this only gives you 7 digits of precision. If that's a problem, then you should keep the <code>Select</code> part, but be sure to specify <code>\"R\"</code> (round-trip) or <code>\"G9\"</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#GFormatString\" rel=\"noreferrer\">recommended for performance reasons</a>) as the to-string format.</li>\n<li>Again, no need for a local variable (<code>points</code>).</li>\n<li>Note that formatting and parsing string representations of floats is slower than writing and reading them as binary data.</li>\n</ul>\n\n<hr>\n\n<pre><code> byte[] byteArray = Encoding.ASCII.GetBytes(mystring.ToString());\n inputFileStream.Write(byteArray, 0, byteArray.Length);\n inputFileStream?.Close();\n</code></pre>\n\n<ul>\n<li>Consider using a <code>StreamWriter</code> instead. That takes care of encoding and buffering, so you don't have to mess with string builder buffers and byte arrays and all that.</li>\n<li>With a <code>using</code> statement around the file stream, you don't need to call <code>Close</code> manually here. Either way, you don't need an 'elvis operator' here - <code>inputFileStream</code> obviously won't be null.</li>\n</ul>\n\n<hr>\n\n<pre><code> return true;\n}\n</code></pre>\n\n<ul>\n<li>You're returning a boolean to indicate success, but that's actually somewhat misleading: this method <em>can</em> fail, but instead of returning false (which I would expect, with such a method signature) it'll throw an exception. Either catch it and return false (but then the caller won't know why it failed), or don't return anything and let the method throw (but document it).</li>\n</ul>\n\n<h3>Alternatives</h3>\n\n<p>5000 floats isn't a whole lot, so unless you need to create a lot of these files, the following code should be fast enough:</p>\n\n<pre><code>File.AppendAllText(filePath, \"[MYIMPPOINTS]\" + string.Join(\",\", values), Encoding.ASCII);\n</code></pre>\n\n<p>If, after actually measuring performance, that turns out to be too slow, then here's what your code could look like with the above notes taken into account:</p>\n\n<pre><code>using (var file = File.Open(originalFile, FileMode.Append, FileAccess.Write))\nusing (var writer = new StreamWriter(file, Encoding.ASCII)) // buffer size can be adjusted if necessary\n{\n writer.Write(\"[MYIMPPOINTS]\");\n\n if (values.Count &gt; 0)\n writer.Write(values[0]);\n\n for (int i = 1; i &lt; values.Count; i++)\n {\n writer.Write(',');\n writer.Write(values[i]);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:49:35.443", "Id": "210328", "ParentId": "210305", "Score": "6" } }, { "body": "<p>One small addition to Pieter's exhaustive answer. As all you do with myFloatPoints in your WriteAaray method is iterating, you could relax the parameter type to <code>IEnumerable&lt;float&gt;</code>.</p>\n\n<pre><code>public static bool WriteAaray(string originalFile, IEnumerable&lt;float&gt; myFloatPoints)\n</code></pre>\n\n<p>This way it can be called directly not only for <code>List&lt;float&gt;</code>, but also e.g. for <code>float[]</code> or the result of a LINQ expression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T08:27:34.627", "Id": "210682", "ParentId": "210305", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T10:05:17.637", "Id": "210305", "Score": "1", "Tags": [ "c#", "performance", "array", "file", "serialization" ], "Title": "Write byte array to end of file" }
210305
<p>I am coding a bot for Starcraft 2, in which many distances have to be calculated every frame.</p> <p>Here is the part of the library that is being used and I want to improve: <a href="https://github.com/Dentosal/python-sc2/blob/develop/sc2/position.py" rel="nofollow noreferrer">https://github.com/Dentosal/python-sc2/blob/develop/sc2/position.py</a></p> <p>I built a new class <code>Points</code> that inherits from <code>np.ndarray</code>. It is not yet connected to the rest of the library, but the functions are done. I removed the functions <code>furthest_to</code>, <code>further_than</code> and so on because the <code>closer</code>-versions are basically the same execpt a <code>-1</code> or <code>&lt;</code>.</p> <p>Are these functions implemented in most efficient way? Is there a way to improve the parts that look like this:</p> <p><code>find = np.where(np.any(M &lt; distance, axis=1)) selection = np.array([self[i] for i in find[0]])</code></p> <p>Any other comments or suggestions are also welcome :)</p> <pre><code>from typing import Any, Dict, List, Optional, Set, Tuple, Union # for mypy type checking import numpy as np from scipy.spatial.distance import cdist from position import Point2 class Points(np.ndarray): def __new__(cls, units_or_points): obj = np.asarray(units_or_points).view(cls) return obj def closest_to(self, point: Point2) -&gt; Point2: """Returns the point of self that is closest to another point.""" if point in self: return Point2(tuple(point)) deltas = self - point distances = np.einsum("ij,ij-&gt;i", deltas, deltas) result = self[np.argmin(distances)] return Point2(tuple(result)) def closer_than(self, point: Point2, distance: Union[int, float]) -&gt; "Points": """Returns a new Points object with all points of self that are closer than distance to point.""" position = np.array([point]) M = cdist(self, position) find = np.where(np.all(M &lt; distance, axis=1)) selection = np.array([self[i] for i in find[0]]) return Points(selection) def in_distance_between( self, point: Point2, distance1: Union[int, float], distance2: Union[int, float] ) -&gt; "Points": """Returns a new Points object with all points of self that are between distance1 and distance2 away from point.""" p = np.array([point]) M = cdist(self, p) find = np.where(np.any(np.logical_and(distance1 &lt; M, M &lt; distance2), axis=1)) selection = np.array([self[i] for i in find[0]]) return Points(selection) def sort_by_distance_to(self, point: Point2, reverse: bool = False) -&gt; "Points": """Returns a new Points object with all points of self sorted by distance to point. Ordered from smallest to biggest distance. Reverse order with keyword reverse=True.""" deltas = self - point distances = (1 if reverse else -1) * np.einsum("ij,ij-&gt;i", deltas, deltas) result = self[distances.argsort()[::-1]] return Points(result) def closest_n_points(self, point: Point2, n: int) -&gt; "Points": """Returns a new Points object with the n points of self that are closest to point.""" deltas = self - point distances = np.einsum("ij,ij-&gt;i", deltas, deltas) result = (self[distances.argsort()[::-1]])[-n:] return Points(result) def in_distance_of_points(self, points: "Points", distance: Union[int, float]) -&gt; "Points": """Returns a new Points object with every point of self that is in distance of any point in points.""" M = cdist(self, points) find = np.where(np.any(M &lt; distance, axis=1)) selection = np.array([self[i] for i in find[0]]) return Points(selection) def n_closest_to_distance(self, point: Point2, distance: Union[int, float], n: int) -&gt; "Points": """Returns a new Points object with the n points of self which calculated distance to point is closest to distance.""" deltas = self - point distances = np.absolute(distance - np.einsum("ij,ij-&gt;i", deltas, deltas)) result = (self[distances.argsort()[::-1]])[-n:] return Points(result) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T18:23:07.923", "Id": "406497", "Score": "1", "body": "What is a typical size for `Points`, so that timings are meaningful?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T18:29:49.947", "Id": "406498", "Score": "0", "body": "Not all of above functions are currently in the library.I tracked size of the calls for a single game for the function closest:\n`average n of 'closest' call: 13.8`\n`min n of 'closest' call: 2`\n`max n of 'closest' call: 128`\nSo i think if you test with up to 300 for a really late game situation with both players maxed out, it would make a meaningful test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T10:57:00.743", "Id": "406535", "Score": "0", "body": "Also, what is `Point2`. Is it also a subclass of `numpy.ndarray` (since it seems to support subtraction)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T10:58:46.530", "Id": "406536", "Score": "1", "body": "You can see it in the link I provided. It is just an object with x and y coordinates." } ]
[ { "body": "<p>You should probably have another look at the <a href=\"https://docs.scipy.org/doc/scipy/reference/spatial.html\" rel=\"nofollow noreferrer\"><code>scipy.spatial</code></a> module. It provides (hopefully) faster methods for most of these checks using a <a href=\"https://en.wikipedia.org/wiki/K-d_tree\" rel=\"nofollow noreferrer\">k-d-tree</a>.</p>\n\n<pre><code>from scipy.spatial import cKDTree\n\nclass Points(np.ndarray):\n def __new__(cls, units_or_points):\n obj = np.asarray(units_or_points).view(cls)\n obj.kd_tree = cKDTree(obj)\n return obj\n\n def closest_to(self, point: Point2) -&gt; Point2:\n \"\"\"Returns the point of self that is closest to another point.\"\"\"\n _, i = self.kd_tree.query([[point.x, point.y]])\n return Point2(self[i][0])\n\n def closer_than(self, point: Point2, distance: Union[int, float]) -&gt; \"Points\":\n \"\"\"Returns a new Points object with all points of self that\n are closer than distance to point.\"\"\"\n selection = self.kd_tree.query_ball_point([point.x, point.y], distance)\n return self[selection]\n\n def in_distance_between(\n self, point: Point2, distance1: Union[int, float], distance2: Union[int, float]\n ) -&gt; \"Points\":\n \"\"\"Returns a new Points object with all points of self\n that are between distance1 and distance2 away from point.\"\"\"\n selection_close = self.kd_tree.query_ball_point([point.x, point.y], distance1)\n selection_far = self.kd_tree.query_ball_point([point.x, point.y], distance2)\n selection = list(set(selection_far) - set(selection_close))\n return self[selection]\n\n def closest_n_points(self, point: Point2, n: int) -&gt; \"Points\":\n \"\"\"Returns a new Points object with the n points of self that are closest to point.\"\"\"\n _, indices = self.kd_tree.query([[point.x, point.y]], k=n)\n return self[indices]\n\n def in_distance_of_points(self, points: \"Points\", distance: Union[int, float]) -&gt; \"Points\":\n \"\"\"Returns a new Points object with every point of self that\n is in distance of any point in points.\"\"\"\n pairs = self.kd_tree.query_ball_tree(points.kd_tree, distance)\n return points[[i for closest in pairs for i in closest]]\n</code></pre>\n\n<p>These are all the ones I could quickly find a way for using the tree. Not included are <code>sort_by_distance_to</code>, <code>n_closest_to_distance</code> and <code>n_closest_to_distance</code>.</p>\n\n<p>In order to test if this is really faster, here are some tests, with the following setup:</p>\n\n<pre><code>np.random.seed(42)\npoints = np.random.rand(300, 2)\npoints_graipher = Points(points)\npoints_op = PointsOP(points)\npoint = Point2(np.random.rand(2))\npoints2 = np.random.rand(10, 2)\npoints2_graipher = Points(points2)\n</code></pre>\n\n<p>Here <code>PointsOP</code> is you class and <code>Points</code> is the class defined in this answer.</p>\n\n<pre><code>%timeit points_op.closest_to(point)\n# 38.3 µs ± 1.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n%timeit points_graipher.closest_to(point)\n# 43.7 µs ± 249 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n%timeit points_op.closer_than(point, 0.1)\n# 39.5 µs ± 238 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) \n%timeit points_graipher.closer_than(point, 0.1)\n# 11 µs ± 26 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n%timeit points_op.in_distance_between(point, 0.1, 0.2)\n# 52.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n%timeit points_graipher.in_distance_between(point, 0.1, 0.2)\n# 21.9 µs ± 180 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n%timeit points_op.closest_n_points(point, 10)\n# 29.5 µs ± 359 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n%timeit points_graipher.closest_n_points(point, 10)\n# 41.7 µs ± 287 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n%timeit points_op.in_distance_of_points(points2, 0.1)\n# 116 µs ± 727 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n%timeit points_graipher.in_distance_of_points(points2_graipher, 0.1)\n# 89.2 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n\n<p>As you can see for <span class=\"math-container\">\\$N = 300\\$</span> points there are some methods which are faster with the KDTree (up to four times), some that are basically the same and some that are slower (by up to two times).</p>\n\n<p>To get a feeling how the different approaches, scale, here are some plots. The only thing changing is the number of points. The steps are <code>30, 300, 3000, 30000</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/T5t1S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/T5t1S.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/VQxmo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VQxmo.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/17M4T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/17M4T.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/chMJg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/chMJg.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/DZ6rk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DZ6rk.png\" alt=\"enter image description here\"></a></p>\n\n<p>To summarize, you should check this for some actual cases you have. Depending on the size of points your implementation or this implementation is faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:19:42.360", "Id": "406549", "Score": "0", "body": "Thank you for your answer. In the first comment i said n around 300 will be the highest values, most n will be at 20 or so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:22:24.990", "Id": "406550", "Score": "0", "body": "@Tweakimp: Yes, which is why I took 300 as the first case. The larger case was mostly to see if and when the KDTree becomes much better. Will add some plots including also some lower numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:59:46.027", "Id": "406552", "Score": "1", "body": "@Tweakimp: Added those plots." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:07:05.527", "Id": "406553", "Score": "1", "body": "Thank you for all the work you put into this. :) Interesting to see how closest n points is constant..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:08:18.880", "Id": "406554", "Score": "0", "body": "@Tweakimp: Yeah, I was a bit surprised by this as well. Apparently those cuts in the tree are very efficient :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T11:31:25.323", "Id": "210353", "ParentId": "210306", "Score": "3" } } ]
{ "AcceptedAnswerId": "210353", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T10:07:38.447", "Id": "210306", "Score": "4", "Tags": [ "python", "python-3.x", "numpy", "scipy" ], "Title": "Fast distance calculation for Starcraft2 bot" }
210306
<p>I'm trying to get reacquainted with C after years of higher-level languages.</p> <p>I wrote a small fixed-width to CSV converter. It works (for ASCII at least) and it's quite fast, but I wonder if I missed anything or if it can be made even faster.</p> <p>I'm reading the file line by line and process the desired columns (some can be skipped), placing them into an output 8K buffer. I'm using one function to do the substring, appending and trimming trailing space (just the space, in this case I don't want to bother testing for other whitespace characters).</p> <pre><code>#include &lt;ctype.h&gt; // number of columns to process #define COLS 3 #define LINE_SIZE 256 #define BUFFER_SIZE 8192 #define INFILE "in.txt" #define OUTFILE "out.csv" size_t RANGES[COLS][2] = {{0, 6}, {6, 20}, {29, 3}}; /* * Copy from source to destination, up to len chars, trimming trailing spaces * Returns number of chars actually copied */ int trimcpy(char *destination, char *source, size_t len) { // trim spaces from the end - we only care about the space char while (len&gt;0 &amp;&amp; source[len-1]==' ') len--; int i = 0; while (i&lt;len &amp;&amp; *source != '\0') { *destination++ = *source++; i++; } *destination = '\0'; return i; } int main(void) { FILE *rfp; FILE *wfp; char line[LINE_SIZE]; char out[BUFFER_SIZE]; rfp = fopen(INFILE, "r"); if (rfp == NULL) exit(EXIT_FAILURE); wfp = fopen(OUTFILE, "w"); if (wfp == NULL) exit(EXIT_FAILURE); int p = 0; // fgets is 4x faster than getline! while (fgets(line, LINE_SIZE, rfp) != NULL) { // write buffer if almost full (largest column is 20 chars) if (p &gt; BUFFER_SIZE - 20) { fputs(out, wfp); p = 0; } // go through the columns for (int i=0; i&lt;COLS; i++) { p += trimcpy(out+p, line+RANGES[i][0], RANGES[i][1]); p += trimcpy(out+p, i&lt;COLS-1 ? "," : "\n", 1); } } // write any remaining data in buffer fputs(out, wfp); fclose(rfp); fclose(wfp); exit(EXIT_SUCCESS); } </code></pre>
[]
[ { "body": "<p>This code:</p>\n\n<pre><code>int i = 0;\nwhile (i&lt;len &amp;&amp; *source != '\\0') {\n *destination++ = *source++;\n i++;\n}\n*destination = '\\0';\n</code></pre>\n\n<p>shouldn't be doing a byte-by-byte copy. (It should also be a <code>for</code>-loop instead of a <code>while</code> loop, but that's beside the point.) Instead, you should probably just call <code>memcpy</code>:</p>\n\n<pre><code>memcpy(destination, source, len);\ndestination[len] = '\\0';\n</code></pre>\n\n<p>The reference for <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html\" rel=\"nofollow noreferrer\"><code>fopen</code></a> says that:</p>\n\n<blockquote>\n <p>Upon successful completion, <code>fopen()</code> shall return a pointer to the object controlling the stream. Otherwise, a null pointer shall be returned, and <code>errno</code> shall be set to indicate the error. </p>\n</blockquote>\n\n<p>Your invocation here:</p>\n\n<pre><code>rfp = fopen(INFILE, \"r\");\nif (rfp == NULL)\n exit(EXIT_FAILURE);\n</code></pre>\n\n<p>is throwing away the error information. In the failure block, you should be calling <code>perror</code> to see why exactly the call failed.</p>\n\n<p>This:</p>\n\n<pre><code>while (fgets(line, LINE_SIZE, rfp) != NULL) {\n</code></pre>\n\n<p>assumes that <code>NULL</code> only happens if an EOF is encountered, but that isn't necessarily the case. You need to check <code>feof</code>, and if it isn't an EOF, then something bad has happened and you need to again call <code>perror</code> and bail.</p>\n\n<p>A note about the <code>fgets</code> documentation described in the POSIX standard. The \"CX\" in this text:</p>\n\n<blockquote>\n <p>... <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/help/codes.html#CX\" rel=\"nofollow noreferrer\">[CX]</a> and shall set <code>errno</code> to indicate the error. </p>\n</blockquote>\n\n<p>indicates that support for setting <code>errno</code> is in an extension; however, from the same standard:</p>\n\n<blockquote>\n <p>The functionality described is an extension to the ISO C standard. Application developers may make use of an extension as it is supported on all POSIX.1-2017-conforming systems.</p>\n</blockquote>\n\n<p>So as long as you're targeting a system that doesn't violate POSIX, you should be able to use it. Even if a system violated POSIX and didn't set <code>errno</code>, you should still be checking <code>feof</code>; the condition where <code>fgets</code> returns <code>NULL</code> and <code>errno</code> is set to an error would just never be seen. The worst that would happen is a <code>perror</code> indicating that the system doesn't know what the error is, but <em>you</em> still know that there's an error.</p>\n\n<p>Lastly: do some light reading here - <a href=\"https://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main\">https://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main</a></p>\n\n<p>I don't recommend calling <code>exit</code> at the end of <code>main</code>; simply <code>return</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T09:00:28.983", "Id": "406529", "Score": "0", "body": "On `fopen()` error, The C spec says \"If the open operation fails, fopen returns a null pointer.\". There is no spec concerning `errno` with that function - unlike the extension in your reference. OP's code is portable because of that. Using \"you should be calling `perror()`\" can well be un-informative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T09:06:15.127", "Id": "406530", "Score": "0", "body": "The similar advice about \"You need to check feof, ... and you need to again call perror and bail.\" similarly relies on an extension." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T15:03:10.650", "Id": "406585", "Score": "0", "body": "@chux Edited; I stand by my recommendation but I've added more detail about the standard." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T01:42:47.017", "Id": "210334", "ParentId": "210307", "Score": "1" } }, { "body": "<p><strong>Consider <code>const char *</code></strong></p>\n\n<p><code>const char *source</code> allows the function to be used with <code>const</code> strings, better conveys code's functionality and more readily allows for optimizations.</p>\n\n<pre><code>// int trimcpy(char *destination, char *source, size_t len) {\nint trimcpy(char *destination, const char *source, size_t len) {\n</code></pre>\n\n<p><strong>Undefined behavior</strong></p>\n\n<p><code>trimcpy()</code> begins by examining later elements of <code>source[]</code> even though they are not known to have been assigned. The string may not be as long as <code>len</code>.</p>\n\n<pre><code>int trimcpy_alt(char *destination, char *source, size_t len) {\n // Suggest memchr() here rather than strlen() to not look too far.\n char *null_character_pos = memchr(source, '\\0', len);\n if (null_character_pos) len = null_character_pos - source;\n ...\n</code></pre>\n\n<p><strong>Undefined behavior 2</strong></p>\n\n<p>In a selective case of an empty file, the first call to <code>fgets()</code> returns <code>NULL</code> and then the following <code>fputs(out, wfp);</code> is UB as <code>out</code> contents are not initialized. Add initialization or assignment.</p>\n\n<pre><code>char out[BUFFER_SIZE];\nout[0] = '\\0'; // add\n</code></pre>\n\n<p><strong>Not trimming end spaces before \\n</strong></p>\n\n<p><code>trimcpy()</code> does not trim spaces just before <code>'\\n'</code>. I suspect this in not in line with OP's goals.</p>\n\n<p><strong>Avoid redundant information</strong></p>\n\n<p>Redundant information takes more work to maintain. Consider dropping the <code>3</code></p>\n\n<pre><code>// #define COLS 3\nsize_t RANGES[][2] = {{0, 6}, {6, 20}, {29, 3}};\n#define COLS (sizeof RANGES/sizeof RANGES[0])\n</code></pre>\n\n<hr>\n\n<p>Minor things:</p>\n\n<p><strong>Mixing types</strong></p>\n\n<p>Little reason to mix <code>size_t</code> and <code>int</code> types here for array indexing and sizing. Recommend to use just one: <code>size_t</code> (my preference) or 2) <code>int</code>, but not both.</p>\n\n<pre><code>// From\nint trimcpy(char *destination, char *source, size_t len) {\n ...\n int i = 0;\n while (i&lt;len &amp;&amp; *source != '\\0') {\n\n// To\nsize_t trimcpy(char *destination, char *source, size_t len) {\n ...\n size_t i = 0;\n while (i&lt;len &amp;&amp; *source != '\\0') {\n</code></pre>\n\n<p><code>main()</code> </p>\n\n<pre><code> // int p = 0;\n size_t p = 0;\n</code></pre>\n\n<hr>\n\n<p><strong>Subtraction with unsigned types</strong></p>\n\n<p>If above <code>size_t</code> employed, consider the 2 below: Which works well should a later version of code surprisingly define <code>#define BUFFER_SIZE 19</code>?</p>\n\n<pre><code>if (p &gt; BUFFER_SIZE - 20) {\nif (p + 20 &gt; BUFFER_SIZE) {\n</code></pre>\n\n<blockquote class=\"spoiler\">\n <p> The first is the same as <code>if (p &gt; SIZE_MAX) {</code> or <code>if (0) {</code></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T19:10:54.793", "Id": "406775", "Score": "0", "body": "@Armand `null_character_pos - source` subtracts two `char *` pointers. The difference is the length from `source` to `null_character_pos`, the length of the string." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T09:45:17.650", "Id": "210349", "ParentId": "210307", "Score": "2" } } ]
{ "AcceptedAnswerId": "210349", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T10:18:11.770", "Id": "210307", "Score": "4", "Tags": [ "performance", "c", "csv" ], "Title": "Converting fixed-width text file to CSV in C" }
210307
<p>I want to the user to filter a list of receipts by various criteria. Just the regular, an empty filter should show all items, an entry in customer should show all receipts from that customer and an additional entry in date should show all entries from said customer on the given date. I have the feeling, my if else apprach is not the best way, since with 4 criteria I'm already at 16 branches, not speak of 5, 6, or 7 criteria.</p> <p>What is the most elegant way to achieve this. </p> <p>Model:</p> <pre><code>class customer { public int ID { get; set; } public string Name { get; set; } } class receipt { public int ID { get; set; } public string Number { get; set; } public DateTime Date { get; set; } public double Amount { get; set; } public customer Customer { get; set; } } </code></pre> <p>Viewmodel</p> <pre><code>class receiptViewModel { ObservableCollection&lt;receipt&gt; ReceiptList { get; set; } List&lt;receipt&gt; ReceiptListView { get; set; } private string filter; public string Filter { get { return filter; } set { filter = value; if (number != null &amp;&amp; date == null &amp;&amp; customer &amp;&amp; null) { ReceiptListView = ReceiptList.Where(x =&gt; x.Number.Contains(number)).ToList(); } else if (number != null &amp;&amp; date != null &amp;&amp; customer &amp;&amp; null) { ReceiptListView = ReceiptList.Where(x =&gt; x.Number.Contains(number) &amp;&amp; x.Date === date).ToList(); } //aso aso aso } } </code></pre>
[]
[ { "body": "<p>You can build the LINQ query in several steps by appending new where clauses</p>\n\n<pre><code>IEnumerable&lt;receipt&gt; query = ReceiptList;\nif (customer != null) {\n query = query.Where(x =&gt; x.CustomerId == customer.ID);\n}\nif (number != null) {\n query = query.Where(x =&gt; x.Number.Contains(number));\n}\nif (date != null) {\n query = query.Where(x =&gt; x.Date == date);\n}\n...\nReceiptListView = query.ToList();\n</code></pre>\n\n<p>This reduces the complexity from <strong><code>O(2ⁿ)</code></strong> to <strong><code>O(n)</code></strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T00:00:46.057", "Id": "406511", "Score": "2", "body": "It's probably also worth to look into [linqkit's predicatebuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) if more complex predicates have to be put together (say instead of combining all the limitations, wanting \"or\")." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T15:29:54.470", "Id": "210314", "ParentId": "210313", "Score": "13" } } ]
{ "AcceptedAnswerId": "210314", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T15:20:17.873", "Id": "210313", "Score": "12", "Tags": [ "c#", "mvvm" ], "Title": "Filter Collection by Multiple Criteria" }
210313
<p>The code bellow is my implementation for the natural merge exercise in Robert Sedgwick's Algorithms book: </p> <blockquote> <p>Write a version of bottom-up mergesort that takes advantage of order in the array by proceeding as follows each time it needs to find two arrays to merge: find a sorted subarray (by incrementing a pointer until finding an entry that is smaller than its predecessor in the array), then find the next, then merge them.</p> </blockquote> <pre><code>def merge(a, lo, mi, hi): aux_lo = deque(a[lo:mi]) aux_hi = deque(a[mi:hi]) for i in range(lo, hi): if len(aux_lo) and len(aux_hi): a[i] = aux_lo.popleft() if aux_lo[0] &lt; aux_hi[0] else aux_hi.popleft() elif len(aux_lo) or len(aux_hi): a[i] = aux_lo.popleft() if aux_lo else aux_hi.popleft() def find_next_stop(a, start): if start &gt;= len(a)-1: return start stop = start + 1 if a[start] &lt; a[stop]: while(stop&lt;len(a)-1 and a[stop] &lt;= a[stop+1]): stop += 1 else: while(stop&lt;len(a)-1 and a[stop] &gt;= a[stop+1]): stop += 1 _stop = stop while(start&lt;_stop): a[_stop], a[start] = a[start], a[_stop] start += 1 _stop -= 1 return stop def natural_merge(a): lo = hi = 0 while(True): lo = hi mi = find_next_stop(a, lo) if lo == 0 and mi == len(a) - 1: return hi = find_next_stop(a, mi) if mi == hi == len(a)-1: lo = hi = 0 continue merge(a, lo, mi, hi) </code></pre> <p>I referenced <a href="https://codereview.stackexchange.com/a/87334/77243">this answer</a>. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:23:51.723", "Id": "406495", "Score": "0", "body": "Add docstrings and typed arguments. Otherwise it's not bad" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:32:12.053", "Id": "406496", "Score": "1", "body": "A pity the code presented is uncommented but for a cryptic `this takes more space than allowed` - extra constraint(s)? (There's more than one error in `I take this anwser as a referenced.`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T10:05:28.357", "Id": "406533", "Score": "0", "body": "@greybeard Thanks for helping me point out the errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T11:59:56.033", "Id": "406543", "Score": "3", "body": "I've reverted your change. The code in the question should not be updated to ensure that answers stay relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T16:09:26.093", "Id": "406592", "Score": "0", "body": "@Josay But if you could update your answer according to my change reverted by you, I'd appreciate it very much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T20:01:42.557", "Id": "406613", "Score": "0", "body": "@lerner I've updated my answer accordingly and added many other small details" } ]
[ { "body": "<p><strong>Tests and bugs</strong></p>\n\n<p>Your code looks mostly good. Before trying to go and change the code to see what can be improved. I usually try to write a few simple tests. This is even easier when you have a reference implementation that can be compared to your function. In your case, I wrote:</p>\n\n<pre><code>TESTS = [\n [],\n [0],\n [0, 0, 0],\n [0, 1, 2],\n [0, 1, 2, 3, 4, 5],\n [5, 4, 3, 2, 1, 0],\n [5, 2, 3, 1, 0, 4],\n [5, 2, 5, 3, 1, 3, 0, 4, 5],\n]\n\nfor t in TESTS:\n print(t)\n ref_lst, tst_lst = list(t), list(t)\n ref_lst.sort()\n natural_merge(tst_lst)\n print(ref_lst, tst_lst)\n assert ref_lst == tst_lst\n</code></pre>\n\n<p>which leads to a first comment: the empty list is not handled properly and the function never returns.</p>\n\n<p><strong>Improving <code>merge</code></strong></p>\n\n<p>The case <code>elif len(aux_lo) or len(aux_hi)</code> seems complicated as we check <code>if aux_lo</code> just after. Things would be clearer if we were to split in two different cases:</p>\n\n<pre><code> if len(aux_lo) and len(aux_hi):\n a[i] = aux_lo.popleft() if aux_lo[0] &lt; aux_hi[0] else aux_hi.popleft()\n elif len(aux_lo):\n a[i] = aux_lo.popleft()\n elif len(aux_hi):\n a[i] = aux_hi.popleft()\n</code></pre>\n\n<p>Also, we could reuse the fact that in a boolean context, list are considered to be true if and only if they are not empty to write:</p>\n\n<pre><code>for i in range(lo, hi):\n if aux_lo and aux_hi:\n a[i] = aux_lo.popleft() if aux_lo[0] &lt; aux_hi[0] else aux_hi.popleft()\n elif aux_lo:\n a[i] = aux_lo.popleft()\n elif aux_hi:\n a[i] = aux_hi.popleft()\n</code></pre>\n\n<p><strong>Improving <code>find_next_stop</code></strong></p>\n\n<p>You don't need so many parenthesis.</p>\n\n<p>You could store <code>len(a) - 1</code> in a variable in order not to re-compute it every time.</p>\n\n<p>The name <code>_stop</code> is pretty ugly. I do not have any great suggestion for an alternative but <code>end</code> seems okay-ish.</p>\n\n<p><strong>More tests... and more bugs</strong></p>\n\n<p>I wanted to add a few tests to verify an assumption... and I stumbled upon another issue.</p>\n\n<p>Here is the corresponding test suite:</p>\n\n<pre><code>TESTS = [\n [],\n [0],\n [0, 0, 0],\n [0, 1, 2],\n [0, 1, 2, 3, 4, 5],\n [5, 4, 3, 2, 1, 0],\n [0, 1, 2, 2, 1, 0],\n [0, 1, 2, 3, 2, 1, 0],\n [5, 2, 3, 1, 0, 4],\n [5, 2, 5, 3, 1, 3, 0, 4, 5],\n [5, 2, 5, 3, 1, 3, 0, 4, 5, 3, 1, 0, 1, 5, 2, 5, 3, 1, 3, 0, 4, 5],\n]\n</code></pre>\n\n<hr>\n\n<p>Taking into account my comments and the fix you tried to add in the question, we now have:</p>\n\n<pre><code>from collections import deque\n\ndef merge(a, lo, mi, hi):\n aux_lo = deque(a[lo:mi])\n aux_hi = deque(a[mi:hi])\n\n for i in range(lo, hi):\n if aux_lo and aux_hi:\n a[i] = aux_lo.popleft() if aux_lo[0] &lt; aux_hi[0] else aux_hi.popleft()\n elif aux_lo:\n a[i] = aux_lo.popleft()\n elif aux_hi:\n a[i] = aux_hi.popleft()\n\ndef find_next_stop(a, start):\n upper = len(a) - 1\n if start &gt;= upper:\n return start\n\n stop = start + 1\n if a[start] &lt;= a[stop]:\n while stop &lt; upper and a[stop] &lt;= a[stop+1]:\n stop += 1\n else:\n while stop &lt; upper and a[stop] &gt;= a[stop+1]:\n stop += 1\n\n end = stop\n while start &lt; end:\n a[end], a[start] = a[start], a[end]\n start += 1\n end -= 1\n return stop\n\ndef natural_merge(a):\n upper = len(a) - 1\n if upper &lt;= 0:\n return\n lo = hi = 0\n while True:\n lo = hi\n mi = find_next_stop(a, lo)\n if lo == 0 and mi == upper:\n return\n hi = find_next_stop(a, mi)\n if mi == hi == upper:\n lo = hi = 0\n else:\n merge(a, lo, mi, hi)\n\n\n\nTESTS = [\n [],\n [0],\n [0, 0, 0],\n [0, 1, 2],\n [0, 1, 2, 3, 4, 5],\n [5, 4, 3, 2, 1, 0],\n [0, 1, 2, 2, 1, 0],\n [0, 1, 2, 3, 2, 1, 0],\n [5, 2, 3, 1, 0, 4],\n [5, 2, 5, 3, 1, 3, 0, 4, 5],\n [5, 2, 5, 3, 1, 3, 0, 4, 5, 3, 1, 0, 1, 5, 2, 5, 3, 1, 3, 0, 4, 5],\n]\n\nfor t in TESTS:\n print(t)\n ref_lst, tst_lst = list(t), list(t)\n ref_lst.sort()\n natural_merge(tst_lst)\n print(ref_lst, tst_lst)\n assert ref_lst == tst_lst\n</code></pre>\n\n<p><strong>More improvements in <code>find_next_stop</code></strong></p>\n\n<p>We have a <code>while</code> loop but we can compute the number of iterations we'll need: it corresponds to have the distance between <code>start</code> and <code>stop</code>. We could use a <code>for _ in range</code> loop to perform this. It has pros and cons but one of the key aspect is that we do not need to change <code>start</code> and <code>stop</code>, thus we don't need to copy the value in a variable.</p>\n\n<pre><code> for k in range((1 + stop - start) // 2):\n i, j = start + k, stop - k\n a[i], a[j] = a[j], a[i]\n</code></pre>\n\n<p><strong>More improvements in <code>natural_merge</code></strong></p>\n\n<p>A few steps can be used to re-organise the function:</p>\n\n<ul>\n<li>see that we can move the assignment <code>lo = hi</code> from the beginning of the loop to the end of the loop with no impact</li>\n<li>realise that it is already done in the first branch of the test already so move it to the <code>else</code> block exclusively</li>\n<li>see that the initialisation of <code>hi</code> is not required anymore</li>\n<li>notice that the condition <code>mi == upper</code> is checked in 2 places (with the same value of <code>mi</code> and <code>upper</code> and that if <code>lo != 0</code>, we see that <code>mi == upper</code> directly leads to <code>find_next(a, mi)</code> returning <code>upper</code> and thus ending with <code>mi == hi == upper</code> and thus to the assignment <code>lo = hi = 0</code>.</li>\n</ul>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def natural_merge(a):\n upper = len(a) - 1\n if upper &lt;= 0:\n return\n lo = 0\n while True:\n mi = find_next_stop(a, lo)\n if mi == upper:\n if lo == 0:\n return\n lo = hi = 0\n else:\n hi = find_next_stop(a, mi)\n merge(a, lo, mi, hi)\n lo = hi\n</code></pre>\n\n<p>We can go further:</p>\n\n<ul>\n<li>the assignment <code>hi = 0</code> has no effect</li>\n<li>we can reorganise conditions</li>\n</ul>\n\n<p>We'd get</p>\n\n<pre><code>def natural_merge(a):\n upper = len(a) - 1\n if upper &lt;= 0:\n return\n lo = 0\n while True:\n mi = find_next_stop(a, lo)\n if mi != upper:\n hi = find_next_stop(a, mi)\n merge(a, lo, mi, hi)\n lo = hi\n elif lo == 0:\n return\n else:\n lo = 0\n</code></pre>\n\n<p>Interestingly, removing <code>lo = hi</code> leads a much more efficient code on my benchmark: the function returns much more quickly (because we always have <code>lo == 0</code>, we get out of the loop as soon as <code>mi == upper</code>) and the list is still fully sorted.</p>\n\n<pre><code>def natural_merge(a):\n upper = len(a) - 1\n if upper &lt;= 0:\n return\n while True:\n mi = find_next_stop(a, 0)\n if mi == upper:\n return\n hi = find_next_stop(a, mi)\n merge(a, 0, mi, hi)\n</code></pre>\n\n<p>This looked surprising at first but thinking about it, it looks like this may be the way this algorithm is supposed to be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T23:57:33.937", "Id": "408697", "Score": "0", "body": "I've realized the meaning of the last snippet in your answer, awesome!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T23:25:02.657", "Id": "210332", "ParentId": "210315", "Score": "4" } } ]
{ "AcceptedAnswerId": "210332", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:14:59.753", "Id": "210315", "Score": "4", "Tags": [ "python", "algorithm", "python-3.x", "sorting", "mergesort" ], "Title": "Natural merge: mergesort that uses already sorted subarrays" }
210315
<p>This program calculates with numbers from different number systems and outputs the result in the desired number system.</p> <p>You call it like that:</p> <pre><code>java Calculator &lt;operator&gt; &lt;number&gt; &lt;base&gt; &lt;otherNumber&gt; &lt;base&gt; (solutionBase) </code></pre> <p>Unfortunately it does not work with floating point numbers.</p> <p>Example:</p> <pre><code>$java Calculator + 5234 7 FABCD43 16 3 200022201200110011 </code></pre> <p>My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?</p> <pre><code>public class Calculator { public static void main(String[] args) { // display usage if user wants so if (args[0].contains("help")) { displayHelp(); return; } // parse arguments String operator = args[0]; String number1 = args[1]; int baseOfNumber1 = Integer.parseInt(args[2]); String number2 = args[3]; int baseOfNumber2 = Integer.parseInt(args[4]); int baseOfSolution = 0; if (args.length == 6) { baseOfSolution = Integer.parseInt(args[5]); } int number1Dec = randomBaseToDecimal(number1, baseOfNumber1); int number2Dec = randomBaseToDecimal(number2, baseOfNumber2); // calculate and print out int solutionDec = 0; if (operator.equals("+")) { solutionDec = number1Dec + number2Dec; } else if (operator.equals("-")) { solutionDec = number1Dec - number2Dec; } else if (operator.equals("x")) { solutionDec = number1Dec * number2Dec; } else if (operator.equals("/")) { solutionDec = number1Dec / number2Dec; } if (args.length == 6) { System.out.println(decimalToRandomBase(solutionDec, baseOfSolution)); } else { System.out.println(solutionDec); } } private static int randomBaseToDecimal(String number, int base) { int result = 0; for (int i = 0; i &lt; number.length(); i++) { int digit = Character.getNumericValue(number.charAt(i)); result = base * result + digit; } return result; } // works only till base 16 private static String decimalToRandomBase(int number, int base) { StringBuilder finalNumber = new StringBuilder(); while (number != 0) { if ((number % base) &gt; 9) { switch ((number % base)) { case 10: finalNumber.append("A"); break; case 11: finalNumber.append("B"); break; case 12: finalNumber.append("C"); break; case 13: finalNumber.append("D"); break; case 14: finalNumber.append("E"); break; case 15: finalNumber.append("F"); break; } } else { finalNumber.append(number % base); } number = number / base; } return new StringBuilder(finalNumber).reverse().toString(); } private static void displayHelp() { System.out.println("This program calculates with numbers of different bases"); System.out.println("Example: "); System.out.println("java Calculator + 34 5 554 6"); System.out.println("You can also specify the base of the output number as the last argument:"); System.out.println("java Calculator + 34 5 554 6 2"); } } </code></pre>
[]
[ { "body": "<p>If your goal is to implement the conversion functions yourself:</p>\n\n<ol>\n<li><p>You are repeating <code>number % base</code> 3 times. Once in the <code>if</code> statement, once in the <code>switch</code> statement, and once in <code>finalNumber.append()</code>. You should do the calculation once, and store it as a local variable.</p></li>\n<li><p>As noted in the comment, <code>decimalToRandomBase()</code> only works up to base 16. You could expand this to base 36 by:</p>\n\n<ul>\n<li>calculating the character to append, <code>'A' + (number % base - 10)</code>, instead of using a <code>switch</code> statement, or</li>\n<li>Using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#forDigit(int,%20int)\" rel=\"nofollow noreferrer\"><code>Character.forDigit(value, radix)</code></a> which is the opposite of the <code>Character.getNumericValue()</code> function. For values 10 and greater, it will return lower case letters, however.</li>\n</ul></li>\n<li><p>You already have a <code>StringBuilder</code>; you don't need to create a <code>new StringBuilder(finalNumber)</code> in order to <code>.reverse().toString()</code>. Simply <code>finalNumber.reverse().toString()</code> will work.</p></li>\n</ol>\n\n<p>If your goal isn't to implement the conversion functions yourself, you can replace <code>randomBaseToDecimal</code> and <code>decimalToRandomBase</code> with:</p>\n\n<ul>\n<li><a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#parseInt(java.lang.String,int)\" rel=\"nofollow noreferrer\"><code>Integer.parseInt(str, radix)</code></a> - string to int with arbitrary base, and</li>\n<li><a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#toString(int,int)\" rel=\"nofollow noreferrer\"><code>Integer.toString(i, radix)</code></a> - int to string with arbitrary base</li>\n</ul>\n\n<hr>\n\n<p>You check twice for a 6th argument: the base to display the answer in. Once to convert it to an integer (if present), and a second time when printing the answers. If you initialize the <code>baseOfSolution</code> to <code>10</code>:</p>\n\n<pre><code> int baseOfSolution = 10;\n if (args.length == 6) {\n baseOfSolution = Integer.parseInt(args[5]);\n }\n</code></pre>\n\n<p>then you don't have to check for the existence of the 6th argument to decide between printing out the value in <code>baseOfSolution</code>, or base 10. You can simply print the solution in <code>baseOfSolution</code>.</p>\n\n<hr>\n\n<p>This chain of if/elseif statements can be replaced by a <code>switch</code> statement. </p>\n\n<pre><code> int solutionDec = 0;\n if (operator.equals(\"+\")) {\n solutionDec = number1Dec + number2Dec;\n } else if (operator.equals(\"-\")) {\n solutionDec = number1Dec - number2Dec;\n } else if (operator.equals(\"x\")) {\n solutionDec = number1Dec * number2Dec;\n } else if (operator.equals(\"/\")) {\n solutionDec = number1Dec / number2Dec;\n }\n</code></pre>\n\n<p>If the operator isn't one of the listed operations, the program simply outputs zero? That is unexpected behaviour! This would be better:</p>\n\n<pre><code> int solutionDec = 0;\n switch (operator) {\n case \"+\": \n solutionDec = number1Dec + number2Dec;\n break;\n case \"-\":\n solutionDec = number1Dec - number2Dec;\n break;\n case \"x\":\n solutionDec = number1Dec * number2Dec;\n break;\n case \"/\":\n solutionDec = number1Dec / number2Dec;\n break;\n default:\n throw new IllegalArgumentException(\"Unrecognized operator: \"+operator);\n }\n</code></pre>\n\n<hr>\n\n<p>The test <code>if (args[0].contains(\"help\"))</code> is odd. Is it really the intention to match words like <code>\"unhelpful\"</code> in addition to <code>\"help\"</code>? Or was this supposed to be <code>if (args[0].equals(\"help\"))</code>? Or perhaps <code>if (args[0].equalsIgnoreCase(\"help\"))</code>?</p>\n\n<hr>\n\n<p>Your help is less than helpful. It doesn't describe which of the arguments are the values and which are the bases. It would also be useful to advise the user as to which operations are supported; many might try \"*\" instead of \"x\" for multiplication.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:47:13.433", "Id": "210318", "ParentId": "210316", "Score": "3" } }, { "body": "<p>Main feedback has already been given by @AJNeufeld and this post is not about the performance of your program but rather other aspects.</p>\n\n<p>You should try putting a check before you access an index in an array and slightly change your if block from this,</p>\n\n<pre><code>if (args[0].contains(\"help\")) {\n</code></pre>\n\n<p>to,</p>\n\n<pre><code>if (args.length == 0 || args[0].contains(\"help\") || args.length &lt; 5) {\n</code></pre>\n\n<p>as the former will run into <code>ArrayIndexOutOfBoundsException</code> if no argument is passed. Also it would be helpful to call the <code>displayHelp()</code> method in case no argument (<code>args.length == 0</code>) was passed so the user knows the usage of program.</p>\n\n<p>Also, for safely accessing array indexes, you should put another <code>OR</code> condition <code>args.length &lt; 5</code> which will ensure at least five parameters are passed, else again you may run into <code>ArrayIndexOutOfBoundsException</code>.</p>\n\n<p>These checks should make the program a little more safer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:04:31.993", "Id": "406544", "Score": "1", "body": "This can in 95% of cases be simplified to `if(args.length < 5) {...}` since this will catch `length == 0` and `java Calculator help`. This will miss if the user for some reason calls `java Calculator help arg2 arg3 arg4 arg5`. To cover that last 5% just change it to `if(args.length < 5 || args[0].contains(\"help\")) {...}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:17:45.707", "Id": "406547", "Score": "0", "body": "@Charanor: Agreed. In fact, even better will be, it should be just `if(args.length < 5)` and the program should catch `NumberFormatException` while parsing the data `Integer.parseInt(args[2])` and just call the usage method in catch block." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T18:20:49.483", "Id": "210320", "ParentId": "210316", "Score": "4" } }, { "body": "<h3>Abstraction</h3>\n\n<p>One thing that makes code more elegant is abstraction. Consider adding something like </p>\n\n<pre><code>class ArbitraryBaseNumber {\n\n private final int number;\n private final int base;\n\n public ArbitraryBaseNumber(int number, int base) {\n this.number = number;\n this.base = base;\n }\n\n public static ArbitraryBaseNumber valueOf(String number, String base) {\n int radix = Integer.parseInt(base);\n int n = Integer.parseInt(number, radix);\n return new ArbitraryBaseNumber(n, radix);\n }\n\n public String toString(int radix) {\n return Integer.toString(number, radix);\n }\n\n @Override\n public String toString() {\n return toString(base);\n }\n\n public int toInteger() {\n return number;\n }\n\n public getBase() {\n return base;\n }\n\n}\n</code></pre>\n\n<p>I think that arbitrary is more descriptive than random. Usually when something is random in computer science, it is created by a random number generator. But you're not doing that here. Random may be correct English, but it makes for confusing code here. Arbitrary does not cause that same confusion. </p>\n\n<p>Now, code like </p>\n\n<blockquote>\n<pre><code> String number1 = args[1];\n int baseOfNumber1 = Integer.parseInt(args[2]);\n String number2 = args[3];\n int baseOfNumber2 = Integer.parseInt(args[4]);\n</code></pre>\n</blockquote>\n\n<p>Can be written </p>\n\n<pre><code> ArbitraryBaseNumber operand1 = ArbitraryBaseNumber.valueOf(args[1], args[2]);\n ArbitraryBaseNumber operand2 = ArbitraryBaseNumber.valueOf(args[3], args[4]);\n</code></pre>\n\n<p>And code like </p>\n\n<blockquote>\n<pre><code> int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);\n int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);\n</code></pre>\n</blockquote>\n\n<p>could just be </p>\n\n<pre><code> int number1Dec = operand1.toInteger();\n int number2Dec = operand2.toInteger();\n</code></pre>\n\n<p>Although I would actually approach this differently. </p>\n\n<p>I think that it's a bit odd to call Java integers <code>Dec</code>. They are actually stored in binary. They are often converted to strings as decimal numbers, but they aren't stored that way. </p>\n\n<h3>Delegation</h3>\n\n<p>When you have something like </p>\n\n<blockquote>\n<pre><code> // calculate and print out\n int solutionDec = 0;\n if (operator.equals(\"+\")) {\n solutionDec = number1Dec + number2Dec;\n } else if (operator.equals(\"-\")) {\n solutionDec = number1Dec - number2Dec;\n } else if (operator.equals(\"x\")) {\n solutionDec = number1Dec * number2Dec;\n } else if (operator.equals(\"/\")) {\n solutionDec = number1Dec / number2Dec;\n }\n</code></pre>\n</blockquote>\n\n<p>Consider writing a method. </p>\n\n<pre><code> public int calculate(char operator, int a, int b) {\n switch (operator) {\n case '+':\n return a + b;\n case '-':\n return a - b;\n case '*':\n case 'x':\n return a * b;\n case '/':\n return a / b;\n default:\n throw new IllegalArgumentException(\"Unrecognized operator: [\" + operator + \"]\");\n }\n }\n</code></pre>\n\n<p>As <a href=\"https://codereview.stackexchange.com/a/210318/71574\">previously suggested</a>, we can use a <code>switch</code> with a default behavior of throwing an exception. This can save a lot of <code>operator.equals</code> calls. </p>\n\n<p>I added <code>'*'</code> accidentally but then kept it as more intuitive. This way, it will accept either <code>*</code> or <code>x</code>. </p>\n\n<p>By using <code>return</code>, we can exit from both the <code>switch</code> and the method. This saves us also having to write <code>break;</code> each time. </p>\n\n<p>Adding <code>[]</code> to the exception message makes it easier to tell where the operator begins and ends. Sometimes that gets lost. For example, if someone enters a period where the operator should be. </p>\n\n<p>I changed from a <code>String</code> operator to a character operator. You would use it like </p>\n\n<pre><code> public int calculate(String operator, ArbitraryBaseNumber operand1, ArbitraryBaseNumber operand2) {\n return calculate(operator.charAt(0), operand1.toInteger, operand2.toInteger);\n }\n</code></pre>\n\n<p>which you would call like </p>\n\n<pre><code> int solution = calculate(operator, operand1, operand2);\n</code></pre>\n\n<p>In the background, I would expect this to make the evaluation more efficient, since all your operators are single characters. </p>\n\n<h3>Putting it together</h3>\n\n<pre><code> ArbitraryBaseNumber operand1 = ArbitraryBaseNumber.valueOf(args[1], args[2]);\n ArbitraryBaseNumber operand2 = ArbitraryBaseNumber.valueOf(args[3], args[4]);\n\n int solution = calculate(args[0], operand1, operand2);\n\n String result;\n if (args.length == 6) {\n result = Integer.toString(solution, Integer.parseInt(args[5]));\n } else {\n result = Integer.toString(solution);\n }\n\n System.out.println(result);\n</code></pre>\n\n<p>That's the entire body of the <code>main</code> method except for the part that displays your help message. </p>\n\n<p>I moved the parsing of the operator and the base of the solution later in the method. The operator isn't a big deal either way. The problem with the base of the solution is that you created parallel logic. You checked <code>args.length == 6</code> in two places. This merges that into one check, which is generally more reliable. If you do have to separate the logic, consider something like </p>\n\n<pre><code> Integer solutionBase = null;\n if (args.length == 6) {\n solutionBase = Integer.parseInt(args[5]);\n }\n</code></pre>\n\n<p>and then later </p>\n\n<pre><code> String result = (solutionBase == null) ? Integer.toString(solution)\n : Integer.toString(solution, solutionBase);\n</code></pre>\n\n<p>That tends to be more robust in regards to future changes (e.g. adding another argument or allowing an arbitrary number of operators and operands). </p>\n\n<p>Or in this case, you might do </p>\n\n<pre><code> int solutionBase = 10;\n if (args.length == 6) {\n solutionBase = Integer.parseInt(args[5]);\n }\n</code></pre>\n\n<p>And then at the end </p>\n\n<pre><code> System.out.println(Integer.toString(solution, solutionBase));\n</code></pre>\n\n<p>Now we have the same logic at the end regardless of the number of arguments. </p>\n\n<h3>Reinventing the wheel</h3>\n\n<p>It is of course possible that you wanted to write your own versions of <code>parseInt</code> and <code>toString</code>. You can certainly do that (using the <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged &#39;reinventing-the-wheel&#39;\" rel=\"tag\">reinventing-the-wheel</a> tag would tell us that's what you're doing). But I would still suggest making them match the original versions' method signatures unless you have a strong reason to change them. Then you could just replace the standard versions with your versions in this code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T06:42:23.273", "Id": "406521", "Score": "0", "body": "If you are creating an `ArbitraryBaseNumber` class, you may want to extend [`Number`](https://docs.oracle.com/javase/10/docs/api/java/lang/Number.html) ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T03:37:25.797", "Id": "210337", "ParentId": "210316", "Score": "4" } } ]
{ "AcceptedAnswerId": "210337", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:22:38.020", "Id": "210316", "Score": "3", "Tags": [ "java", "calculator", "number-systems" ], "Title": "Calculate with numbers from different number systems" }
210316
<blockquote> <p>Problem: Given a string str and array of pairs that indicates which indices in the string can be swapped, return the lexicographically largest string that results from doing the allowed swaps. You can swap indices any number of times.</p> <p>Example</p> <p>For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be swapLexOrder(str, pairs) = "dbca".</p> <p>By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca".</p> </blockquote> <p>My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.</p> <pre><code>#include&lt;iostream&gt; #include&lt;set&gt; #include&lt;string&gt; #include&lt;vector&gt; #include&lt;map&gt; #include&lt;algorithm&gt; std::string swapLexOrder(std::string str, std::vector&lt;std::vector&lt;int&gt;&gt; pairs) { if(pairs.size() == 0) return str; std::vector&lt;std::set&lt;int&gt;&gt; pairpool; //pairpool : contains sets of interchangeable indices std::vector&lt;std::vector&lt;std::string&gt;&gt; stringpool; //stringpool : contains vectors of interchangeable characters //creates pairpool structure for(std::size_t i = 0; i &lt; pairs.size(); i++) { bool alrExists = false; std::set&lt;int&gt; newSet; for(auto&amp; p : pairpool) { for(auto ele : p) { if((pairs[i][0] == ele) || (pairs[i][1] == ele)) { if(!alrExists) { alrExists = true; p.insert(pairs[i][0]); p.insert(pairs[i][1]); newSet = p; } else { if(p == newSet) break; p.insert(newSet.begin(), newSet.end()); pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end()); break; // needed this break statement really badly } } } } if(!alrExists) { newSet.insert(pairs[i][0]); newSet.insert(pairs[i][1]); pairpool.push_back(newSet); } } //creates sorted stringpool structure for(auto p : pairpool) { std::vector&lt;std::string&gt; newset; for(auto ele : p) { newset.push_back(str.substr(ele - 1, 1)); } std::sort(newset.begin(), newset.end()); stringpool.push_back(newset); } //uses stringpool and pairpool to modify string only one time through int counter = 0; for(auto p : pairpool) { for(auto ele : p) { str.replace(ele - 1, 1, stringpool[counter].back()); stringpool[counter].pop_back(); } counter++; } return str; } int main() { std::cout &lt;&lt; swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) &lt;&lt; "\n"; std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv"; std::vector&lt;std::vector&lt;int&gt;&gt; PAIR = { {13, 23}, {13, 28}, {15, 20}, {24, 29}, {6, 7}, {3, 4}, {21, 30}, {2, 13}, {12, 15}, {19, 23}, {10, 19}, {13, 14}, {6, 16}, {17, 25}, {6, 21}, {17, 26}, {5, 6}, {12, 24} }; std::cout &lt;&lt; swapLexOrder(STR, PAIR) &lt;&lt; "\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T00:20:41.820", "Id": "406512", "Score": "0", "body": "I guess one minor thing I see in my code is I have a #include<map> when I didn't use a hashmap." } ]
[ { "body": "<p>Your code is quite good for a beginning, but there's still much room for improvement. Your code main flaw is that it is difficult to read. There are also some performance issues, but they are a lot easier to correct.</p>\n<p>N.B: I'll stay close to your algorithm, although you could probably find a better one in a graph library (see for instance <a href=\"https://en.wikipedia.org/wiki/Connected_component_(graph_theory)#algorithms\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Connected_component_(graph_theory)#algorithms</a>)</p>\n<h1>Performance</h1>\n<p>You must pick your types more carefully. Don't choose a type that allocates memory when you can use one that doesn't. For instance, don't represent a pair of indices by a <code>std::vector</code>: a pair will always have two elements, there is no need to ever grow it. So choose a <code>std::pair&lt;int, int&gt;</code> instead: it is lighter, quicker, and reflects your intent more clearly. In the same way, don't use <code>std::string</code> to represent 1 character: your <code>stringpool</code> can as well be of type <code>std::vector&lt;std::string&gt;</code>.</p>\n<p>You must also be more careful while passing objects around. Don't pass large objects by value unless you need both to copy and modify them. For instance, the signature: <code>std::string swapLexOrder(std::string str, std::vector&lt;std::vector&lt;int&gt;&gt; pairs)</code> is only partially correct. You will indeed modify <code>str</code>, and you want the user to keep his original string untouched, so passing by value is a good call. But <code>pairs</code> is read-only in your code, so pass it by const reference.</p>\n<h1>Expressiveness</h1>\n<p>Your code is one big function containing a lot of nested loops. As a result,it's very hard to understand, let alone optimize. There is two ways to fix it: the first is to better comment on your algorithm (for instance, a minimum would be: <em>first, we merge all pairs of indices that are connected together; then we extract the corresponding characters from the input string, sort them in decreasing order and put them back</em>); the second, is to make your code express your intent clearly.</p>\n<p>The most important rule, which also is one of the hardest to obey, is to choose meaningful names. <code>newset</code> doesn't mean much, neither does <code>p</code>. <code>pairpool</code> should not contain set of more than two elements.</p>\n<p>Another way to write more expressive code is to avoid &quot;raw loops&quot;. Use named algorithms instead. For instance, I rewrote the first part of your algorithm as a combination of a <strong>partition</strong> discriminating sets containing one element of the considered pair and an <strong>accumulation</strong> which merges them:</p>\n<pre><code>std::string swapLexOrder(std::string str, const std::vector&lt;std::pair&lt;int, int&gt;&gt;&amp; pairs)\n{\n if(pairs.size() == 0) return str;\n std::vector&lt;std::set&lt;int&gt;&gt; index_permutations; //pairpool : contains sets of interchangeable indices\n \n for(auto pair : pairs)\n { \n // [matches, end) &lt;- sets containing either one of the pair's elements \n auto matches = std::partition(index_permutations.begin(), index_permutations.end(), \n [&amp;pair](const auto&amp; permutation_set) {\n return std::none_of(permutation_set.begin(), permutation_set.end(), [&amp;pair](auto index) {\n return index == pair.first || index == pair.second;\n });\n });\n \n if (matches == index_permutations.end()) index_permutations.push_back({pair.first, pair.second});\n else { // merge matches\n *matches = std::accumulate(matches, index_permutations.end(),\n std::set&lt;int&gt;{pair.first, pair.second},\n [](auto&amp;&amp; init, auto&amp;&amp; permutation) {\n init.insert(permutation.begin(), permutation.end());\n return init;\n });\n index_permutations.erase(std::next(matches), index_permutations.end());\n }\n }\n// ...\n</code></pre>\n<p>Here's a link to the partially rewritten code if you want to experiment with it: <a href=\"https://wandbox.org/permlink/6Wij6Y4NuooMlW6C\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/6Wij6Y4NuooMlW6C</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T12:09:34.540", "Id": "210355", "ParentId": "210321", "Score": "4" } }, { "body": "<p>You are allocating and deallocating memory all over the place. That is not only an expensive operation by itself, it also destroys locality of reference, and wastes much memory for bookkeeping:</p>\n\n<ul>\n<li>A <code>std::vector&lt;T&gt;</code> is quite an extravagance where a simple <code>std::pair&lt;T, T&gt;</code> suffices.</li>\n<li>A <code>std::set</code> is a sorted, node-based container. Convenient, but better use a <code>std::vector</code> and sort it once.</li>\n<li>The only good thing about the <code>std::string</code> in the <code>stringpool</code> is that a single character will not allocate an extra-buffer due to SSO.</li>\n<li>The least you can do with <code>newSet</code> is <code>std::move()</code> it.</li>\n<li>Same for <code>newset</code>. Did you see the different casing there?</li>\n<li>How you copy complex elements in the for-range-loops is just cruel.</li>\n<li>You could <code>std::move()</code> the return-value. Not that it makes that much difference after the rest.</li>\n</ul>\n\n<p>Iterating over candidate-sets is a very slow way to find clusters of interchangable elements. Just use a proper union-find-datastructure.</p>\n\n<p>Thus, while your code may work, it is <em>really</em> slow, especially as the problem-size grows O(n²) will become problematic. </p>\n\n<p>An alternative, doing only three allocations, and using a proper union-find-datastructure, reducing time-complexity to O(n*log(n)):</p>\n\n<pre><code>auto findUnion(\n std::size_t n,\n std::span&lt;std::pair&lt;std::size_t, std::size_t&gt;&gt; pairs\n) {\n std::vector&lt;std::size_t&gt; r(n);\n std::iota(begin(r), end(r), n-n);\n const auto find = [&amp;](auto a){\n if (a == r[a])\n return a;\n return r[a] = find(r[a]);\n };\n for (auto [a, b] : pairs) {\n if (a &lt; 0 || b &lt; 0 || a &gt;= n || b &gt;= n)\n throw std::out_of_range();\n a = find(a);\n b = find(b);\n r[a] = r[b] = std::min(a, b);\n }\n for (auto&amp; x : r)\n x = r[x];\n return r;\n}\n\nauto findLargest(\n std::string s,\n std::span&lt;std::pair&lt;std::size_t, std::size_t&gt;&gt; pairs\n) {\n const auto n = size(s);\n const auto unions = findUnion(n, pairs);\n std::vector&lt;std::size_t&gt; indices(n);\n std::iota(begin(indices), end(indices), n-n);\n std::sort(begin(indices), end(indices), [&amp;](auto a, auto b){\n return std::tie(unions[a], a) &lt; std::tie(unions[b], b);\n });\n std::vector&lt;char&gt; buffer(n);\n for (auto i = n-n; i &lt; n;) {\n auto j = i;\n for (; j &lt; n &amp;&amp; unions[indices[j]] == unions[indices[i]]; ++j)\n elements[j - i] = s[indices[j]];\n j -= i;\n if (j &gt; 1) { // need not be optional\n std::sort(data(buffer), data(buffer) + j);\n while (j)\n s[indices[i++]] = buffer[--j];\n }\n }\n return std::move(s);\n}\n</code></pre>\n\n<ul>\n<li><a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a> was expected for C++17, but got pushed back to C++20. See <a href=\"https://stackoverflow.com/questions/45723819/what-is-a-span-and-when-should-i-use-one\">\"<em>What is a “span” and when should I use one?</em>\"</a> for details, and where to get an implementation. Most only need C++11.</li>\n<li>One could probably improve efficiency marginally by coalescing the allocations and not depending on the compiler to cut out useless initializations, possibly using C++20 <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique\" rel=\"nofollow noreferrer\"><code>std::make_unique_default_init</code></a> to avoid manual allocation.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:26:37.413", "Id": "210398", "ParentId": "210321", "Score": "2" } } ]
{ "AcceptedAnswerId": "210355", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T18:24:17.020", "Id": "210321", "Score": "6", "Tags": [ "c++", "algorithm", "sorting" ], "Title": "Lexicographically largest string from allowed swaps" }
210321
<p>I have written a probability table generator in Java to help me generate randomized girl's names for the game I am making.</p> <p>It reads from a text file and creates a <code>HashMap&lt;String, Double&gt;</code> full of two-character combinations and their rate of incidence.</p> <p>I don't have a lot of experience with either probability tables or Java in general.</p> <p>I would like help making it run faster</p> <p><strong>Example text from input file:</strong></p> <p>Each line has ten names. The real text file has 462 lines, and 4620 names.</p> <blockquote> <p>Marva Kandy Debbi Louisa Edris Orpha Lynn Louise Reyna Jacki Evangeline</p> <p>Ray Sienna Alecia Elin Debby Noreen Alishia Michael Evangelina Eliz</p> <p>Usha Ladawn Dominga Cynthia Marty Shayla Sanora Betsey Ira Jodee</p> <p>Qiana Elia Elke Torie Amirah Marta Lavonna Ozie Lavonne Teofila</p> <p>Latoria Catharine Epifania Susy Keli Delpha Isa Marth Rosina Marti</p> <p>Jordan Ella Theda Tyesha Rana Francesca Shayna Letha Shayne Marry</p> <p>Rea Joellen Fidela Kandi Celeste Salina Kamryn Jenelle Celena Celesta</p> <p>Kenyatta Ada Shelia Maribel Edith Lorilee Jazmyn Myrtice Kena Laurence</p> </blockquote> <p><strong>My code</strong></p> <pre><code>public class MCVE { public static void main(String[] args) throws Exception { // create the file-path String address = &quot;./res/text_files/Human_FirstNames&quot;; // will hold letter combinations and their frequency HashMap&lt;String, Double&gt; frequencies = new HashMap&lt;&gt;(); FileReader fr = new FileReader(address); BufferedReader br = new BufferedReader(fr); // Iterate through file // get rid of new-line characters and concat to wholeString String aLine = &quot;&quot;; String wholeString = &quot;&quot;; while((aLine = br.readLine()) != null) { wholeString += aLine.replaceAll(System.lineSeparator(), &quot; &quot;); } // convert names to lowercase and into char[] char[] charArr = wholeString.toLowerCase().toCharArray(); // iterate through char[] charArr and // add the number of times each character-combination is shown // to the value for each character-combination key. int length = charArr.length; String tempString = &quot;&quot;; for(int i = 0; i &lt; length; i++) { if(i + 1 == length) break; if(charArr[i] != ' ' &amp;&amp; charArr[i + 1] != ' ') { tempString = Character.toString(charArr[i]) + Character.toString(charArr[i + 1]); if (frequencies.containsKey(tempString)) frequencies.replace(tempString, frequencies.get(tempString) + 1.0); else // if it doesn't contain this key yet, create it frequencies.put(tempString, 1.0); } } // iterate through HashMap frequencies and // replace the values with the product of // (original_value / size_of_HashMap) double mapLength = frequencies.size(); Iterator iter = frequencies.entrySet().iterator(); while(iter.hasNext()) { HashMap.Entry pair = (HashMap.Entry)iter.next(); frequencies.replace((String) pair.getKey(), (Double) pair.getValue() / mapLength); System.out.println(pair.getKey() + &quot; &quot; + pair.getValue()); iter.remove(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:50:46.043", "Id": "406507", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Your latest edits can be tolerated, but please don't make any further changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:53:08.837", "Id": "406508", "Score": "0", "body": "@Mast Thanks for the heads-up. I was already editing the file when the answer was posted. It has not been edited to accommodate it." } ]
[ { "body": "<p>I have looked through your code. Here are a few things I notice</p>\n\n<ol>\n<li>StringBuilder instead of using <code>+=</code> on <code>String</code>, for more efficient string concatenation.</li>\n</ol>\n\n<p>Creating a new instance of StringBuilder and using that would work better than using the + operator on Strings. Something like this:</p>\n\n<p><code>StringBuilder builder = new StringBuilder();\n// inside the loop call the following\nbuilder.append(\"some string to append\");\n// ...\n// later on when you need the string\nbuilder.toString();</code></p>\n\n<ol start=\"2\">\n<li>More descriptive variable names</li>\n</ol>\n\n<p>Try to explain what your variable represents instead of just calling it <code>wholeString</code>. To you, you may very well remember the significance of each variable and what it represents, but this is a good coding practice to get into because code will be read more than written and it would be easier for anyone else reading your code to immediately tell what it's doing without having to in many cases even read comments. This is called \"self-documenting code\".</p>\n\n<ol start=\"3\">\n<li>JDK 8+ Files API</li>\n</ol>\n\n<p>After JDK 8 you can call lines() using the Files API. Although your approach is correct using BufferedReader and FileReader, you may want to consider switching to using the lines() method and operating on the Stream returned because it is a bit less verbose which makes reading it easier.</p>\n\n<ol start=\"4\">\n<li>Succinct method chaining using Stream over iterative approach</li>\n</ol>\n\n<p>If you switch to using Stream for the file, you can easily adopt a more functional approach of calling filter or other stream related functions on it. This is a bit cleaner to read than the iternative while loop to remove the newlines in my view.</p>\n\n<ol start=\"5\">\n<li>Multiline comments using multiline comment syntax</li>\n</ol>\n\n<p>For in-depth explanations and long comments that span to multiple lines, you can use the following notation:</p>\n\n<p>/*</p>\n\n<p>This comment </p>\n\n<p>spans</p>\n\n<p>multiple lines</p>\n\n<p>*/</p>\n\n<p>However, with that being said - I think the comments in this code are a bit much. Using self documenting variables as mentioned above, comments can be lessened and the code would be more readable too.</p>\n\n<p>Hope that helps, let me know if you have any questions on the feedback I've given.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:15:45.870", "Id": "210327", "ParentId": "210325", "Score": "1" } } ]
{ "AcceptedAnswerId": "210327", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T20:18:55.733", "Id": "210325", "Score": "0", "Tags": [ "java", "statistics", "iteration", "hash-map" ], "Title": "Generating probability table of 2-character combinations from text file in Java" }
210325
<p>I'm creating a django web application and I would like to know how to shorten this code.</p> <p>I have a model where every user has a typeOfPerson (Student, Teacher, Guest ...) and I want to count these types.</p> <pre><code>@register.simple_tag() def get_stats_type(choice): items = [] for vote in choice.vote_set.all(): if vote.user not in items: items.append(vote.user) types = {} for user in items: if user.userprofile.typeOfPerson not in types: types[user.userprofile.typeOfPerson] = Vote.objects.filter(Choice=choice).count() percent = 0 for type, value in types.items(): percent += value if percent == 0: percent = 1 values = {} for type, value in types.items(): if type not in values: values[type] = value / percent * 100 return values </code></pre>
[]
[ { "body": "<blockquote>\n <p>I'm creating a django</p>\n</blockquote>\n\n<p>You probably mean that you're creating a web application on top of Django.</p>\n\n<p>Given this code:</p>\n\n<pre><code>items = []\nfor vote in choice.vote_set.all():\n if vote.user not in items:\n items.append(vote.user)\n</code></pre>\n\n<p>you should instead be able to do</p>\n\n<pre><code>items = set(v.user for v in choice.vote_set.all())\n</code></pre>\n\n<p>This achieves the same goal - creating a collection of unique entries. The only catch is that order will not be preserved. If that's important, you'll have to do something more clever.</p>\n\n<p>This:</p>\n\n<pre><code>types = {}\nfor user in items:\n if user.userprofile.typeOfPerson not in types:\n types[user.userprofile.typeOfPerson] = Vote.objects.filter(Choice=choice).count()\n</code></pre>\n\n<p>apparently makes an effort to avoid overwriting entries in a dictionary, but I'm not clear on whether that's necessary. If order doesn't matter, and if <code>items</code> all have equal priorities, then you can make this much more simple:</p>\n\n<pre><code>n_votes = Vote.objects.filter(Choice=choice).count()\ntypes = {u.userprofile.typeOfPerson: n_votes for u in items}\n</code></pre>\n\n<p>This also assumes that <code>Vote.objects.filter(Choice=choice).count()</code> doesn't vary at all over the course of the loop.</p>\n\n<p>This:</p>\n\n<pre><code>percent = 0\nfor type, value in types.items():\n percent += value\nif percent == 0:\n percent = 1\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>percent = max(1, sum(types.values()))\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>values = {}\nfor type, value in types.items():\n if type not in values:\n values[type] = value / percent * 100\n</code></pre>\n\n<p>can probably just be</p>\n\n<pre><code>values = {t: v/percent * 100 for t, v in types.items()}\n</code></pre>\n\n<p>Again, it's not clear why all three of your loops are attempting to be careful in avoiding rewriting values, or what the priority system should be.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:51:04.327", "Id": "210329", "ParentId": "210326", "Score": "3" } }, { "body": "<p>This code itself doesn't look bad, but since this is Code Review there are always ways that it can be improved.</p>\n\n<h2>Let's talk about what the code was supposed to do</h2>\n\n<p>PEP 8, the Python style guide, strongly encourages docstrings to be used to document what the function itself is supposed to do. Since this is a Django template tag, docstrings can be used here as well. I wrote up a small one based on my understanding of what is trying to be accomplished here.</p>\n\n<pre><code>@register.simple_tag()\ndef get_stats_type(choice):\n \"\"\"\n Returns a dictionary containing the percentage of users who voted for a\n choice, organized by the type of user, out of all users who voted.\n \"\"\"\n</code></pre>\n\n<p>It doesn't have to be anything long or complex, but the idea is to document what is trying to be accomplished so future readers of your code can understand it more quickly.</p>\n\n<p><em>Spoiler: your code doesn't currently do what this docstring says.</em></p>\n\n<h2>Document what you're actually trying to accomplish along the way</h2>\n\n<p>Again, documentation is something which someone will inevitably jump on here and should \"But you don't need it if your code is obvious!\" and they might be right. But hey, it's Code Review and here's an example of why you might want it.</p>\n\n<p>The first part of your function is trying to get all of the users who voted for the choice that was passed in. In the Django ORM, depending on what you're looking to get back, you can shortcut this in a few different ways.</p>\n\n<p>If you're just trying to get the IDs of all of the users, you query for all of the votes with that choice and use <code>.values_list('user', flat=True)</code> to get the user ID back.</p>\n\n<pre><code>items = Vote.objects.filter(Choice=choice).values_list('user', flat=True).distinct()\n</code></pre>\n\n<p>And this will return a list of user IDs for all the unique votes who voted for this choice. But, based on the next part of the function, it actually looks like you may be looking for the types of the users who voted for this choice, which is a little more complex but can also be done on the database side.</p>\n\n<pre><code># Get all of the users who voted for this choice\nusers = Vote.objects.filter(Choice=choice).values_list('user', flat=True).distinct()\n\n# Get a list of the types of the users who voted\nuser_types = UserProfile.objects.filter(users__in=users).values_list('typeOfPerson', flat=True).distinct()\n</code></pre>\n\n<p>This will get you a list of the unique user types who voted using this choice.</p>\n\n<h2>You aren't getting the votes for just the specific user type</h2>\n\n<p>This was caught in the other answer, but it was never addressed and was treated as something which could be simplified. Right now, any time this function returned percentages, all of the user types will have an equal percentage because it uses the same set of votes for each user type, never filtering it down.</p>\n\n<pre><code>votes_by_type = {}\n\n# Get the number of votes, by user type, who voted for this choice\nfor user_type in user_types:\n votes_by_type[user_type] = Vote.objects.filter(\n user__userprofile__typeOfPerson=user_type,\n Choice=choice,\n ).count()\n</code></pre>\n\n<p>While this can be done with a dictionary comprehension, as recommended by the other answer, I would suggest doing it as you did it before. It's easier to read and understand what is actually trying to be accomplished.</p>\n\n<p>Here is where the bug that existed in the original version was fixed. I added an additional <code>filter()</code> to the votes to limit it down to just those made by the given user type.</p>\n\n<p>We don't need to check for duplicate user types here because we know that <code>user_types</code> is a list of unique user types already.</p>\n\n<h2>Summing it up and doing percentages</h2>\n\n<p>Python has a built-in <code>sum</code> function which can be used to get the sum of a list of numbers. Dictionaries in Python also have a built-in <code>values</code> function which gets you the list containing all of the values in the dictionary. You can combine these together to get the total votes cast for the choice.</p>\n\n<pre><code># Get the total number of votes cast for this choice\ntotal_votes = sum(votes_by_type.values())\n</code></pre>\n\n<p>You can then use this, as stated in the other answer and done originally, to calculate the percentages.</p>\n\n<pre><code>percentages = {}\n\n# Calculate the percentage of votes by user type\nfor user_type in user_types:\n percentages[user_type] = (votes_by_type[user_type] / total_votes) * 100\n</code></pre>\n\n<p>But wait, I'm not checking for when <code>total_votes</code> is zero! This is because if nobody votes, then <code>user_types</code> will be empty (because nobody voted, so there are no user types who voted), and the division by zero error will not happen.</p>\n\n<p>If you choose to change this later to always return the types regardless of whether or not they have actually voted, then you may need to add back in your logic of handling cases where there are no votes. But I would consider this to be a standard special case, since you're trying to calculate percentages based off of no votes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T18:57:04.303", "Id": "210568", "ParentId": "210326", "Score": "1" } } ]
{ "AcceptedAnswerId": "210329", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T21:12:32.513", "Id": "210326", "Score": "4", "Tags": [ "python", "django" ], "Title": "Counting users by the type in their profile" }
210326
<p>The idea is to write a function that takes two strings and returns a new string that repeats in the previous two: examples:</p> <pre><code>'ABBA' &amp; 'AOHB' =&gt; 'AB' 'cohs' &amp; 'ohba' =&gt; 'oh' </code></pre> <p>A brute force solution would be nested for loops like so:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const x = 'ABCD' const y = 'AHOB' function subStr(str1, str2) { let final = '' for (let i = 0; i &lt; str1.length; i++) { for (let j = 0; j &lt; str2.length; j++) { if (str1[i] === str2[j]) { final += str1[i] } } } return final } console.log(subStr(x, y)) // =&gt; AB</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T05:41:46.493", "Id": "406518", "Score": "5", "body": "Could you clarify, with additional examples, what should happen when letters appear in different orders within the two input strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T02:13:24.470", "Id": "428324", "Score": "0", "body": "How is this supposed to behave with repeated characters? For example, your `subStr` function returns `\"ABBA\"` on the input `(\"ABBA\", \"AOHB\")`, which isn't the output you specified (`\"AB\"`)" } ]
[ { "body": "<p>I know the root of all evil is premature optimization, but I would first ask if this is expected to be either a hotspot or usef with large strings.</p>\n\n<p>Because it can be made much more readable using the array methods, but doing so obviously comes with a performance cost. OTOH, your method has its own performance issues.</p>\n\n<p>If this isn’t expected to be particularly performance sensitive, I think that a straightforward method that turned the two strings into arrays then used the filter or map method to generate an array that is then turned into a string would be much more readable, and I prefer readable over performant as long as the performance isn’t a problem.</p>\n\n<p>One additional point, what should your function return for “a”, “aa”? currently it returns “aa”?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:30:45.353", "Id": "406838", "Score": "0", "body": "That would make a nice one-liner: `common = (str1, str2) => str1.split('').filter(s => str2.contains(s)).join('')`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:16:58.583", "Id": "210357", "ParentId": "210341", "Score": "1" } }, { "body": "<p>One option to simplify the procedure is use <code>Set</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const subStr = (a, b) =&gt; {\n const set = s =&gt; new Set(s);\n const [x, y, s = set([...x, ...y])] = [set(a), set(b)];\n \n for (let z of s) \n if (!x.has(z) || !y.has(z)) s.delete(z)\n \n return [...s].join('')\n}\n \n \nconsole.log(subStr('ABBA', 'AOHB'), subStr('cohs', 'ohba'), subStr('aa', 'a'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:41:48.903", "Id": "210780", "ParentId": "210341", "Score": "1" } }, { "body": "<p>If both string are equal length and sort is allowed, performance can be reduced to linear o(n).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const x = 'ABCD'\nconst y = 'AHOB'\n\nfunction subStr(str1, str2) {\n str1 = str1.split('');\n str2 = str2.split('');\n\n str1.sort();\n str2.sort();\n\n let final = ''\n\n for (let i = 0; i &lt; str1.length; i++) {\n if (str1[i] === str2[i]) {\n final += str1[i]\n }\n }\n\n return final\n}\n\n\n\nconsole.log(subStr(x, y)) // =&gt; AB</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T09:10:39.630", "Id": "428347", "Score": "0", "body": "What exactly do you mean with \\$n\\$, and how can sorting be \\$\\mathcal O(n)\\$?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T02:12:41.007", "Id": "221516", "ParentId": "210341", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T04:58:23.433", "Id": "210341", "Score": "0", "Tags": [ "javascript", "algorithm", "strings" ], "Title": "Form a string consisting of the common letters that appear in two input strings" }
210341
<p>I would like some feedback on a CMakeLists.txt file I created for compiling my project. I have pasted the CMakeLists as well as my source code below. One thing I would specifically appreciate feedback on the sanitization options I have enabled. Are there more I should enable, and/or should I should reduce? I know <code>-fsanitize=address, -fsanitize=thread, and -fsanitize=memory</code> groups can't be used with others (according to the clang documentation). Would one of the other groups be better preferred to use on a first-pass rather than the one I chose (<code>address</code>)?</p> <p>Also - the blob feature I am using, I have based on a StackOverflow answer I read - I understand that this doesn't detect new C source files and I'm fine with that, but besides that subtle detail is this an okay practice to follow?</p> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 3.13) project(FirstProject C) find_package(Curses REQUIRED) include_directories(${CURSES_INCLUDE_DIR}) set(CMAKE_C_COMPILER clang) set(CMAKE_C_STANDARD 99) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default") FILE(GLOB Sources *.c) add_executable(${CMAKE_PROJECT_NAME} ${Sources}) target_link_libraries(${CMAKE_PROJECT_NAME} ${CURSES_LIBRARIES}) </code></pre> <p><strong>main.c</strong> (Code comes from <a href="/a/210304/9357">here</a>)</p> <blockquote> <pre><code>#include &lt;ctype.h&gt; #include &lt;errno.h&gt; #include &lt;inttypes.h&gt; #include &lt;limits.h&gt; #include &lt;ncurses.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; // Generous estimate of the maximum number of digits // https://stackoverflow.com/a/10536254 #define ULL_DIGITS (3 * sizeof(unsigned long long)) #define ERR_MSG_MAX_LENGTH 32 #define NUL '\0' #define NUL_SIZE 1 int ask_ull(unsigned long long *result, const char *prompt); /** * Prints a prompt then reads an unsigned long long, using ncurses. * Returns 0 on success. Returns errno on failure, which is set to * ERANGE, EDOM, or EIO. */ int ask_ull(unsigned long long *result, const char *prompt) { char buf[ULL_DIGITS + NUL_SIZE]; char *endptr; printw("%s", prompt); getnstr(buf, ULL_DIGITS); *result = strtoull(buf, &amp;endptr, 10); if (errno == ERANGE) { // Overflow or underflow return errno; } if (endptr == buf || strchr(buf, '-')) { // Unsuccessful conversion errno = EDOM; return errno; } while (isspace(*endptr)) endptr++; if (*endptr) { // Trailing junk errno = EIO; return errno; } errno = 0; return errno; } int main(void) { unsigned long long height, width, length; height = width = length = 0; char errmsg[ERR_MSG_MAX_LENGTH]; errmsg[0] = NUL; initscr(); printw("--- Volume Calculator --\n"); if (!ask_ull(&amp;length, "Enter length: ")) { sscanf(errmsg, "%s", "Unable to scan length"); } if (!ask_ull(&amp;width, "Enter width: ")) { sscanf(errmsg, "%s", "Unable to scan width"); } if (!ask_ull(&amp;height, "Enter height: ")) { sscanf(errmsg, "%s", "Unable to scan height"); } if (errmsg[0] != NUL) { refresh(); endwin(); perror(errmsg); return errno; } unsigned long long volume = length * width * height; printw("Volume: %llu", volume); refresh(); getch(); endwin(); } </code></pre> </blockquote>
[]
[ { "body": "<p>I am not familiar with the Clang sanitization command-line options so I can't give any feedback about those,\nbut regarding the CMake code I would suggest the following <em>CMakeLists.txt</em> file</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>cmake_minimum_required(VERSION 3.13)\nproject(FirstProject C)\n\nfind_package(Curses REQUIRED)\n\nadd_executable(${CMAKE_PROJECT_NAME} main.c)\n\ntarget_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_INCLUDE_DIR})\ntarget_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_LIBRARIES})\n\nif(NOT CMAKE_C_COMPILER_ID STREQUAL \"Clang\")\n message(WARNING \"Use the Clang compiler instead. \"\n \"FirstProject officially supports Clang \"\n \"(although other compilers might work).\") \nendif() \n\ntarget_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99)\ntarget_compile_options(${CMAKE_PROJECT_NAME} PRIVATE\n $&lt;$&lt;C_COMPILER_ID:Clang&gt;:\n -Weverything\n -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi\n -flto\n -fvisibility=default&gt;)\ntarget_link_options(${CMAKE_PROJECT_NAME} PRIVATE\n $&lt;$&lt;C_COMPILER_ID:Clang&gt;:\n -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi\n -flto&gt;)\n</code></pre>\n\n<h1>Some comments</h1>\n\n<h2>Avoid using FILE(GLOB) to specify source code files</h2>\n\n<p>Avoid using <a href=\"https://cmake.org/cmake/help/latest/command/file.html?highlight=file\" rel=\"nofollow noreferrer\"><code>FILE(GLOB)</code></a>, instead specify the source code files explicitly either by</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>add_executable(${CMAKE_PROJECT_NAME} main.c)\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>add_executable(${CMAKE_PROJECT_NAME})\ntarget_sources(${CMAKE_PROJECT_NAME} PRIVATE main.c)\n</code></pre>\n\n<p>Śee also <a href=\"https://stackoverflow.com/questions/32411963/why-is-cmake-file-glob-evil\">https://stackoverflow.com/questions/32411963/why-is-cmake-file-glob-evil</a></p>\n\n<h2>Use target_* commands</h2>\n\n<p>Avoid</p>\n\n<ul>\n<li>using <a href=\"https://cmake.org/cmake/help/latest/command/include_directories.html?highlight=include_directories#command:include_directories\" rel=\"nofollow noreferrer\"><code>include_directories()</code></a></li>\n<li>setting <a href=\"https://cmake.org/cmake/help/latest/envvar/CFLAGS.html?highlight=cmake_c_flags\" rel=\"nofollow noreferrer\"><code>CMAKE_C_FLAGS</code></a> directly</li>\n</ul>\n\n<p>Instead use</p>\n\n<ul>\n<li><a href=\"https://cmake.org/cmake/help/latest/command/target_compile_features.html?highlight=target_compile_features#command:target_compile_features\" rel=\"nofollow noreferrer\"><code>target_compile_features()</code></a></li>\n<li><a href=\"https://cmake.org/cmake/help/latest/command/target_compile_options.html?highlight=target_compile_options#command:target_compile_options\" rel=\"nofollow noreferrer\"><code>target_compile_options()</code></a></li>\n<li><a href=\"https://cmake.org/cmake/help/latest/command/target_include_directories.html?highlight=target_include_directories#command:target_include_directories\" rel=\"nofollow noreferrer\"><code>target_include_directories()</code></a></li>\n<li><a href=\"https://cmake.org/cmake/help/latest/command/target_link_libraries.html?highlight=target_link_libraries#command:target_link_libraries\" rel=\"nofollow noreferrer\"><code>target_link_libraries()</code></a></li>\n<li><a href=\"https://cmake.org/cmake/help/latest/command/target_link_options.html?highlight=target_link_options#command:target_link_options\" rel=\"nofollow noreferrer\"><code>target_link_options()</code></a></li>\n</ul>\n\n<p>The <a href=\"https://cmake.org/cmake/help/latest/module/FindCurses.html?highlight=ncurses\" rel=\"nofollow noreferrer\">FindCurses</a> module does not yet support imported targets as of today (2 January 2019, CMake 3.13.2) so it needs to \nbe used in the old style </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_INCLUDE_DIR})\ntarget_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_LIBRARIES})\n</code></pre>\n\n<p>In the future (when support has been added to CMake for imported targets in FindCurses) the two lines should be replaced by the line:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Curses::Curses)\n</code></pre>\n\n<p>Instead of setting the CMake variable <a href=\"https://cmake.org/cmake/help/latest/variable/CMAKE_C_STANDARD.html?highlight=cmake_c_standard\" rel=\"nofollow noreferrer\"><code>CMAKE_C_STANDARD</code></a></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>set(CMAKE_C_STANDARD 99)\n</code></pre>\n\n<p>is good practice to use <a href=\"https://cmake.org/cmake/help/latest/command/target_compile_features.html?highlight=target_compile_features#command:target_compile_features\" rel=\"nofollow noreferrer\"><code>target_compile_features()</code></a> instead </p>\n\n<pre class=\"lang-none prettyprint-override\"><code> target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99)\n</code></pre>\n\n<p>In this very case it makes no practical difference but for a\n C++ header-only library, such compile features could be specified in the INTERFACE</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> add_library(myheaderonly INTERFACE)\n target_compile_features(headeronlylib INTERFACE cxx_std_11)\n</code></pre>\n\n<p>to provide usage requirements for consumers of the library (see also <a href=\"https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html\" rel=\"nofollow noreferrer\">https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html</a>)</p>\n\n<p>The <code>target_link_options()</code> line was added to be able to build the executable. (I am not sure it is correct).</p>\n\n<h2>Use generator expressions</h2>\n\n<p>The <a href=\"https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html\" rel=\"nofollow noreferrer\">generator expression</a></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$&lt;$&lt;C_COMPILER_ID:Clang&gt;:-Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default&gt;\n</code></pre>\n\n<p>is expanded to </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>-Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default\n</code></pre>\n\n<p>when the Clang compiler is used, but for other compilers it is expanded to nothing.</p>\n\n<h2>Avoid setting CMAKE_C_COMPILER</h2>\n\n<p>Instead of setting the CMake variable <code>CMAKE_C_COMPILER</code>, give a <code>WARNING</code> or a <code>FATAL_ERROR</code> whenever a non-supported C compiler is used.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>if(NOT CMAKE_C_COMPILER_ID STREQUAL \"Clang\")\n message(WARNING \"Use the Clang compiler instead. FirstProject officially supports Clang (although other compilers might work).\") \nendif() \n</code></pre>\n\n<p>(<code>WARNING</code> could be replaced by <code>FATAL_ERROR</code> to prevent the use of any other C compiler than Clang)</p>\n\n<p>To compile the project, specify the C compiler with the environment variable <a href=\"https://cmake.org/cmake/help/latest/envvar/CC.html?highlight=cmake_c_compiler\" rel=\"nofollow noreferrer\"><code>CC</code></a> </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mkdir /tmp/build\ncd /tmp/build\nCC=clang cmake -G Ninja ~/FirstProject\nninja -v\n</code></pre>\n\n<p>Use the <a href=\"https://ninja-build.org/\" rel=\"nofollow noreferrer\">ninja</a> command-line flag <code>-v</code> if you want to see the actual commands being run.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:37:56.083", "Id": "407431", "Score": "0", "body": "I appreciate the thorough answer. The last segment though, any particular advantage of using ninja over traditional make? Will it make a difference in compile-time speed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:42:52.157", "Id": "407432", "Score": "1", "body": "Probably very little. For me the main advantages of `ninja` is that you don't need to specify the number of threads (e.g. make -j) and that the software is available for Linux, Mac and Windows." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:13:48.200", "Id": "210770", "ParentId": "210342", "Score": "1" } } ]
{ "AcceptedAnswerId": "210770", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T06:23:33.187", "Id": "210342", "Score": "0", "Tags": [ "c", "cmake" ], "Title": "CMakeLists and Clang sanitization options for an ncurses program" }
210342
<p>I'm new to MVVM and WPF. Please suggest whether this is okay or I need to correct my understanding of MVVM which I confess is very limited as at the moment. </p> <p>I have created a simple addition application which gets two number as input and provide the added number after clicking the Button.</p> <p>Please give me your honest (and brutal) opinion, since that will help me improve the most.</p> <p><strong>Model.cs:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace addition.Model { class Number { public int number1 { get; set; } public int number2 { get; set; } public int number3 { get; set; } } } </code></pre> <p><strong>ViewModel.cs</strong></p> <pre><code>using addition.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace addition.ViewModel { class ViewModel : INotifyPropertyChanged { private Number n1 = new Number(); int num, num1; public RelayCommand AddNew { get; set; } private string _number1; public string FirstArgument { get { return this._number1; } set { this._number1 = value; if (int.TryParse(_number1.ToString(), out num)) { this.n1.number1 = num; this.OnPropertyChanged("FirstArgument"); } else { MessageBox.Show("The given Value is not a Number "); } } } private string _number2; public string secondargument { get { return this._number2; } set { this._number2 = value; if (int.TryParse(_number2.ToString(), out num1)) { this.n1.number2 = num1; this.OnPropertyChanged("secondargument"); } else { MessageBox.Show("The given Value is not a Number "); } } } private string _number3; public string Addedargument { get { return this._number3; } set { this._number3 = value; this.OnPropertyChanged("Addedargument"); } } public ViewModel() { AddNew = new RelayCommand(o =&gt; AddNumbers()); } private void AddNumbers() { var a = this.FirstArgument; var b = this.secondargument ; var c = (Convert.ToInt32(a) + Convert.ToInt32(b)).ToString(); MessageBox.Show(c); Addedargument = c; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } } </code></pre> <p><strong>View.xaml</strong></p> <pre><code>&lt;Window x:Class="addition.Window1" xmlns:vm="clr-namespace:addition.ViewModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;Window.DataContext&gt; &lt;vm:ViewModel /&gt; &lt;/Window.DataContext&gt; &lt;Grid&gt; &lt;Label Height="28" Margin="28,54,0,0" Name="Number1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="48"&gt;Number&lt;/Label&gt; &lt;TextBox Height="28" Margin="112,56,46,0" Text ="{Binding Path = FirstArgument}" Name="textBox1" VerticalAlignment="Top" /&gt; &lt;Label Margin="28,106,0,128" Name="Number2" Width="58" HorizontalAlignment="Left"&gt;Number1&lt;/Label&gt; &lt;TextBox Height="28" Margin="112,120,46,120" Text ="{Binding Path = secondargument}" Name="textBox2" /&gt; &lt;Label Height="28" Margin="28,0,0,75" Name="label1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="58"&gt;Number2&lt;/Label&gt; &lt;TextBox Height="23" Margin="112,0,46,68" Name="textBox3" Text="{Binding Path = Addedargument}" VerticalAlignment="Bottom" /&gt; &lt;Button Height="23" HorizontalAlignment="Left" Margin="39,0,0,16" Name="button1" VerticalAlignment="Bottom" Width="75" Command="{Binding AddNew}"&gt;Button&lt;/Button&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T03:30:02.347", "Id": "406645", "Score": "0", "body": "Pick a code formatting layout and *be consistent* with it. The amount of random indenting and bracing makes the code near impossible to follow. Microsoft has guidelines for this if you don't have a standard: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions#layout-conventions" } ]
[ { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Give things proper names. \"Model.cs\" is a bad name for a class, and in your case it is even the name of a namespace. Microsoft has <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Naming Guidelines</a>; please follow them.</p></li>\n<li><p>Same for properties, e.g. <code>public int number1</code>: follow Microsoft's <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Naming Guidelines</a>.</p></li>\n<li><p>Give things meaningful names. You're not improving your code by obscuring your names of fields, variables etc., e.g. <code>n1</code>, <code>num</code>, <code>num1</code>.</p></li>\n<li><p>Why are you doing <code>_number1.ToString()</code>, when <code>_number1</code> is already a <code>string</code>?</p></li>\n<li><p>Be consistent in naming: <code>FirstArgument</code> is correctly named, yet <code>secondargument</code> makes two mistakes against the guidelines. And then <code>Addedargument</code> makes one mistake against the guidelines.</p></li>\n<li><p>Why are those \"arguments\" <code>string</code>s and not <code>int</code>s? You check this in their <code>get</code>s yet store them as <code>string</code>s, causing you to again needing to convert them in <code>AddNumbers()</code>.</p></li>\n<li><p>Use a Grid or a StackPanel for lay-outs instead of placing items via defined margins.</p></li>\n<li><p>Use <code>nameof()</code> instead of a \"magic string\" in <code>this.OnPropertyChanged(\"FirstArgument\");</code>.</p></li>\n<li><p>Don't use a <code>MessageBox</code> in your ViewModel. Look at the approaches discussed in <a href=\"https://stackoverflow.com/questions/1098023/how-have-you-successfully-implemented-messagebox-show-functionality-in-mvvm\">this StackOverflow question</a> for better solutions.</p></li>\n<li><p>Avoid clutter in your XAML. It's been a while since I've done such development, but IIRC you don't need to give everything a <code>Name</code>. Communication between Labels and TextBoxes and the VM should be done via Bindings, and thus names are not needed. </p></li>\n<li><p>Give your button a proper text. \"Button\" is stating the obvious and doesn't explain to the user what it does.</p></li>\n</ul>\n\n<hr>\n\n<p>To end on a compliment: you're using <code>Binding</code>s and <code>Command</code>s, which is excellent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T11:36:23.017", "Id": "210354", "ParentId": "210344", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T07:05:43.207", "Id": "210344", "Score": "1", "Tags": [ "c#", "wpf", "mvvm" ], "Title": "Addition Program using wpf through MVVM" }
210344
<pre><code>function solution(A) { var len = A.length; if(len &gt; 1){ let max = Math.max.apply(null, A); let range = Array.from(Array(max).keys()); for(let i = 0; i &lt; range.length; i++){ if(A.includes(range[i]) === false){ if(range[i] &gt; 0){ return range[i]; } continue; } continue; } return max + 1; }else if(len == 1 &amp;&amp; (A[0] &lt; 1 || A[0] &gt; 1)){ return 1; }else if((len == 1) &amp;&amp; (A[0] == 1)){ return 2; } return 1; } </code></pre> <p>This is mainly used to get the first positive value that does not exist in sequence of integers in an array.</p> <p>There is a time complexity of O(N ** 2).</p> <p>Can it be better than this?</p> <p>If there is no better complexity, can we optimize the for loop better than that?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T07:14:16.683", "Id": "407080", "Score": "0", "body": "This can be done in O(n): See [this link](https://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/)" } ]
[ { "body": "<p>How about just brute forcing it?</p>\n\n<pre><code>function solution(A) {\n for (let n = 1;; n++) {\n if (A.indexOf(n) === -1) {\n return n;\n }\n }\n}\n</code></pre>\n\n<p><strong>UPD:</strong> The bottleneck of the above function is the <code>indexOf</code> method that should search entire array for the passed number. You have to pass large arrays, to significantly increase the speed you may want to convert array to object by swapping values and indices. This would be faster because checking whether an object has a property is much faster than searching for a value in an array.</p>\n\n<pre><code>function solution(A) {\n let obj = {};\n for (let i of A) {\n if (i &gt; 0) {\n obj[i] = 1;\n }\n }\n\n for (let n = 1; ; n++) {\n if (!(n in obj)) {\n return n;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T11:23:40.480", "Id": "210351", "ParentId": "210348", "Score": "0" } }, { "body": "<blockquote>\n <p>If there is no better complexity than N**2, can we optimize the for loop better than that?</p>\n</blockquote>\n\n<p>Complexity is more subtle: your code is O(N²) in the worst case (<code>A</code> is an arithmetic progression with an initial term of 1 and a common difference of 1: <code>[1,2, ... , N]</code>) but O(N) in the best case (<code>A</code> doesn't contain <code>1</code>).</p>\n\n<p>If you chose to sort the array <code>A</code> first, which is a <code>O(n*log(n))</code> operation, then searching for the first non-negative, non-consecutive pair of elements would be a <code>O(n)</code> operation. It means the solution is reliably <code>O(n*log(n))</code>: it's better than your worst case, but worse than your best case. So which one is better? It's up to you to decide. It depends a lot on what you know about your input. If there are a lot of negative values, for instance, you could remove them as the first step: a partition is a <code>O(n)</code> operation. </p>\n\n<p>Now, if we leave the realm of the big O notation, creating an array of <code>max(A)</code> size can be a very costly operation. What if <code>Math.max.apply(null, A);</code> returns 99999999999999999999999999? Imagine an array this size, and then having to populate it with increasing values? So @Victor's proposed solution is better than your original code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:16:47.033", "Id": "406574", "Score": "0", "body": "but @Victor's solution will loop forever in case the array passed to the function does not have a missing element and this is one of the test cases, which will pass an array without a missing element, can you imagine how the code will behave?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T18:48:17.943", "Id": "406610", "Score": "0", "body": "@Victor's solution will not loop forever, unless he has an infinite array. His worst case will be for an array of \\$x\\$ elements his loop will exit at \\$n = x + 1\\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T06:53:46.743", "Id": "406655", "Score": "0", "body": "@rolfl, I think that this ```for (let n = 1; ; n++) {``` will loop forever if the array does not contain a missing value. Ex: ```[0, 1, 2, 3, 4, 5]```, Maybe you can try and see it, please take a look at the first solution, and I think anyway it is not a good practice not to limit the loop boundaries and keep it able to loop forever" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T15:10:46.533", "Id": "406728", "Score": "0", "body": "@MostafaA.Hamid - you're missing a significant point, for example, in your example `[0, 1, 2, 3, 4, 5]` it will exit when `n == 6`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T17:43:16.687", "Id": "406753", "Score": "0", "body": "Yes, it will finish the loop then exit, it will not detect that there are no missing elements unless it finishes the loop" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:53:25.123", "Id": "210359", "ParentId": "210348", "Score": "0" } }, { "body": "<p>I think we have being make in 2 stages.</p>\n\n<p><strong>FIRST</strong> sorting array;</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arr = [-5, 44, 43, -3, -7, 3, 3, 1, 2, 7, 4];\n arr.sort((item1, item2) =&gt; item1 - item2);\n console.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>SECOND</strong>. Array is sorting it means that every element of array will be equal array position minus positive position. However, we can have duplicate fields and we must process this situation: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//const arr = [-5, 44, 43, -3, -7, 1, 2,2,3, 5];\n//const arr = [ 0, 1, 0, 1, 0, 1, 2, 7, 4];\nconst arr = [ -100, -200];\n arr.sort((item1, item2) =&gt; item1 - item2);\n console.log(arr);\n \n // SECOND part\n \n let position = 0;\n let index = 1;\n for(let i = 0; i &lt; arr.length; i++) {\n \n if(arr[i] &lt;= 0) { //if NOT positive value we add one to position\n position = position + 1;\n continue;\n }\n \n if(i &gt; 0 &amp;&amp; arr[i] === arr[i-1]) {//if NOT duplicate value \n position = position + 1;\n continue;\n }\n \n index = i - position + 1;\n if(arr[i] !== index) {// end if value != index\n break;\n }\n }\n \n console.log(index);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>As result we have Sorting and one loop. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:54:18.377", "Id": "406580", "Score": "0", "body": "But it is missing the condition if all the values of the array are negative (it should return 1 in that case), I think that one line to be added to it to return 1 at the end of the ```for``` loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T04:35:12.593", "Id": "406648", "Score": "0", "body": "`Array.sort` is well above O(n), anywhere from O(n log(n)) to O(n^2) so that makes any function using `Array.sort` at least O(n^2)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:20:47.497", "Id": "210362", "ParentId": "210348", "Score": "0" } }, { "body": "<h1>Review</h1>\n\n<p>There are 3 answers already, yet none have addressed the flaws or reviewed your code. </p>\n\n<p>Thus I will give a detailed review and an alternative solution</p>\n\n<p>Your solution has bugs that make a estimation of complexity impossible.</p>\n\n<p>To help review your code I have numbered the lines. See <strong>Snippet (B)</strong> for line numbers</p>\n\n<h2>Flaws AKA bugs</h2>\n\n<p>There are many cases where your code can not run. 3 different errors the last is the worst type of error <strong>uncatchable</strong>.</p>\n\n<ol>\n<li><code>solution([-1,-2])</code> will throw an error.</li>\n<li><code>solution([1,2e100])</code> will throw an error.</li>\n<li><code>solution([1,2**31])</code> will crash the page after a long hangup on all but the top end machines.</li>\n</ol>\n\n<p>Your code is not <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> but rather it is incomplete or if run on a perfect machine <span class=\"math-container\">\\$\\mathcal{O}(\\infty)\\$</span> (and same storage) as that is the largest number that the function <code>Math.max</code> can return. </p>\n\n<p>Or if you have a max value less than the array size max then the complexity is <span class=\"math-container\">\\$\\mathcal{O}(2^{m+1})\\$</span> where <span class=\"math-container\">\\$m\\$</span> is the max value in the array.Thus the complexity for input <code>[1,2**32-1]</code> is a whopping <span class=\"math-container\">\\$\\mathcal{O}(n^{33})\\$</span> and storage of <span class=\"math-container\">\\$\\mathcal{O}(n^{32})\\$</span></p>\n\n<h2>By the lines</h2>\n\n<p>The following numbered items (bold numbers <strong>1</strong>) refer to your source code by line number</p>\n\n<ul>\n<li><strong>1</strong> <code>A</code> is a very poor name, <code>arr</code>, <code>array</code>, <code>nums</code>, <code>numbers</code> or many more. Even <code>a</code> would be better as we do not capitalize variable names unless they are instantiatable objects defined as functions or using the class syntax. </li>\n<li><strong>2</strong> <code>len</code> should be a constant. eg <code>const len</code> as it is not to be reassigned at any point in the code.</li>\n<li><strong>3</strong>, <strong>16</strong> and <strong>17</strong>. The <code>if</code> statements can be rearranged to reduce complexity.</li>\n<li><strong>4</strong> <code>max</code> should be a constant. Its almost 2019 and the spread operator <code>...</code> has been available for 4 years, Use it!!! Line <strong>4</strong> becomes <code>const max = Math.max(...A);</code></li>\n<li><strong>5</strong> Use constant <code>const range =</code>. You create an array of indexes from 0 to max. Which is a major problem, (See intro above) The irony is that you can (and do) calculate all the values from 0 to max via the for loop on the next line making line <strong>7</strong>. <code>A.include(range[i])</code> is identical to <code>A.include(i)</code></li>\n<li><strong>6</strong> <code>range.length</code> is the same as <code>max</code> so use the shorter form <code>for (let i = 0; i &lt; max; i ++) {</code></li>\n<li><strong>7</strong> Use the shorter form for not true <code>if (! A.includes(range[i])) {</code></li>\n<li><strong>8</strong> Use the shorter form is truthy. All numbers <code>!== 0</code> are truthy <code>true</code> thus this line can be <code>if (range[i]) {</code></li>\n<li><strong>9</strong> Could be <code>return i;</code></li>\n<li><strong>11</strong> and line <strong>13</strong> the continue is not needed as you are at the bottom of the for loop at those lines already.</li>\n<li><strong>16</strong> Use the strict equality operator <code>len === 1</code>. use the shorter not form of <code>val &lt; value || val &gt; value</code> as <code>val !== value</code>, making the line <code>} else if (len === 1 &amp;&amp; A[0] !== 1) {</code></li>\n<li><strong>18</strong> Use the strict equality operators, There is no need for the () around each clause <code>} else if (len === 1 &amp;&amp; A[0] === 1) {</code></li>\n</ul>\n\n<h2>General points.</h2>\n\n<ul>\n<li><p>If you <code>return</code> inside a statement block, you should not include the <code>else</code> at the end as It will never be used. Thus lines <strong>16</strong> and <strong>17</strong> do not need the <code>else</code> and can be moved down one line (away from the closing <code>}</code>)</p></li>\n<li><p>Though not a must it is cleaner to put spaces after <code>for</code>, <code>if</code>, <code>else</code> etc, before else, between <code>){</code></p></li>\n<li><p>When you find you are needing to search a set of values repeatedly it pays to consider using a Map or Set to find the matches as they use a hash to lookup values and have a complexity of <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> for the search, however to create the lookups is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. Thus using a Map or Set you can easily reduce complexity from <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> to <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. There is a storage penalty meaning you can go from <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> to <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. </p></li>\n</ul>\n\n<h2>Rewriting you code</h2>\n\n<p>Using a Set to remove the <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> overhead of each <code>Array.includes</code></p>\n\n<p>The Set <code>positiveInts</code> can be created as we iterate the array, saving a little complexity.</p>\n\n<p>I assume array items are less than or equal to <code>Number.MAX_SAFE_INTEGER</code> </p>\n\n<h3>Snippet (A)</h3>\n\n<pre><code>function solution(array) {\n var min = 1;\n if (array.length === 1) {\n min = array[0] === 1 ? 2 : min;\n } else if (array.length) {\n const positiveInts = new Set();\n for (const val of array) {\n if (val &gt; 0) {\n positiveInts.add(val);\n if (val === min) { \n while (positiveInts.has(min)) { min ++ }\n }\n }\n }\n }\n return min;\n}\n</code></pre>\n\n<h2>Snippet (B)</h2>\n\n<pre><code>/*lines*/\n/* 1*/function solution(A) {\n/* 2*/ var len = A.length;\n/* 3*/ if(len &gt; 1){\n/* 4*/ let max = Math.max.apply(null, A);\n/* 5*/ let range = Array.from(Array(max).keys());\n/* 6*/ for(let i = 0; i &lt; range.length; i++){\n/* 7*/ if(A.includes(range[i]) === false){\n/* 8*/ if(range[i] &gt; 0){\n/* 9*/ return range[i];\n/*10*/ }\n/*11*/ continue;\n/*12*/ }\n/*13*/ continue;\n/*14*/ }\n/*15*/ return max + 1;\n/*16*/ }else if(len == 1 &amp;&amp; (A[0] &lt; 1 || A[0] &gt; 1)){\n/*17*/ return 1;\n/*18*/ }else if((len == 1) &amp;&amp; (A[0] == 1)){\n/*19*/ return 2;\n/*20*/ }\n/*21*/ return 1;\n/*22*/}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T19:52:19.007", "Id": "406779", "Score": "0", "body": "Please use [chat] for extended discussions about a post. Thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:28:35.820", "Id": "210420", "ParentId": "210348", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T09:26:19.030", "Id": "210348", "Score": "2", "Tags": [ "javascript", "algorithm" ], "Title": "Get the first positive value that does not exist in array" }
210348
<p>I am trying to do my c++ homework and as a part of it I have to implement a <code>std::map</code> with an <code>int</code> as its <code>key</code> and a <code>value</code> should be a specific <code>void</code> function, which prints some text. I can`t find an answer to what are the correct ways of doing that.</p> <p>This is what I have so far:</p> <pre><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; class testClass { public: void testFunc1() { std::cout &lt;&lt; "func1\n"; } void testFunc2() { std::cout &lt;&lt; "func2\n"; } }; typedef void(testClass::*runFunc)(void); typedef std::map&lt;int, runFunc&gt; myMapType; int main() { testClass t1; std::map&lt;int, runFunc&gt; myMap; myMap.emplace(1, &amp;testClass::testFunc1); myMap.emplace(2, &amp;testClass::testFunc2); myMapType::const_iterator itr; itr = myMap.find(2); if (itr != myMap.end()) { (t1.*(itr-&gt;second))(); } } </code></pre> <p>The code is working now, however I am not sure if that is the way people with more experience do. </p> <p>Also, if you are aware of any sources where one can read more about knowledge required to achieve the needed result - any ideas are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T21:51:09.590", "Id": "406617", "Score": "1", "body": "If your code is a simplified version of what you really have to do, then it's off-topic and this question needs to be closed; per https://codereview.stackexchange.com/help/on-topic - \"In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used. Generic code (such as code containing placeholders like foo, MyClass, or doSomething()) leaves too much to the imagination.\"" } ]
[ { "body": "<p>In general your code looks good. But I have some little annotations (improvements) for you.</p>\n\n<h3>1. I'd prefer direct initialization of <code>itr</code> for sake of readability:</h3>\n\n<pre><code>myMapType::const_iterator itr = myMap.find(2);\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>myMapType::const_iterator itr;\nitr = myMap.find(2);\n</code></pre>\n\n<p>That said you could also avoid </p>\n\n<pre><code>typedef std::map&lt;int, runFunc&gt; myMapType;\n</code></pre>\n\n<p>completely using the <code>auto</code> keyword:</p>\n\n<pre><code>auto itr = myMap.find(2);\n</code></pre>\n\n<h3>2. Make use <code>std::function</code> and lambda bindings</h3>\n\n<p>For the callable value parameter of the <code>std::map</code> I'd prefer to use an appropriate <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a> value type and <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\"><em>lambda function bindings</em></a> to the instance to operate on.</p>\n\n<pre><code>testClass t1;\n\nstd::map&lt;int, std::function&lt;void()&gt;&gt; myMap;\nmyMap.emplace(1, [&amp;t1](){t1.testFunc1();});\nmyMap.emplace(2, [&amp;t1](){t1.testFunc2();});\n</code></pre>\n\n<p>This will give you greater flexibility for later changes and use of other classes than just <code>testClass</code>. Also you can get rid of that other type definition then:</p>\n\n<pre><code>typedef void(testClass::*runFunc)(void);\n</code></pre>\n\n<p>As soon you want to use your map for the general case you can clearly see the benefits:</p>\n\n<pre><code>class A {\npublic:\n void print() { std::cout &lt;&lt; \"print() from class A.\\n\"; }\n};\n\nclass B {\npublic:\n void print() { std::cout &lt;&lt; \"print() from class B.\\n\"; }\n};\n\n// ...\nint main() {\n A a;\n B b;\n\n std::map&lt;int, std::function&lt;void()&gt;&gt; myMap;\n myMap.emplace(1, [&amp;a](){a.print();});\n myMap.emplace(2, [&amp;b](){b.print();});\n\n}\n</code></pre>\n\n<hr>\n\n<p>Here's my set of changes in whole (you can check it's still working as intended <a href=\"http://coliru.stacked-crooked.com/a/ddc6f12661f9f89b\" rel=\"nofollow noreferrer\">here</a>): </p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;functional&gt;\n\nclass testClass\n{\npublic:\n void testFunc1() { std::cout &lt;&lt; \"func1\\n\"; }\n void testFunc2() { std::cout &lt;&lt; \"func2\\n\"; }\n};\n\nint main() {\n testClass t1;\n\n std::map&lt;int, std::function&lt;void()&gt;&gt; myMap;\n myMap.emplace(1, [&amp;t1](){t1.testFunc1();});\n myMap.emplace(2, [&amp;t1](){t1.testFunc2();});\n\n auto itr = myMap.find(2);\n\n if (itr != myMap.end()) {\n (itr-&gt;second)();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T15:55:41.510", "Id": "406591", "Score": "0", "body": "Instead of a lambda that calls the function you can use [std::bind](https://en.cppreference.com/w/cpp/utility/functional/bind)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:33:37.003", "Id": "406639", "Score": "2", "body": "@EmilyL. But lambdas are preferred over `std::bind`! There is no need for it now. Lambdas are far more expressive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:24:48.430", "Id": "406699", "Score": "0", "body": "@lightnessracesinorbit that's the first I've heard, can you give a reference? I still feel like bind is better expressing the intent" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T14:02:13.787", "Id": "406706", "Score": "2", "body": "@EmilyL. Sure! https://stackoverflow.com/a/17545183/560648" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:02:16.130", "Id": "210360", "ParentId": "210356", "Score": "5" } }, { "body": "<p>Given your current test code, there's no reason for <code>testClass</code> to exist. Your two test functions can simply be functions in the global namespace, and then your <code>emplace</code> calls can be simplified.</p>\n\n<pre><code>void testFunc1() { std::cout &lt;&lt; \"func1\\n\"; }\nvoid testFunc2() { std::cout &lt;&lt; \"func2\\n\"; }\n\ntypedef void(*runFunc)(void);\n// ...\n\nmyMap.emplace(1, testFunc1);\nmyMap.emplace(2, testFunc2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T18:40:51.500", "Id": "406608", "Score": "0", "body": "thanks for your suggestion. my code above is a simplified version of what I really have to do. with just global functions it won't go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T21:52:29.800", "Id": "406618", "Score": "0", "body": "See comments on question, in that case. This is off-topic." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T17:54:03.953", "Id": "210378", "ParentId": "210356", "Score": "0" } }, { "body": "<p>As other answers have already said, the trick you're looking for is called <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a>, and it's defined in the standard <code>&lt;functional&gt;</code> header.</p>\n\n<p>You include <code>&lt;string&gt;</code> but never use it. You define <code>myMapType</code> but never use it.</p>\n\n<p>Unless you need portability back to C++03, you should use <code>using X = Y;</code> in place of <code>typedef Y X;</code>.</p>\n\n<p>A common name for \"scratch\" iterator variables is <code>it</code> (not to be confused with <code>i</code> for integer indices). Your <code>itr</code> is reasonably clear, but not idiomatic.</p>\n\n<hr>\n\n<p>Following the dictum that \"good C++ code should look like Python,\" I'd write your program like this:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;functional&gt;\n#include &lt;map&gt;\n\nvoid testFunc1() {\n puts(\"func1\");\n} \nvoid testFunc2() {\n puts(\"func2\");\n}\n\nusing MapType = std::map&lt;int, std::function&lt;void()&gt;&gt;;\n\nint main() {\n MapType myMap = {\n { 1, testFunc1 },\n { 2, testFunc2 },\n };\n\n auto it = myMap.find(2);\n if (it != myMap.end()) {\n it-&gt;second();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Instead of the map initializer I wrote, you could write</p>\n\n<pre><code>MapType myMap;\nmyMap[1] = testFunc1;\nmyMap[2] = testFunc2;\n</code></pre>\n\n<p>but I strongly recommend \"declarative\" over \"imperative.\" \"Declarative\" style means to define the whole map at once, as a data object, in the state you want it; \"imperative\" style means to define an empty map and then repeatedly mutate it so as to <em>eventually arrive at</em> the state you want. \"Declarative\" tends to be easier to reason about.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:06:04.493", "Id": "210396", "ParentId": "210356", "Score": "2" } } ]
{ "AcceptedAnswerId": "210396", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:01:23.507", "Id": "210356", "Score": "6", "Tags": [ "c++" ], "Title": "Improvement for std::map <int, run_some_function> double dispatch" }
210356
<p>Here is my code with 2 services, one is <code>messageService</code> which is used to get user messages:</p> <pre><code>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import 'rxjs/add/operator/retry'; import 'rxjs/add/operator/catch'; import { handleError } from '../common/error-handler'; @Injectable({ providedIn: 'root' }) export class MessagesService { private _config = environment; constructor(private http: HttpClient) { } getMessages() { return this.http.get(`${this._config.apiUrl}/messages`) .retry(3) .map(data =&gt; (data &amp;&amp; data['messages']) || []) .catch(handleError); } } </code></pre> <p>And the other is <code>usersService</code> which is used to get user information based on <code>user_id</code>:</p> <pre><code>import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { Injectable } from '@angular/core'; import { handleError } from '../common/error-handler'; @Injectable({ providedIn: 'root' }) export class UsersService { private _config = environment; constructor(private http: HttpClient) { } getUser(user_id) { return this.http.get(`${this._config.apiUrl}/users/${user_id}/public_profile`) .retry(3) .map(data =&gt; data || {}) .catch(handleError); } } </code></pre> <p>And in the constructor of my component:</p> <pre><code> @Component({ selector: 'wall', templateUrl: './wall.component.html', styleUrls: ['./wall.component.css'] }) export class WallComponent { constructor(private messageService: MessagesService, private usersService: UsersService) { this.messageService.getMessages() .switchMap(response =&gt; { let resArray: any[] = response.map( post =&gt; { return Observable.zip( this.usersService.getUser(post.user_id), Observable.of(post) ); }); return Observable.merge(...resArray) }).switchMap(res =&gt; { res[1]['user'] = res[0]; this.messages.push(res[1]); return Observable.of(res[1]); }) .subscribe(final_post =&gt; { console.log('final post:', final_post) }) } } </code></pre> <p><strong>The question is</strong> how should I get user messages using <code>Observable</code> and then getting users information for each message (each message may have different user information), then merging them into one object which finally will be used in the desired component with fewer <code>Observable</code> pipelines? I suppose using <code>merge</code> and then again <code>switchMap</code> to merge these data is not optimal and best practice.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T13:22:33.400", "Id": "210358", "Score": "3", "Tags": [ "typescript", "angular-2+", "rxjs" ], "Title": "Fetching user information along with user posts in Angular" }
210358
<p>How could I rewrite this jquery code to compact it in a more elegant form:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ $('input[name="table_exist"]').click(function(){ if($('input[name="table_name"]').val()=='users' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="table_name"]').val(''); } else if($('input[name="table_name"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="table_name"]').val('users'); } if($('input[name="user_id"]').val()=='user_id' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="user_id"]').val(''); } else if($('input[name="user_id"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="user_id"]').val('user_id'); } if($('input[name="user_name"]').val()=='user_name' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="user_name"]').val(''); } else if($('input[name="user_name"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="user_name"]').val('user_name'); } if($('input[name="user_email"]').val()=='user_email' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="user_email"]').val(''); } else if($('input[name="user_email"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="user_email"]').val('user_email'); } if($('input[name="user_pass"]').val()=='user_pass' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="user_pass"]').val(''); } else if($('input[name="user_pass"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="user_pass"]').val('user_pass'); } if($('input[name="joining_date"]').val()=='joining_date' &amp;&amp; $('input[name="table_exist"]').is(':checked')) { $('input[name="joining_date"]').val(''); } else if($('input[name="joining_date"]').val()=='' &amp;&amp; !$('input[name="table_exist"]').is(':checked')) { $('input[name="joining_date"]').val('joining_date'); } }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;form method="POST"&gt; &lt;h2&gt;DB Table&lt;/h2&gt; &lt;p&gt; Activate the slider if you already have your own database table created! &lt;/p&gt; &lt;div class="inputCheckBox"&gt; &lt;input type="checkbox" name="table_exist" /&gt; &lt;/div&gt; &lt;p&gt; Edit here only if you have your own predifined table header names! &lt;/p&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="table_name" value="users" required /&gt; &lt;label&gt;Table Name&lt;/label&gt; &lt;/div&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="user_id" value="user_id" required /&gt; &lt;label&gt;User ID&lt;/label&gt; &lt;/div&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="user_name" value="user_name" required /&gt; &lt;label&gt;User Name&lt;/label&gt; &lt;/div&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="user_email" value="user_email" required /&gt; &lt;label&gt;User E-mail&lt;/label&gt; &lt;/div&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="user_pass" value="user_pass" required /&gt; &lt;label&gt;User Password&lt;/label&gt; &lt;/div&gt; &lt;div class="inputBox"&gt; &lt;input type="text" name="joining_date" value="joining_date" required /&gt; &lt;label&gt;User Added Date&lt;/label&gt; &lt;/div&gt; &lt;button type="submit" name="btn-install"&gt; Install &lt;/button&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>The whole process is to identify if the fields have the default values when a checkbox is unchecked. If the state is changed to checked then empty all fields to input custom information/values. If unchecked again it returns the initial values.</p>
[]
[ { "body": "<p>There're multiple ways to do that. You should use a loop.</p>\n\n<p>I've wrote a small script, that would do the job. I do not know if the if block is correct but you should easily fix that with this base.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).ready(function(){\n$('input[name=\"table_exist\"]').click(function(){\n var table_exist_checked = $('input[name=\"table_exist\"]').is(':checked');\n \n var fields = [\n 'table_name',\n 'user_id',\n 'user_name',\n 'user_email',\n 'user_pass',\n 'joining_date',\n ]; // Your field names\n \n // iterate over all fieldnames\n for(var index of fields) {\n var fieldName = fields[index]; // extract current fieldName\n var $elem = $('input[name=\"' + fieldName + '\"]'); // save current element so we do not need to repeat\n \n // This is ur if-else. I do not exactly know if this is correct\n if($elem.val() == fieldName &amp;&amp; table_exist_checked){\n $elem.val('');\n } else if($elem.val()=='' &amp;&amp; !table_exist_checked){\n $elem.val(fieldName);\n }\n }\n \n}); });</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T16:40:29.367", "Id": "210370", "ParentId": "210361", "Score": "2" } }, { "body": "<p>Following @ArayniMax example I fixed it this way:</p>\n\n<pre><code>$(document).ready(function(){\n $('input[name=\"table_exist\"]').click(function(){\n\n var inputCheck = $('input[name=\"table_exist\"]').is(':checked');\n\n var fields = {\n 'table_name': 'users',\n 'user_id': 'user_id',\n 'user_name': 'user_name',\n 'user_email': 'user_email',\n 'user_pass': 'user_pass',\n 'joining_date': 'joining_date'\n };\n\n $.each(fields, function(key, value) {\n\n var fieldInput = $('input[name=\"' + key + '\"]');\n\n if(fieldInput.val()==value &amp;&amp; inputCheck)\n {\n fieldInput.val('');\n }\n else if(fieldInput.val()=='' &amp;&amp; !inputCheck)\n {\n fieldInput.val(value);\n }\n });\n });\n});\n</code></pre>\n\n<p>Thank you for your help everyone!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T18:22:36.410", "Id": "210379", "ParentId": "210361", "Score": "0" } } ]
{ "AcceptedAnswerId": "210370", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:15:02.433", "Id": "210361", "Score": "1", "Tags": [ "javascript", "jquery", "form" ], "Title": "jQuery code to detect whether form fields have the default value when a checkbox is unchecked" }
210361
<p>I've begun developing a library which can be used to represent and analyse corporate ownership structures. The first stage has been to design a library which allows a user to model ownership structures (e.g. company A owns 52% of B and 90% of C).</p> <p>The library contains two fundamental types - entities (i.e. companies) and entityspace (where different entities exist). Each entity has a vector of 'relations' which relate that entity to another entity via an ownership relation (e.g. a relation might designate A as a parent of B with 50 'units' of ownership). Each relation is mirrored in the related entity's relations vector (e.g. if A has a relation which shows it has 50 units in B then B will have a relation showing it has 50 units owned by A).</p> <p>I'd be grateful for any comments on this library, especially the design (e.g. is it ok for each entity object to refer back to the entityspace,should the 'link' functions in the entity class actually belong to entityspace, am I returning the appropriate types).</p> <p>Thanks</p> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &quot;Entityspace.h&quot; using namespace std; int main() { Entityspace test; EntityID father = test.addEntity(&quot;Father Ltd&quot;, EType::LTD); EntityID mother = test.addEntity(&quot;Mother Plc&quot;, EType::PLC); EntityID son = test.addEntity(&quot;Son LLP&quot;, EType::LLP); EntityID daughter = test.addEntity(&quot;Daughter&quot;, EType::IND); test[father].addEntAsChild(son,40, UType::ORDINARY_SHARE); test[father].addEntAsChild(daughter,30, UType::ORDINARY_SHARE); test[son].addEntAsParent(mother,50, UType::ORDINARY_SHARE); test[daughter].addEntAsParent(mother,60, UType::ORDINARY_SHARE); test.deleteEntity(mother); VecEID ents = test.findParentsOf(son); return 0; } </code></pre> <p><strong>Entityspace.h</strong>:</p> <pre><code>#ifndef ENTITYSPACE_H #define ENTITYSPACE_H #include &lt;map&gt; #include &quot;Entity.h&quot; using namespace std; class Entityspace { private: map&lt;EntityID,Entity&gt; EntityContainer; VecEID findDirectRelations(EntityID id, RType rel_type) const; //function used by findParentsOf and findChildrenOf public: Entity&amp; operator[](EntityID id); const Entity&amp; operator[](EntityID id) const; //const qualified version EntityID addEntity(const string&amp; nm, EType type); bool deleteEntity(EntityID id); bool hasEntity (EntityID Id) const; int totalEntsCount() const; //methods of finding related entities VecEID findParentsOf(EntityID id) const; VecEID findChildrenOf(EntityID id) const; VecEID findSiblingsOf(EntityID id) const; }; #endif </code></pre> <p><strong>Entityspace.cpp:</strong></p> <pre><code>#include &lt;algorithm&gt; #include &quot;Entityspace.h&quot; //private member functions VecEID Entityspace::findDirectRelations(EntityID Id,RType rtype) const { VecEID relatedEnts; const Entity&amp; ent = (*this)[Id]; VecRel foundRels = ent.findRelsByType(rtype); for (VecRel_It it = foundRels.begin(); it != foundRels.end();it++) { if (find(relatedEnts.begin(), relatedEnts.end(),it-&gt;related_ent_id) == relatedEnts.end()) //do not add duplicate parents { relatedEnts.push_back(it-&gt;related_ent_id); } } return relatedEnts; } Entity&amp; Entityspace::operator[](EntityID Id) { return EntityContainer.at(Id); } const Entity&amp; Entityspace::operator[](EntityID Id) const { return EntityContainer.at(Id); } //public member functions EntityID Entityspace::addEntity(const string&amp; nm,EType type) { Entity ent(nm,type, *this); EntityContainer.insert(pair&lt;EntityID,Entity&gt;(ent.getId(),ent)); return ent.getId(); } bool Entityspace::deleteEntity(EntityID Id) { if (!hasEntity(Id)) //cannot delete entity if it does not exist { return false; } Entity&amp; entToDel = (*this)[Id]; VecRel entToDelRels = entToDel.getRelsVec(); //all relations of the entity to be deleted for (VecRel::const_iterator it = entToDelRels.begin(); it != entToDelRels.end();++it) { if (!entToDel.deleteRelation(*it)) //delink every relation in the entity being deleted (so that equivalent relations removed from related entities) { return false; //if a delink fails then PROBLEM that other relations already deleted } } EntityContainer.erase(Id); //remove the entity from Entityspace return true; } bool Entityspace::hasEntity(EntityID Id) const { return (EntityContainer.find(Id) != EntityContainer.end()); } int Entityspace::totalEntsCount() const { return EntityContainer.size(); } VecEID Entityspace::findParentsOf(EntityID Id) const { return findDirectRelations(Id, RType::OWNED_BY); } VecEID Entityspace::findChildrenOf(EntityID Id) const { return findDirectRelations(Id, RType::OWNER_OF); } VecEID Entityspace::findSiblingsOf(EntityID Id) const { VecEID sibEntsArr; VecEID prtEnts = findParentsOf(Id);// all parents for (VecEID_It prtIt = prtEnts.begin(); prtIt != prtEnts.end();prtIt++) { VecEID prtCldEnts = findChildrenOf(*prtIt); //all children of each parent for (VecEID_It prtCldIt = prtCldEnts.begin(); prtCldIt != prtCldEnts.end();prtCldIt++) { if (*prtCldIt == Id) // do not add a the current entity { continue; } if (find(sibEntsArr.begin(),sibEntsArr.end(),*prtCldIt) != sibEntsArr.end()) //do not add duplicate siblings { continue; } sibEntsArr.push_back(*prtCldIt); } } return sibEntsArr; } </code></pre> <p><strong>Entity.h:</strong></p> <pre><code>#ifndef ENTITY_H #define ENTITY_H #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; using namespace std; class Entityspace; //forward declaration enum class RType { OWNER_OF, OWNED_BY }; enum class EType{ //type of entity LTD, LLP, PLC, IND }; enum class UType{ //type of unit ORDINARY_SHARE, PREFERENCE_SHARE, VOTING_RIGHT, LLP_MEMBER }; struct relation; //forward declaration typedef vector&lt;relation&gt; VecRel; typedef vector&lt;relation&gt;::const_iterator VecRel_It; typedef unsigned int EntityID; typedef vector&lt;EntityID&gt; VecEID; typedef vector&lt;EntityID&gt;::const_iterator VecEID_It; class Entity { private: //private variables static int idgenerator; //used to generate 'unique' ids for Entity objects string name; EntityID ent_id; EType type; VecRel rels_v; //stores all relations with other objects (i.e. as parent/child) - these relations are mirrored in related Entity. There may be identical relations stored in this vector. Entityspace&amp; rEntityContainer; //reference to container - this allows Entity methods to access other Entities through the Entityspace map //private member functions - can still be accessed by other Entity objects void addRelToVec(relation rel); void delRelFrVec(VecRel_It rel); //deletes relation from relations vector VecRel_It findFirstRel(relation rel); //return iterator to first matching relation in relsvec VecRel_It relsVecEnd(); //iterator to end of relsvec public: Entity (string value1, EType value2, Entityspace&amp; ES_r); //getter/setters void setName(string name); string getName() const; EntityID getId() const; //linkage functions bool addRelation(relation rel); //this adds a relation to rels_v bool addEntAsParent(EntityID id, unsigned int units, UType units_type); //convenience function bool addEntAsChild(EntityID id, unsigned int units, UType units_type); //convenience function bool deleteRelation(relation rel); //remove first matching relation from rels_v //find functions VecRel getRelsVec() const; //this returns a copy of a vector of an Entities' relations VecRel findRelsById(EntityID rel_id) const; //returns a vector of relations with matching Id VecRel findRelsByType(RType type) const; VecRel findRelsByUnits(unsigned int min_units, unsigned int max_units) const; }; struct relation { //struct containing entity related to, number of ownership units owned and type of relationship i.e. owned by/owner of EntityID related_ent_id; //the id of the parent/child unsigned int units; //how many units are owned UType units_type; //type of unit RType rel_type; //OWNER_OF or OWNED_BY bool operator==(const relation &amp;rhs) //when we need to compare a relation - think this may redundant { return (related_ent_id==rhs.related_ent_id &amp;&amp; units==rhs.units &amp;&amp; units_type==rhs.units_type &amp;&amp; rel_type==rhs.rel_type); } }; #endif </code></pre> <p><strong>Entity.cpp:</strong></p> <pre><code>#include &lt;algorithm&gt; #include &quot;Entity.h&quot; #include &quot;Entityspace.h&quot; //because we are using methods of Entityspace class which has been forward declared int Entity::idgenerator = 1; // initialisation of static idgenerator //private member functions void Entity::addRelToVec(relation rel) { rels_v.push_back(rel); } void Entity::delRelFrVec(VecRel_It relIt) { rels_v.erase(relIt); } VecRel_It Entity::findFirstRel(relation rel) { return find(rels_v.begin(), rels_v.end(), rel); } VecRel_It Entity::relsVecEnd() { return rels_v.end(); } //public member functions Entity::Entity (string value1, EType value2, Entityspace&amp; value3): name(value1), type(value2), rEntityContainer(value3) { ent_id = idgenerator; idgenerator++; } void Entity::setName(string nm) { name = nm; } string Entity::getName() const { return name; } EntityID Entity::getId() const { return ent_id; } bool Entity::addRelation (relation rel) { //check to ensure valid request if (rel.related_ent_id == getId()) //cannot link to self { return false; } if (!rEntityContainer.hasEntity(rel.related_ent_id)) // cannot find entity to be linked { return false; } //valid, so make link addRelToVec(rel); RType rev_rel_type = static_cast&lt;RType&gt;(1 - static_cast&lt;underlying_type&lt;RType&gt;::type&gt; (rel.rel_type)); //ugly way of flipping enum (as other entity will have opposite relation type) rEntityContainer[rel.related_ent_id].addRelToVec(relation{getId(),rel.units,rel.units_type,rev_rel_type}); //add equivalent relation to entity to be linked return true; } bool Entity::addEntAsParent(EntityID id, unsigned int units, UType units_type) { return addRelation(relation{id,units,units_type, RType::OWNED_BY}); } bool Entity::addEntAsChild(EntityID id, unsigned int units, UType units_type) { return addRelation(relation{id,units, units_type, RType::OWNER_OF}); } bool Entity::deleteRelation(relation rel) { //check its ok to delink if(rel.related_ent_id == getId()) // cannot delink self { return false; } if (!rEntityContainer.hasEntity(rel.related_ent_id)) // cannot find entity to be delinked { return false; } Entity&amp; lnkEnt = rEntityContainer[rel.related_ent_id]; //reference to entity to be delinked VecRel_It entRelIt = findFirstRel(rel); //get iterator to first matching relation in current ent if (entRelIt == relsVecEnd()) //if none found then terminate { return false; } relation opp_rel {getId(),rel.units,rel.units_type,static_cast&lt;RType&gt;(1 - static_cast&lt;underlying_type&lt;RType&gt;::type&gt; (rel.rel_type))}; //this is the equivalent relation in the linked object VecRel_It lnkEntRelIt = lnkEnt.findFirstRel(opp_rel); // if (lnkEntRelIt == lnkEnt.relsVecEnd()) { return false; } //ok to remove links delRelFrVec(entRelIt); lnkEnt.delRelFrVec(lnkEntRelIt); return true; } VecRel Entity::getRelsVec() const { return rels_v; } VecRel Entity::findRelsById (EntityID rel_id) const { VecRel relsToReturn; for (VecRel_It it = rels_v.begin(); it != rels_v.end();it++) { if (it-&gt;related_ent_id == rel_id) { relsToReturn.push_back(*it); } } return relsToReturn; } VecRel Entity::findRelsByType (RType type) const { VecRel relsToReturn; for (VecRel_It it = rels_v.begin(); it != rels_v.end();++it) { if (it-&gt;rel_type == type) { relsToReturn.push_back(*it); } } return relsToReturn; } VecRel Entity::findRelsByUnits (unsigned min, unsigned max) const { VecRel relsToReturn; // vector of iterators to elements in relations vector for (VecRel_It it = rels_v.begin(); it != rels_v.end();++it) { if (it-&gt;units &gt;= min &amp;&amp; it-&gt;units &lt;= max) { relsToReturn.push_back(*it); } } return relsToReturn; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T21:31:56.167", "Id": "406615", "Score": "0", "body": "Just to be devil's advocate, wouldn't the problem this code is solving be sufficiently and more easily solved by a simple spreadsheet? You're writing a library but who exactly are you expecting to use this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T21:43:48.223", "Id": "406616", "Score": "0", "body": "Hi, I probably didn't make this clear enough but the work so far is just in representing the relationships. The idea is to analyse complex ownership relationships e.g: if A owns 50% of B and B owns 15% of C, what is A's effective stake in C? Or, how closely connected are two companies or what are the sibling entities? I think it would be extremely difficult to do this in a spreadsheet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:21:41.110", "Id": "406697", "Score": "1", "body": "How often will you be using this? My point is that I think that you are spending a lot of effort on writing code that will be used a few times only and maybe there is an easier way for you solve your specific problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T19:43:40.120", "Id": "490953", "Score": "0", "body": "Removing code in the question goes against the Question + Answer style of Code Review. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Take this with a grain of salt, because my \"modern\" C++ is not at all fluent, but: read about this form of <code>for</code> loop.</p>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/range-for</a></p>\n\n<p>This will allow you to simplify your loops that operate on STL iterators.</p>\n\n<p>Otherwise, your code seems quite clean to me. Consider adding structured documentation, in a format such as the one that Doxygen supports.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T17:33:39.810", "Id": "210373", "ParentId": "210364", "Score": "1" } }, { "body": "<p>I've not looked over all the code, but here are some observations.</p>\n\n<p>Avoid <code>using namespace std;</code>.</p>\n\n<p>You don't document how you handle not finding a company when you try to look it up with your <code>operator[]</code> function. The expectation (from the standard containers) is that if this method is provided, the existing element will be returned or a new one will be created. No exceptions will be thrown. Your code defers to map's <code>at</code>, which will throw an exception if the EntityId is not found. These should probably be called <code>at</code> instead.</p>\n\n<p>You have inconsistent spacing. The <code>public:</code> in <code>Entityspace</code> is indented and hard to see, and some of your function calls lack spaces after a comma (see, for example, the call to <code>addEntAsChild</code> in <code>main</code>, and your declaration of <code>EntityContainer</code> in <code>Entityspace</code>).</p>\n\n<p>In <code>addEntity</code>, you use map's <code>insert</code> method. However, the <code>pair</code> you pass is not correctly typed. A map has a <code>const</code> first value in the pair, so the correct type is <code>pair&lt;const EntityID, Entity&gt;</code>. Without that const there will be one pair created, then copied to a 2nd pair to convert it to the correct type. A simple way to avoid this is to use the <code>value_type</code> of the map if you have a <code>typedef</code> for it. Better still is to forgo <code>insert</code> and use <code>emplace</code>.</p>\n\n<pre><code>EntityContainer.emplace(ent.getId(), ent);\n</code></pre>\n\n<p>How does <code>addEntity</code> behave if an entity already exists? Since you're ignoring the result from <code>insert</code> (or <code>emplace</code>), you'll return the wrong Id. It should return the one stored in the map, not the temporary object created for the insertion.</p>\n\n<p><code>totalEntsCount</code> should return a <code>size_t</code>.</p>\n\n<p>Some of your for loops can be simplified using the range-based for loop. For example, instead of</p>\n\n<pre><code>for (VecEID_It prtIt = prtEnts.begin(); prtIt != prtEnts.end();prtIt++)\n{\n VecEID prtCldEnts = findChildrenOf(*prtIt); //all children of each parent\n</code></pre>\n\n<p>you can use</p>\n\n<pre><code>for (const auto &amp;prt: prtEnts)\n{\n VecEID prtCldEnts = findChildrenOf(prt);\n</code></pre>\n\n<p>Your use of <code>1 - rtype</code> to change the relation type makes an assumption about the relative difference of <code>OWNER_OF</code> and <code>OWNER_OF</code>. If this ever changes (because you add more complicated relations or different relation types) your code will break in possibly hard to detect ways. A better way to do this is to create a function to call to get the complementary/reverse relation given an existing relationship.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T19:38:53.153", "Id": "406611", "Score": "0", "body": "thanks very much, all good observations/suggestions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T19:26:40.393", "Id": "210383", "ParentId": "210364", "Score": "1" } } ]
{ "AcceptedAnswerId": "210383", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:34:58.130", "Id": "210364", "Score": "3", "Tags": [ "c++" ], "Title": "Library to analyse corporate ownership" }
210364
<p>I have built an Excel application, which gets all the titles of books from Amazon.com, which it is asked to do and scrapes the following data out of them:</p> <ul> <li>Book Title</li> <li>Author</li> <li>Price</li> </ul> <p><strong>What do you need to run the app?</strong> </p> <p>3 worksheets in Excel, named as in the picture:</p> <p><a href="https://i.stack.imgur.com/vRzrP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vRzrP.png" alt="enter image description here"></a></p> <p>Then in <code>tblInput</code>, make sure to write some keywords in range <code>A2:A4</code> and execute the <code>Main</code> function. No dependencies or additional Excel libraries to be added. </p> <p>The code is also in <a href="https://github.com/Vitosh/VBA_personal/tree/master/DataScrapingFromInternet" rel="nofollow noreferrer">GitHub here</a>. I wrote a blog post about it - <a href="http://www.vitoshacademy.com/vba-data-scraping-from-internet-with-excel-part-2/" rel="nofollow noreferrer">http://www.vitoshacademy.com/vba-data-scraping-from-internet-with-excel-part-2/</a></p> <p><strong>AmazonInternet</strong></p> <pre><code>Public Function PageWithResultsExists(appIE As Object, keyword As String) As Boolean On Error GoTo PageWithResultsExists_Error Dim allData As Object Set allData = appIE.document.getElementById("s-results-list-atf") PageWithResultsExists = True IeErrors = 0 On Error GoTo 0 Exit Function PageWithResultsExists_Error: WaitSomeMilliseconds IeErrors = IeErrors + 1 Select Case Err.Number Case 424 If IeErrors &gt; MAX_IE_ERRORS Then PageWithResultsExists = False IeErrors = 0 Else LogMe "PageWithResultsExists", IeErrors, keyword, IeErrors PageWithResultsExists appIE, keyword End If Case Else Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext End Select End Function Public Function MakeUrl(i As Long, keyword As String) As String MakeUrl = "https://www.amazon.com/s/ref=sr_pg_" &amp; i &amp; "?rh=i%3Aaps%2Ck%3A" &amp; keyword &amp; "&amp;page=" &amp; i &amp; "&amp;keywords=" &amp; keyword End Function Public Sub Navigate(i As Long, appIE As Object, keyword As String) Do While appIE.Busy DoEvents Loop With appIE .Navigate MakeUrl(i, keyword) .Visible = False End With Do While appIE.Busy DoEvents Loop End Sub </code></pre> <p><strong>ConstValues</strong></p> <pre><code>Public IeErrors As Long Public Const MAX_IE_ERRORS = 10 Public Const IN_PRODUCTION = False </code></pre> <p><strong>ExcelRelated</strong></p> <pre><code>Public Function GetNextKeyWord() As String With tblInput Dim lastRowB As Long lastRowB = lastRow(.Name, 2) + 1 GetNextKeyWord = Trim(.Cells(lastRowB, 1)) If Len(GetNextKeyWord) &lt;&gt; 0 Then .Cells(lastRowB, 2) = Now End With End Function Public Sub WriteFormulas() Dim i As Long With tblInput For i = lastRow(.Name) To 2 Step -1 .Cells(i, 3).FormulaR1C1 = "=COUNTIF(Summary!C[1],Input!RC[-2])" .Cells(i, 4).FormulaArray = "=MAX(IF(Summary!C=RC[-3],Summary!C[-1]))" FormatUSD .Cells(i, 4) .Cells(i, 5).FormulaArray = "=AVERAGE(IF(Summary!C[-1]=Input!RC[-4],Summary!C[-2]))" FormatUSD .Cells(i, 5) Next i End With End Sub Public Sub FixWorksheets() OnStart With tblInput .Range("B1") = "Start Time" .Range("C1") = "Count" .Range("D1") = "Max" .Range("E1") = "Average" End With With tblSummary .Range("A1") = "Title" .Range("B1") = "Author" .Range("C1") = "Price" .Range("D1") = "Keyword" End With Dim ws As Worksheet For Each ws In Worksheets ws.Columns.AutoFit Next ws OnEnd End Sub Public Sub FormatUSD(myRange As Range) myRange.NumberFormat = "_-[<span class="math-container">$$-409]* #,##0.00_ ;_-[$$</span>-409]* -#,##0.00 ;_-[$$-409]* ""-""??_ ;_-@_ " End Sub Public Sub CleanWorksheets() tblRawData.Cells.Delete tblSummary.Cells.Delete tblInput.Columns("B:F").Delete End Sub Public Function GetNthString(n As Long, myRange As Range) As String Dim i As Long Dim myVar As Variant myVar = Split(myRange, vbCrLf) For i = LBound(myVar) To UBound(myVar) If Len(myVar(i)) &gt; 0 And n = 0 Then GetNthString = myVar(i) Exit Function ElseIf Len(myVar(i)) &gt; 0 Then n = n - 1 End If Next i End Function Public Function GetPrice(myRange As Range) As String Dim i As Long Dim myVar As Variant myVar = Split(myRange, "$") If UBound(myVar) &gt; 0 Then GetPrice = Mid(myVar(1), 1, InStr(1, myVar(1), " ")) Else GetPrice = "" End If End Function Public Sub WriteToExcel(appIE As Object, keyword As String) If IN_PRODUCTION Then On Error GoTo WriteToExcel_Error Dim allData As Object Set allData = appIE.document.getElementById("s-results-list-atf") Dim book As Object Dim myRow As Long For Each book In allData.getElementsByClassName("a-fixed-left-grid-inner") With tblRawData myRow = lastRow(.Name) + 1 On Error Resume Next .Cells(myRow, 1) = book.innertext .Cells(myRow, 2) = keyword On Error GoTo 0 End With Next IeErrors = 0 On Error GoTo 0 Exit Sub WriteToExcel_Error: IeErrors = IeErrors + 1 If IeErrors &gt; MAX_IE_ERRORS Then Debug.Print "Error " &amp; Err.Number &amp; " (" &amp; Err.Description &amp; ") in procedure WriteToExcel, line " &amp; Erl &amp; "." Else LogMe "WriteToExcel", IeErrors, keyword, IeErrors WriteToExcel appIE, keyword End If End Sub Public Sub RawDataToStructured(keyword As String, firstRow As Long) Dim i As Long For i = firstRow To lastRow(tblRawData.Name) With tblRawData If InStr(1, .Cells(i, 1), "Sponsored ") &lt; 1 Then Dim title As String title = GetNthString(0, .Cells(i, 1)) Dim author As String author = GetNthString(1, .Cells(i, 1)) Dim price As String price = GetPrice(.Cells(i, 1)) If Not IsNumeric(price) Or price = "0" Then price = "" Dim currentRow As String: currentRow = lastRow(tblSummary.Name) + 1 With tblSummary .Cells(currentRow, 1) = title .Cells(currentRow, 2) = author .Cells(currentRow, 3) = price .Cells(currentRow, 4) = keyword End With End If End With Next i End Sub Public Function lastRow(wsName As String, Optional columnToCheck As Long = 1) As Long Dim ws As Worksheet Set ws = Worksheets(wsName) lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row End Function </code></pre> <p><strong>General</strong></p> <pre><code>Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) Public Sub OnEnd() Application.ScreenUpdating = True Application.EnableEvents = True Application.AskToUpdateLinks = True Application.DisplayAlerts = True Application.Calculation = xlAutomatic ThisWorkbook.Date1904 = False Application.StatusBar = False End Sub Public Sub OnStart() Application.ScreenUpdating = False Application.EnableEvents = False Application.AskToUpdateLinks = False Application.DisplayAlerts = False Application.Calculation = xlAutomatic ThisWorkbook.Date1904 = False ActiveWindow.View = xlNormalView End Sub Public Sub LogMe(ParamArray arg() As Variant) Debug.Print Join(arg, "--") End Sub Public Sub PrintMeUsefulFormula() Dim strFormula As String Dim strParenth As String strParenth = """" strFormula = Selection.FormulaR1C1 strFormula = Replace(strFormula, """", """""") strFormula = strParenth &amp; strFormula &amp; strParenth Debug.Print strFormula End Sub Public Sub WaitSomeMilliseconds(Optional Milliseconds As Long = 1000) Sleep Milliseconds End Sub </code></pre> <p><strong>StartUp</strong></p> <pre><code>Public Sub Main() If IN_PRODUCTION Then On Error GoTo Main_Error CleanWorksheets Dim keyword As String: keyword = GetNextKeyWord While keyword &lt;&gt; "" Dim appIE As Object Set appIE = CreateObject("InternetExplorer.Application") LogMe keyword Dim nextPageExists As Boolean: nextPageExists = True Dim i As Long: i = 1 Dim firstRow As Long: firstRow = lastRow(tblRawData.Name) + 1 While nextPageExists WaitSomeMilliseconds Navigate i, appIE, keyword nextPageExists = PageWithResultsExists(appIE, keyword) If nextPageExists Then WriteToExcel appIE, keyword i = i + 1 Wend LogMe Time, keyword, "RawDataToStructured" RawDataToStructured keyword, firstRow keyword = GetNextKeyWord WaitSomeMilliseconds 4000 appIE.Quit Wend FixWorksheets WriteFormulas LogMe "Program has ended!" On Error GoTo 0 Exit Sub Main_Error: MsgBox "Error " &amp; Err.Number &amp; " (" &amp; Err.Description &amp; ") in procedure Main, line " &amp; Erl &amp; "." End Sub </code></pre> <p>In general, I probably could have done it with some OOP/classes, but I have considered not to.</p> <p>Thanks! </p>
[]
[ { "body": "<ul>\n<li><p><code>OnStart</code> and <code>OnEnd</code> should be called from <code>Main</code>.</p></li>\n<li><p>Although, I am a proponent of using single letter iterates in simple <code>For</code> loops, I think that <code>i</code> should have a more descriptive name like <code>pageIndex</code>.</p>\n\n<blockquote>\n<pre><code>Navigate pageIndex, appIE, keyword\n</code></pre>\n</blockquote></li>\n<li><code>Sleep</code> - A common subroutine used across many programming languages. \nI see no reason to wrap it in <code>WaitSomeMilliseconds()</code>. You could even give it a default value.\n\n<blockquote>\n<pre><code>Public Declare PtrSafe Sub Sleep Lib \"kernel32\" (Optional ByVal dwMilliseconds As LongPtr = 1000)\n</code></pre>\n</blockquote></li>\n<li>I don't see any reason to use <code>Sleep</code> in the first place. I would use <code>appIE.readyState &lt;&gt; READYSTATE_COMPLETE</code> instead because the only thing that you are waiting on is the Page to load. There is no lazy loading or controls to be clicked.\n\n<blockquote>\n<pre><code>Const READYSTATE_COMPLETE = 4\nWhile appIE.readyState &lt;&gt; READYSTATE_COMPLETE\n</code></pre>\n</blockquote></li>\n<li><code>PageWithResultsExists()</code> - Probably the biggest reason for the slow code. The way the code is structured it runs until a page is called that has no data and checks that page for 10 seconds. The last link in the Paginator class name is <code>pagnDisabled</code>. You can get the last page number by checking its <code>innerText</code>.</li>\n<li><code>WriteToExcel()</code> - Why? This just adds an extra layer of complexity and slows down the code. Simply process the data in memory.</li>\n<li><code>MakeURL()</code> - I know getters are pretty boring but I would still use <code>getURL()</code>. No big deal though.</li>\n<li><code>WriteFormulas()</code> - You should write all the formulas at once after all the data is processed.</li>\n<li><p><code>GetPrice()</code> - There is no distinction made between Paperback, Hardcover or Kindle. I would expand the dataset to include all the categories; so that you are not comparing apples to oranges.</p></li>\n<li><p>Microsoft HTML Object Library - This library is very convenient when working with HTML. Since there is only one version of the library, I would take advantage of early binding and intellisense by setting a reference to it. </p></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/MU28p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MU28p.png\" alt=\"Microsoft HTML Object Library\"></a></p>\n\n<p>I only use Internet Explorer which I need to process events, I prefer <code>XMLHTTP</code>. </p>\n\n<h2>Sample Userform</h2>\n\n<p>The Userform should have a single Textbox with multiline set to true. When ran the code parses 20 pages of results asynchronously in under 12 seconds. The code is unrefined. It is just a proof of concept.</p>\n\n<pre><code>Option Explicit\nConst READYSTATE_COMPLETE = 4\n\nPrivate Sub UserForm_Initialize()\n Dim t As Double: t = Timer\n TextBox1.Text = Join(getBooks(\"VBA\").ToArray, vbNewLine)\n Debug.Print Round(Timer - t, 2)\nEnd Sub\n\nFunction getDocument(URL As String) As MSHTML.HTMLDocument\n Dim document As MSHTML.HTMLDocument\n With CreateObject(\"MSXML2.XMLHTTP\")\n 'open(bstrMethod As String, bstrUrl As String, [varAsync], [bstrUser], [bstrPassword])\n .Open bstrMethod:=\"GET\", bstrUrl:=URL, varAsync:=False\n .send\n If .readyState = READYSTATE_COMPLETE And .Status = 200 Then\n Set document = New MSHTML.HTMLDocument\n document.body.innerHTML = .responseText\n Set getDocument = document\n Else\n MsgBox \"URL: \" &amp; vbCrLf &amp; \"Ready state: \" &amp; .readyState &amp; vbCrLf &amp; \"HTTP request status: \" &amp; .Status, vbInformation, \"URL Not Responding\"\n End If\n End With\nEnd Function\n\nFunction getBooks(keyword As String) As Object\n Dim server As Object, servers As Object\n Dim document As MSHTML.HTMLDocument, documents As Object\n Set servers = CreateObject(\"System.Collections.ArrayList\")\n Set documents = CreateObject(\"System.Collections.ArrayList\")\n\n Dim URL As String\n URL = MakeUrl(1, keyword)\n\n Set document = getDocument(URL)\n\n documents.Add document\n\n Dim pageindex As Long\n For pageindex = 2 To getPageCount(document)\n URL = MakeUrl(pageindex, keyword)\n Set server = CreateObject(\"MSXML2.XMLHTTP\")\n server.Open bstrMethod:=\"GET\", bstrUrl:=URL, varAsync:=True\n server.send\n servers.Add server\n Next\n\n For Each server In servers\n While server.readyState &lt;&gt; READYSTATE_COMPLETE\n DoEvents\n Wend\n\n If server.Status = 200 Then\n Set document = New MSHTML.HTMLDocument\n document.body.innerHTML = server.responseText\n documents.Add document\n End If\n\n Next\n\n Dim books As Object\n Set books = CreateObject(\"System.Collections.ArrayList\")\n\n Dim ul As HTMLUListElement\n Dim li As HTMLLIElement\n\n For Each document In documents\n Set ul = document.getElementById(\"s-results-list-atf\")\n\n If Not ul Is Nothing Then\n For Each li In ul.getElementsByTagName(\"LI\")\n books.Add li.innerText\n Next\n End If\n Next\n\n Set getBooks = books\nEnd Function\n\nFunction getPageCount(document As HTMLDocument) As Long\n Dim element As HTMLGenericElement\n Set element = document.querySelector(\".pagnDisabled\")\n If Not element Is Nothing Then getPageCount = CInt(element.innerText)\nEnd Function\n\nPublic Function MakeUrl(i As Long, keyword As String) As String\n MakeUrl = \"https://www.amazon.com/s/ref=sr_pg_\" &amp; i &amp; \"?rh=i%3Aaps%2Ck%3A\" &amp; keyword &amp; \"&amp;page=\" &amp; i &amp; \"&amp;keywords=\" &amp; keyword\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:03:11.073", "Id": "406670", "Score": "0", "body": "Thanks for the feedback! :) The library is a good idea indeed, I was trying to make the code portable through copy and paste, thus I was not using early binding. On your code I get an error here `.Open bstrMethod:=\"GET\", bstrUrl:=URL, varAsync:=False` - \"448 - named arbugment is not found\". I call it like this - `Debug.Print Join(getBooks(\"VBA\").ToArray, vbNewLine)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:01:57.890", "Id": "406684", "Score": "0", "body": "@Vityata I got that error using a different version of the library. `CreateObject(\"MSXML2.XMLHTTP.6.0\")` gave me the error but `CreateObject(\"MSXML2.XMLHTTP\")` worked. [download amazon-scraper.xlsb](https://drive.google.com/open?id=1iLe2N7IxX7EkJ2IH-bzVfc-AGv1hajj5)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:32:22.320", "Id": "406688", "Score": "0", "body": "I have just tried the `amazon-scraper.xlsb` and still got the same error on the same place. Currently with Excel 2010, 64 bits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:34:13.797", "Id": "406689", "Score": "1", "body": "@Vityata very strange. Try removing the parameter names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:37:11.787", "Id": "406691", "Score": "0", "body": "I am impressed by your remote-debugging skills! It worked! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:01:12.463", "Id": "406972", "Score": "0", "body": "Not sure if I follow this part \"When ran the code parses 20 pages of results asynchronously in under 12 seconds\". Where/how is the code running async?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T07:05:47.713", "Id": "406990", "Score": "0", "body": "@RyanWildry Although VBA is runs synchronously it does not have to wait on the `XMLHTTP` responses. By setting the `XMLHTTP.Send `varAsync` parameter to True, you can have multiple connections running simultaneously. \n You don't have to wait for each connection to return its response before opening a new connection. My sample code is pretty crude. A better example with more dramatic results is my answer to: [Retrieve data from eBird API and create multi-level hierarchy of locations](https://codereview.stackexchange.com/a/196922/171419)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T15:52:54.050", "Id": "407011", "Score": "0", "body": "I was confused as I didn't see a callback, I guess this part: `While server.readyState <> READYSTATE_COMPLETE:DoEvents:Wend` is doing that. That's not really idiomatic IMO of async code, but, I guess it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:49:06.600", "Id": "407020", "Score": "0", "body": "@RyanWildry I agree. I could think of a better way to explain it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T18:32:11.147", "Id": "413594", "Score": "0", "body": "I think this line: Set element = document.querySelector(\".pagnDisabled\") needs tweaking. It will throw a 424 if not present (unless I am missing where it is handled - which is entirely possible). Either handle the potential error or use a test of Set element = document.querySelectorAll(\".pagnDisabled\") then test if element.length = 0 . You can also remove a loop by using querySelectorAll(\"#s-results-list-atf li\"). Used typed functions where possible and add in the ByVal/ByRefs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:09:44.790", "Id": "413604", "Score": "0", "body": "If there are no elements containing the class javascript returns null ans VBA sets the object to nothing. Testing whether or not the `element is Nothing`, which I do, should be sufficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:12:09.397", "Id": "413605", "Score": "0", "body": "I had an issue with `querySelectorAll` not being supported prior IE9 (I think??). Inserting `<meta http-equiv=\"X-UA-Compatible\" content=\"IE=IE9 />` into the response text head tag, prior to creating the HTMLFile, should fix it." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T05:11:32.180", "Id": "210404", "ParentId": "210365", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T14:37:56.863", "Id": "210365", "Score": "1", "Tags": [ "vba", "excel", "data-mining" ], "Title": "Data scraping from Internet with Excel-VBA" }
210365
<p><a href="https://www.pbinfo.ro/?pagina=probleme&amp;id=1956" rel="nofollow noreferrer">Siruri2 | www.pbinfo.ro</a></p> <blockquote> <p>Fibonacci, a famous Italian mathematician in the Mediaeval Era, had discovered a series of natural numbers with multiple applications, a string that bears his name:</p> <pre><code>Fibonacci (n) = 1, if n = 1 or n = 2 Fibonacci (n) = Fibonacci (n−1) + Fibonacci (n−2), if n&gt;2 </code></pre> <p>Fascinated by Fibonacci's line, and especially the applications of this string in nature, Iccanobif, a mathematician in the making, created a string and he named him:</p> <pre><code>Iccanobif (n) = 1, if n = 1 or n = 2 Iccanobif (n) = reversed (Iccanobif (n-1)) + reversed (Iccanobif (n-2)), if n &gt; 2 </code></pre> <p>Obtaining the following rows:</p> <pre><code>Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Iccanobif: 1, 1, 2, 3, 5, 8, 13, 39, 124, 514, 836, ... </code></pre> <p>Iccanobif now wonders which number has more natural divisors: the n-th term in the Fibonacci row or the n-th term in the Iccanobif row. Requirements:</p> <p>Write a program that reads <strong>n</strong> natural number and displays:</p> <p>a) the n-th term in Fibonacci's row and its number of divisors </p> <p>b) the n-th term of the Iccanobif string and its number of divisors</p> <p><strong>Input data</strong></p> <p>The input file <strong>siruri2.in</strong> contains on the first line a natural number p. For all input tests, the p number can only have a value of 1 or value 2. A natural number n is found on the second line of the file. </p> <p><strong>Output data</strong></p> <p>If the value of p is 1, only a) of the requirements will be solved. In this case, in the output file siruri2.out, the n-th term in Fibonacci string and its number of divisors will be written.</p> <p>If the value of p is 2, only the point b) of the requirements will be solved. In this case, in the output file siruri2.out the n-th term in Iccanobif string and its number of divisors will be written Restrictions and clarifications</p> <pre><code>1 ≤ n ≤ 50 For the correct resolution of the first requirement, 50% of the score is awarded, and 50% of the score is awarded for the second requirement. </code></pre> <p>Limits: - time: 1 second; - memory: 2 MB/ 2 MB.</p> <p><strong><em>Example 1</em></strong></p> <p><strong>siruri2.in</strong></p> <p>1 8</p> <p><strong>siruri2.out</strong></p> <p>21 4</p> <p><strong><em>Example 2</em></strong></p> <p><strong>siruri2.in</strong></p> <p>2 9</p> <p><strong>siruri2.out</strong></p> <p>124 6</p> <p><strong><em>Explanations</em></strong></p> <p>For the first example: The eighth term in Fibonacci's string is 21 and 21 has 4 divisors. (p being 1 solves only requirement a)</p> <p>For the second example: The ninth term in Iccanobif's string is 124, and 124 has six divisors. (p being 2 solves only requirement b)</p> </blockquote> <p>Here is my code, which doesn't execute all given tests in time (exceeds time limit for 3 tests):</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; ifstream in("siruri2.in"); ofstream out("siruri2.out"); void numOfDivisors (long long n) { long numOfDivisors = 1, factor = 2; while (factor * factor &lt;= n) { if (!(n % factor)) { long exponent = 0; while (!(n % factor)) { n /= factor; exponent ++; } numOfDivisors *= exponent + 1; } if (factor == 2) factor = 3; else factor += 2; } if (n &gt; 1) { numOfDivisors *= 2; } out &lt;&lt; numOfDivisors; } long long inverted (long long a) { long long b=0; while (a) { b = b * 10 + a % 10; a /= 10; } return b; } void fibonacci (short ord) { long long a = 1, b = 1; if (ord &lt; 3) {out &lt;&lt; "1 1";} else { ord -= 2; while (ord) { a+=b; ord--; if (!ord) { out &lt;&lt; a &lt;&lt; " "; numOfDivisors(a); break; } else { b+=a; ord--; if (!ord) { out &lt;&lt; b &lt;&lt; " "; numOfDivisors(b); } } } } } void iccanobif (short ord) { long long a = 1, b = 1; if (ord &lt; 3) out &lt;&lt; "1 1"; else { ord -= 2; while (ord) { a = inverted(a) + inverted(b); ord--; if (!ord) { out &lt;&lt; a &lt;&lt; " "; numOfDivisors(a); break; } else { b = inverted(a) + inverted(b); ord--; if (!ord) { out &lt;&lt; b &lt;&lt; " "; numOfDivisors(b); } } } } } int main() { short requirement, ord; in &gt;&gt; requirement &gt;&gt; ord; if (requirement == 1) fibonacci(ord); else iccanobif(ord); } </code></pre>
[]
[ { "body": "<h1>Efficiency</h1>\n\n<h2><code>numOfDivisors()</code></h2>\n\n<ul>\n<li><p><code>numOfDivisors</code> and <code>exponent</code> do not need to be <code>long</code>. Using <code>int</code> is sufficient, and should be slightly faster.</p></li>\n<li><p><code>n</code> is a <code>long long</code>, where as <code>factor</code> is only a <code>long</code>. So <code>factor</code> will be repeated promoted to a <code>long long</code> for the operations <code>n % factor</code> and <code>n /= factor</code>. You might find a speed improvement by actually declaring <code>factor</code> as a <code>long long</code> to avoid the repeated type promotion.</p></li>\n<li><p><code>factor</code> is only a <code>long</code>, so <code>factor * factor</code> is also only a <code>long</code>, and may overflow when looping <code>while (factor * factor &lt;= n)</code>. Using a <code>long long</code> will avoid this, which may prevent the loop from running for <em>a long time</em> if <code>n</code> is prime and larger than a <code>long</code>.</p></li>\n<li><p>If <code>n % factor == 0</code>, then the exponent counting inner loop is entered, and the first thing that is done is <code>n % factor</code>, which is already known to be zero. Using a <code>do { ... } while (!(n % factor));</code> loop will prevent the redundant calculation.</p></li>\n<li><p>The outer loop starts at <code>n=2</code>, and has an <code>if</code> statement to choose between incrementing <code>n</code> by <code>2</code>, or setting it to <code>3</code>. If <code>2</code> was handled as a special case, then the loop could unconditionally increment by <code>2</code>, eliminating the <code>if</code> statement for another speed gain. To handle the <code>2^exponent</code> case, simply count the number of trailing zeros in the binary representation of <code>n</code>.</p></li>\n<li><p>Your factor finder is testing all odd numbers whose square is less than <code>n</code>. You only need to test <code>factor</code> numbers which are prime. Other than 2 &amp; 3, all prime numbers can be generated from <code>6k-1</code> and <code>6k+1</code>. Or maybe use a prime sieve ... you are allowed 2MB of memory ...</p></li>\n</ul>\n\n<h2><code>iccanobif()</code></h2>\n\n<p>You are computing...</p>\n\n<pre><code>while (...) {\n a = inverted(a) + inverted(b); // #1\n ...\n b = inverted(a) + inverted(b); // #2\n}\n</code></pre>\n\n<p>When you are executing statement #2, you've already computed <code>inverted(b)</code> during statement #1, above. If you cached that value, you wouldn't need to invert it a second time.</p>\n\n<p>Similarly, when computing statement #1 in subsequent loops, you've already computed <code>inverted(a)</code> during statement #2, below, on the previous iteration. If you cached that value, you wouldn't need to invert it a second time.</p>\n\n<h1>General</h1>\n\n<p>Add vertical white space after <code>#include</code>s, after global variables, and between functions.</p>\n\n<p>Add whitespace around operators. Ie, <code>a += b;</code> instead of <code>a+=b;</code>.</p>\n\n<p>Don't use <code>using namespace std;</code>. Simply use:</p>\n\n<pre><code>std::ifstream in(\"...\");\nstd::ofstream out(\"...\");\n</code></pre>\n\n<p><code>numOfDivisors()</code> should return the answer, not print the answer.</p>\n\n<p><code>fibonacci()</code> should return the Fibonacci value, not print the value and call another function which also has the side-effect of additional printing. Ditto for <code>iccanobif()</code>.</p>\n\n<p><code>main()</code> is declare to return an <code>int</code>, but doesn't return anything.</p>\n\n<p>If the above changes were made, then <code>in</code> and <code>out</code> don't need to be global variables; they could be made local to the <code>main</code> function:</p>\n\n<pre><code>void main() {\n std::ifstream(\"siruri2.in\");\n std::ofstream(\"siruri2.out\");\n\n short requirement, ord;\n in &gt;&gt; requirement &gt;&gt; ord;\n\n long long n = requirement == 1 ? fibonacci(ord) : iccanobif(ord);\n\n int num_divisors = numOfDivisors(n);\n\n out &lt;&lt; n &lt;&lt; ' ' &lt;&lt; num_divisors;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:59:42.550", "Id": "406843", "Score": "0", "body": "*You only need to test factor numbers which are prime.* Are you sure? I don't see six prime divisors in 124" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:49:57.683", "Id": "406845", "Score": "0", "body": "`int` is NOT necessarily faster than `long`. On all the major compilers for x86, which we're going to assume is used as nothing else was stated, `sizeof(int)==sizeof(long)`. `int` is guaranteed to be at least 16 bits but in practice is almost always 32 bits on machines with a 32 bit native word size while long is guaranteed to be at least 32 bits and most often is, even on 64 bit machines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:52:24.060", "Id": "406912", "Score": "0", "body": "@papagaga You are correct, 124 doesn’t have 6 prime divisors; it has two: 2 & 31. And if you look at `numOfDivisors()`, you’d see it determines 124 = 2^2 * 31^1, takes the exponents 2 & 1, adds one to each, and multiplies them all together: (2+1)*(1+1) = 6. So yes, I’m sure you only need to test factor numbers which are prime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T08:57:25.457", "Id": "406998", "Score": "0", "body": "It's not prime divisors that I care about, it's all of the divisors. AJNeufield is right, but this is much easier to implement that what he suggested. Also, the program will find all my divisors just fine: 4 won't go through, because my number was already divided by 2 until it couldn't be divided anymore. This part of my code isn't the problematic one, but I will try all of your suggestions, as I'm still a learner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:06:53.390", "Id": "407012", "Score": "1", "body": "Your problematic code is an infinite loop. But since this is the Code Review site, where working code gets reviewed, I gave you a review of all of the code. With only 50 numbers to test, and under one second per number, you could write a loop to test each number (instead of reading from a file), and identify which input is the problematic number is under 1 minute. Then, examine what happens with the problematic number. Then, re-read my review, taking extra care when I talk about that area of the code. I mention both the problem and solution. Or ask a debug help question on StackOverflow." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T01:01:27.550", "Id": "210392", "ParentId": "210376", "Score": "1" } }, { "body": "<h1><code>constexpr</code> is your friend</h1>\n<p>You may feel like it's cheating, but C++ allows you to pre-compute the answers really easily with the <code>constexpr</code> keyword. A <code>constexpr</code> value must be known at compile-time, and a <code>constexpr</code> function, given a <code>constexpr</code> argument, will be executed at compile-time. It means that you can easily compute and store the 50 first terms of the fibonacci progression -and of the iccanobif progression for that matter- at compile-time. And you can of course calculate how many divisors they have. The beauty of it is that you don't need the most efficient algorithms: since all the work is done once and for all during compilation, being more readable and maintainable could very well be the right choice.</p>\n<p>Here's a quickly-written <code>constexpr</code> answer to your problem: <a href=\"https://wandbox.org/permlink/qAtXS15Ir9c4vYgG\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/qAtXS15Ir9c4vYgG</a></p>\n<h1>avoid duplicating code</h1>\n<p>Copy-and-paste is an <em>anti-pattern</em> because it is hard to maintain: if you find an improvement in your <code>fibonacci</code> function, you'll need to replicate it in the <code>iccanobif</code> function; at some point, you'll forget to copy, or to modify your copy. That's why you should try to factorize your code. In this case, both functions share most of their code; the only thing <code>iccanobif</code> does in addition is to reverse the previous terms. So you can rewrite both functions into one that decides whether to reverse the previous terms according to a function parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:57:51.800", "Id": "406846", "Score": "0", "body": "Clever with the constexpr but they didn't give any limit on `n` so I find it hard to recommend it because of that. As choosing the right number to pre-compute is hard in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:46:14.697", "Id": "406856", "Score": "0", "body": "@EmilyL. *Restrictions and clarifications: 1 ≤ n ≤ 50*... so please do recommend :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:52:15.377", "Id": "406857", "Score": "0", "body": "Oh I didn't see that due to the formatting, nvm then :) Still it's kinda cheating and defeating the purpose of the exercise ;p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:20:30.973", "Id": "406914", "Score": "0", "body": "It is also, however, quite wrong: 1836311903 + 2971215073 != 512559680 as just one example." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:19:43.333", "Id": "210476", "ParentId": "210376", "Score": "1" } } ]
{ "AcceptedAnswerId": "210392", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T17:50:27.573", "Id": "210376", "Score": "2", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded", "fibonacci-sequence" ], "Title": "Write in file the n-th term in iccanobiF series" }
210376
<p>I work on a small data team where we developed this tool when we began experiencing several job failures on our legacy big data systems. We have several data lakes, each with their own API, and until now had no contingencies for issues centering around query failures. Furthermore, our database sockets had no central repository for accessing our data. This tool brings all query platforms together in a (relatively) seamless experience by way of formulating a socket library and offers redundancy protocols when queries fail. This software is compatible with any SQL-similar interface that has an established Pythonic API, such as Impala, Hive, AWS, and terminal/command-line returns.</p> <p>The usage is very straightforward:</p> <pre><code># Upon instantiation: # &gt; mquery() imports all sockets and aliases via the factory # &gt; Default attempts on any socket is 8 # &gt; Default socket is the first socket in the library # &gt; Default precedence is all sockets of the same type as the default socket # &gt; Default for fail_on_empty and fail_on_zero are both False # Functional a = mquery_lite().query(r"SELECT 'test;") # Returns the result set only; object instance is destructed on next mquery_lite() call print(str(a.get_result())) # Functional with overrides a = mquery_lite().query(r"SELECT 'test;", query_attempts=2, fail_on_zero=True) # Returns the result set only, overriding the default query_attempts and fail_on_zero values print(str(a.get_result())) # Object Oriented with Overrides a = mquery_lite(socket_precedence=["pd","data"]) # Precedence is set to both the pandas and all data sockets a.query_attempts = 4 a.query(r"SELECT 'test';", query_attempts=2, socket_precedence=["pd"]) # Overrides on query submission # query_attempts returns to 4 and socket_precedence returns to ["pd","data"] print(str(a.get_result())) # Object Oriented with Overrides and Handshake a = mquery_lite(socket_precedence=["all","data"], query_attempts=4) # Precedence list will be the list of all sockets plus the additional list of all data sockets; there will be duplicates in the precedence list (not problematic) a.handshake() # Test each socket in the current precedence list; retain only those that pass. Duplicates will persist. a.query(r"SELECT 'test';", query_attempts=2) # query_attempts returns to 4 print(str(a.get_result())) </code></pre> <p>Naturally, all proprietary information has been redacted from this post. I've also stripped most of the bells and whistles (e.g. typecasting property decorators) to demonstrate basic functionality and proof of concept in the code below; all pieces of this code can readily be found from open sources on the internet, but I haven't seen them tied together in this manner.</p> <p>The <code>mquery_lite()</code> object is the primary process of this code and can either be used functionally or instanced as an object. When called, <code>mquery_lite()</code> determines if a query was provided - if so, it will instance itself, perform the query, then return the result pointer from the successful socket. If a query is not passed, <code>mquery_lite()</code> remains instanced and user-modified settings are retained.</p> <p>Sockets are imported by way of a generator-encapsulated factory. Their aliases are mapped in a separate library for ease of use when calling sockets. Sockets are separated by type, defined in the socket itself (we prefer to group by the expected output of the socket as this ensures consistent output on query failure; e.g. data frame, list of lists, generator, etc.). Sockets retain the query results until a new query is submitted.</p> <p>The socket and alias libraries are automatically built on instantiation, based on the order in which they are present in the script. Collisions are rectified on a first-come-first-serve basis. The following object variables are created on instantiation:</p> <ul> <li><code>query_attempts</code> (default 8) is the number of attempts <code>mquery_lite()</code> will make on a socket before moving to the next socket. An exponential timer (2^n) sets the pause between repeat queries on a socket.</li> <li><code>socket_default</code> (default <code>None</code>) is the socket that will be substituted in the precedence list when an unknown alias is provided. Will default to the first socket in the library if <code>None</code> is detected.</li> <li><code>socket_precedence</code> (default <code>[]</code>) is the order in which sockets will be attempted. Will default to all sockets of the same type as the default socket in the library if <code>None</code> is detected.</li> <li><code>fail_on_empty</code> (default <code>False</code>) indicates if a query should raise an exception if it comes back empty (useful for command queries).</li> <li><code>fail_on_zero</code> (default <code>False</code>) indicates if a query should raise an exception if it comes back zero (useful for counts).</li> </ul> <p>Results remain and failures occur at the socket level. Handling of permitted errors (raised from sockets) occurs in the <code>.query()</code> method.</p> <pre><code>import pandas import pyodbc import time def peek(x): try: return next(x) except StopIteration: return None ############################################################################### ### Dynamic Polymorphic Socket Factory ######################################## ############################################################################### class PermittedSocketError(Exception): """ A socket error that should trigger a retry, but not a program termination. """ pass class socket: DSN = "DSN=Your.DSN.Info.Here;" # Used in pyodbc and pandas sockets def handshake(self, query="SELECT 'test';"): self.execute(query, fail_on_empty=False, fail_on_zero=False) # Dynamic socket factory # https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html class factory: objects = {} def add_factory(id, factory): factory.factories.put[id] = factory add_factory = staticmethod(add_factory) def create_object(id): if id not in factory.objects: # updated for Python 3 factory.objects[id] = eval(id + ".factory()") return factory.objects[id].create() create_object = staticmethod(create_object) ############################################################################### ### Socket Library ############################################################ ############################################################################### class generic_socket(socket): socket_aliases = ["alias_1", "alias_2"] socket_type = "type" @property def result(self): # Any type of return handling can go here (such as a generator to improve post-parsing) return self.__data_block def execute(self, query, fail_on_empty, fail_on_zero): # Set up for query self.__data_block = None try: # Execute query # Internal post query handling of error codes should raise exceptions here - useful for non-Pythonic (e.g. command-line) returns # Likely not needed if using processes with full Pythonic exception handling if /*Permitted Error Behavior*/: raise PermittedSocketError("[msg] ") else: raise if fail_on_empty and /*Check if Empty*/: raise PermittedSocketError("Empty return detected.") if fail_on_zero and /*Check if Zero*/: raise PermittedSocketError("Zero return detected.") # Edit: The if-else statements above were note syntactically valid and should be changed to: # if fail_on_empty and /*Check if Empty*/: # raise PermittedSocketError("Empty return detected.") # if fail_on_zero and /*Check if Zero*/: # raise PermittedSocketError("Zero return detected.") # if /*Permitted Error Behavior*/: # raise PermittedSocketError("[msg] ") # if /*Non-Permitted Error Behavior*/: # raise Exception # Exterior post query handling of permitted socket errors - Pythonic exceptions should be caught here except PermittedSocketError: # Permitted error post-process, such as reinitializing security protocols or invalidating metadata # Permitted errors are re-raised and handled within mquery_lite() raise class factory: def create(self): return generic_socket() class pandas_socket(socket): socket_aliases = ["pandas","pd"] socket_type = "data" @property def result(self): return self.data_block def execute(self, query, fail_on_empty, fail_on_zero): self.data_block = None try: connection = pyodbc.connect(self.DSN, autocommit=True) self.data_block = pandas.read_sql(query, connection) connection.close() if fail_on_empty and self.data_block.dropna().empty: raise PermittedSocketError("Empty return detected.") if fail_on_zero and self.data_block.shape == (1,1) and int(float(self.data_block.iloc[0,0])) == 0: raise PermittedSocketError("Zero return detected.") except PermittedSocketError: raise class factory: def create(self): return pandas_socket() class pyodbc_socket(socket): socket_aliases = ["pyodbc"] socket_type = "standard" @property def result(self): return self.data_block def execute(self, query, fail_on_empty, fail_on_zero): self.data_block = None try: connection = pyodbc.connect(self.DSN, autocommit=True) cursor = connection.cursor() cursor.execute(query) self.data_block = cursor.fetchall() cursor.close() connection.close() row = peek(iter(self.data_block)) if fail_on_empty and not row: raise PermittedSocketError("Empty return detected.") if fail_on_zero and len(row) == 1 and peek(iter(row)) in (0, "0"): raise PermittedSocketError("Zero return detected.") except pyodbc.ProgrammingError: # Thrown when .fetchall() returns nothing self.__data_block = [()] raise PermittedSocketError("Empty return detected.") except PermittedSocketError: raise class factory: def create(self): return pyodbc_socket() ############################################################################### ### mquery_lite() ############################################################# ############################################################################### class mquery_lite(object): def __new__(cls, query=None, query_attempts=8, socket_default=None, socket_precedence=[], fail_on_empty=False, fail_on_zero=False): # https://howto.lintel.in/python-__new__-magic-method-explained/ if query is not None: mquery_instance = super(mquery_lite, cls).__new__(cls) mquery_instance.__init__(query_attempts, socket_default, socket_precedence, fail_on_empty, fail_on_zero) mquery_instance.query(query) return mquery_instance.get_results() else: return super(mquery_lite, cls).__new__(cls) ### CTOR def __init__(self, query_attempts=8, socket_default=None, socket_precedence=[], fail_on_empty=False, fail_on_zero=False): ### Socket Library self.socket_library = {socket.__name__:factory.create_object(socket.__name__) for socket in socket.__subclasses__()} self.socket_aliases = ({socket:[socket] for socket in self.socket_library}) self.socket_aliases.update({alias:[socket] for socket in self.socket_library for alias in self.socket_library[socket].socket_aliases if alias not in self.socket_aliases}) self.socket_aliases.update({socket_type:[socket for socket in self.socket_library if self.socket_library[socket].socket_type == socket_type] for socket_type in {self.socket_library[unique_socket_type].socket_type for unique_socket_type in self.socket_library}}) self.socket_aliases.update({"all":[socket for socket in self.socket_library]}) self.query_attempts:int = query_attempts self.socket_default:str = socket_default if socket_default is None: self.socket_default = next(iter(self.socket_library)) self.socket_precedence = socket_precedence if socket_precedence == []: self.socket_precedence:list = self.socket_aliases[self.socket_library[self.socket_default].socket_type] self.fail_on_empty:bool = fail_on_empty self.fail_on_zero:bool = fail_on_empty def handshake(self): precedence_candidates = [] for alias in self.socket_precedence: for socket in self.socket_aliases[alias]: try: self.socket_library[socket].handshake() precedence_candidates.append(socket) except PermittedSocketError: continue if len(precedence_candidates) != 0: self.socket_precedence = precedence_candidates def get_results(self): return self.result_socket.result ### Query Execution def query(self, query, query_attempts=None, socket_precedence=[], fail_on_empty=None, fail_on_zero=None): # Overrides if query_attempts is None: query_attempts = self.query_attempts if socket_precedence==[]: for i in self.socket_precedence: for j in self.socket_aliases[i]: if j in self.socket_library: socket_precedence.append(j) else: socket_precedence.append(self.default_socket) else: candidate_precedence = socket_precedence[:] socket_precedence = [] for i in candidate_precedence: for j in self.socket_aliases[i]: if j in self.socket_library: socket_precedence.append(j) else: socket_precedence.append(self.default_socket) if fail_on_empty is None: fail_on_empty = self.fail_on_empty if fail_on_zero is None: fail_on_empty = self.fail_on_zero # Loop through socket precedence list for socket in socket_precedence: try: # Loop through socket attempts on current socket for attempt_n in range(query_attempts): try: # Exponential timer; pauses 2^n seconds on the current socket if attempt_n &gt; 0: print("Waiting " + str(2**attempt_n) + " seconds before reattempting...") for k in range(2**attempt_n): time.sleep(1) # Query attempt self.socket_library[socket].execute(query, fail_on_empty, fail_on_zero) self.result_socket = self.socket_library[socket] return except PermittedSocketError: print("mquery() failed on socket \"" + str(socket) + "\".") if attempt_n+1 == query_attempts: raise pass except PermittedSocketError: if socket == socket_precedence[-1]: print("mquery() failed after trying all attempts on all sockets.") raise print("mquery() failed after all attempts on socket \"" + str(socket) + "\"; moving to next socket.") continue </code></pre> <p>Questions are mostly along the lines of: We've tried to make this as "Pythonic" as possible - have we missed anything? Are there libraries that already perform this in a more efficient manner?</p>
[]
[ { "body": "<p>By PEP8, your classes <code>sockets</code>, <code>factory</code>, etc. should be capitalized. You also need newlines between your class methods. These can all be fixed fairly easily with the use of a stand-alone or IDE-builtin linter.</p>\n\n<p>This comment:</p>\n\n<pre><code># Dynamic socket factory\n# https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html\n</code></pre>\n\n<p>should be moved to a docstring on the inside of the class:</p>\n\n<pre><code>class Factory:\n \"\"\"Dynamic socket factory\n https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html\n \"\"\"\n</code></pre>\n\n<p>So far as I can tell, <code>socket</code> is an abstract base class. You can pull in <code>abc</code> if you want to, but at the very least, you should explicitly show <code>execute</code> as being a \"pure virtual\" (in C++ parlance) method:</p>\n\n<pre><code>def execute(self, query, fail_on_empty, fail_on_zero):\n raise NotImplementedError()\n</code></pre>\n\n<p>This code:</p>\n\n<pre><code> if /*Permitted Error Behavior*/:\n raise PermittedSocketError(\"[msg] \")\n else:\n raise\n</code></pre>\n\n<p>can lose the <code>else</code>, because the previous block has already <code>raise</code>d.</p>\n\n<p>I'm not sure what's happened here - whether it's a redaction, or what - but it doesn't look syntactically valid:</p>\n\n<pre><code> if fail_on_empty and /*Check if Empty*/:\n raise PermittedSocketError(\"Empty return detected.\")\n if fail_on_zero and /*Check if Zero*/:\n raise PermittedSocketError(\"Zero return detected.\")\n</code></pre>\n\n<p>Your <code>except PermittedSocketError:</code> and its accompanying comment <code>Permitted errors are re-raised</code> are a little odd. If the error is permitted, and you're doing nothing but re-raising, why have the <code>try</code> block in the first place?</p>\n\n<p>This:</p>\n\n<pre><code> else:\n return super(mquery_lite, cls).__new__(cls)\n</code></pre>\n\n<p>doesn't need an <code>else</code>, for the same reason as that <code>raise</code> I've described above.</p>\n\n<p>The series of list comprehensions seen after <code>### Socket Library</code> really needs to have most or all of those broken up onto multiple lines, especially when you have multiple <code>for</code>.</p>\n\n<p><code>self.socket_library</code> is a dictionary, but I'm unclear on your usage. You have this:</p>\n\n<pre><code> if j in self.socket_library:\n socket_precedence.append(j)\n else:\n socket_precedence.append(self.default_socket)\n</code></pre>\n\n<p>Is your intention to look through the keys of <code>socket_library</code>, ignore the values, and add present keys to <code>socket_precedence</code>? If you want to use its values, this needs to change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:50:17.820", "Id": "407021", "Score": "0", "body": "Thanks for the response @Reinderien. I'm unsure about post etiquette here, but this is likely going to be a couple of comments. Regarding PEP 8: done - implementing in the next version. Docstrings: the original code is docstring'd to the nines; it defo got a little messy when we truncated the code. Both if-else blocks you mentioned were indeed victims of redaction; I've added a comment block in the code above to show the correct syntax as I didn't want to change the original post. Awesome info regarding the __new__() function as well - I didn't know it could just be left alone." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:50:46.790", "Id": "407022", "Score": "0", "body": "To answer your question regarding ```PermittedSocketError``` and re-raising: There are some cases when certain code is useful immediately after a permitted query failure (e.g. REFRESH statement in Impala or Kerberos re-authentication). Otherwise, yes, the try block within the sockets serve little purpose and should just be raised back into mquery_lite() for handling. Regarding ```socket_precedence```: Indeed, the intention was to capture the keys of the sockets only so that the precedence list can be examined later if needed; otherwise you just get a list of pointers to the sockets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:51:07.503", "Id": "407023", "Score": "0", "body": "The one element of your response I'm struggling on is the \"pure virtual\" reference. Does this get defined outside the socket classes just to raise ```NotImplementedError``` when someone tries to execute without a socket reference? Thanks again for the thorough review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:58:39.110", "Id": "407025", "Score": "1", "body": "You define it in the parent, raising `NotImplementedError`, and in children, where it does not raise. This does a few things - makes it obvious that it's expected to be implemented in children; and acts as a more explicit failure if you accidentally call it without having defined it in a child." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:21:18.730", "Id": "210511", "ParentId": "210377", "Score": "3" } } ]
{ "AcceptedAnswerId": "210511", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T17:51:16.210", "Id": "210377", "Score": "6", "Tags": [ "python", "object-oriented", "python-3.x", "sql", "database" ], "Title": "Polymorphic Data Socket Factory with Query Contingency Protocols in Python" }
210377
<p>What improvements can I make? Should I organize my functions based on A-Z? For example, <strong>f</strong>ind_letter function comes before <strong>g</strong>uessing function. </p> <pre><code>import json import random import re def find_letter(user_input, vocab, i=None): return [i.start() for i in re.finditer(user_input, vocab)] def guessing(tries,vocab,blank_line): while tries &gt; 0: user_input = input("Guess:") if user_input in vocab: if not(user_input in blank_line): index = find_letter(user_input=user_input,vocab=vocab) i = 0 while i &lt; len(index): blank_line[index[i]] = user_input i += 1 if not('_' in blank_line): return "you won!!!" else: print("YOU ALREADY TRIED THAT LETTER!") else: tries -= 1 print(str(blank_line) + " Number of Tries : " + str(tries)) return "you lost" def hangman_game(vocab): 'Preliminary Conditions' print(introductory(vocab=vocab)) tries = num_of_tries(vocab=vocab) blank_line = produce_blank_lines(vocab=vocab) print(blank_line) print(guessing(tries=tries,vocab=vocab,blank_line=blank_line)) def introductory(vocab): return "HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. " \ "WORD COUNT : " + str(len(vocab)) def num_of_tries(vocab): if len(vocab) &lt; 7: return 8 elif 7 &lt;= len(vocab) &lt; 10: return 10 else: return 14 def produce_blank_lines(vocab): blank_line = [] for i in vocab: if i.isalpha(): blank_line += "_" elif i == " ": blank_line += " " else: blank_line += i + " " return blank_line if __name__ == '__main__': data = json.load(open("vocabulary.json")) vocab = random.choice(list(data.keys())).lower() print(vocab) print(hangman_game(vocab=vocab)) </code></pre> <p>Snippet of the JSON File</p> <pre><code>{"abandoned industrial site": ["Site that cannot be used for any purpose, being contaminated by pollutants."], "abandoned vehicle": ["A vehicle that has been discarded in the environment, urban or otherwise, often found wrecked, destroyed, damaged or with a major component part stolen or missing."], "abiotic factor": ["Physical, chemical and other non-living environmental factor."], "access road": ["Any street or narrow stretch of paved surface that leads to a specific destination, such as a main highway."], "access to the sea": ["The ability to bring goods to and from a port that is able to harbor sea faring vessels."], "accident": ["An unexpected, unfortunate mishap, failure or loss with the potential for harming human life, property or the environment.", "An event that happens suddenly or by chance without an apparent cause."], "accumulator": ["A rechargeable device for storing electrical energy in the form of chemical energy, consisting of one or more separate secondary cells.\\n(Source: CED)"], "acidification": ["Addition of an acid to a solution until the pH falls below 7."], "acidity": ["The state of being acid that is of being capable of transferring a hydrogen ion in solution."], "acidity degree": ["The amount of acid present in a solution, often expressed in terms of pH."], "acid rain": ["Rain having a pH less than 5.6."] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T23:54:19.470", "Id": "406627", "Score": "5", "body": "@ close-voter: Answers on this site are *always* \"opinion-based.\" I don't even know why that's a close-vote reason. Anyway, this question is fine. Also to answer the OP's one explicit question: Almost certainly you should *not* arrange these six functions in a-z order. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T00:17:51.313", "Id": "406630", "Score": "3", "body": "Please include an example (even tiny no problem) json file for easier testing. (The question is fine upvote from me)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:32:19.683", "Id": "406638", "Score": "0", "body": "@Quuxplusone How do programmers organize functions then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:35:37.567", "Id": "406640", "Score": "0", "body": "@Caridorc Sure. I added a snippet of the JSON file because the JSON file I downloaded is too big." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:43:25.117", "Id": "406642", "Score": "2", "body": "@austingae _How do programmers organize functions then?_ Typically by topic, and fine-grained enough that the order doesn't matter. For example you might put everything related to Hangman in `hangman.py`; or once that gets too big, you'd put everything related to the user interface in `hangman-ui.py` and everything related to core gameplay in `hangman-core.py`; or once that gets too big, you'd split out `hangman-dictionary.py` into its own file... And then sure, I'd probably sort those _files_ alphabetically in my manifest or Makefile or whatever." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:50:07.823", "Id": "406643", "Score": "2", "body": "It occurs to me that sorting functions by name has the [dictionary problem](https://www.quora.com/How-do-you-look-for-a-word-in-the-dictionary-if-you-dont-know-how-its-spelled): I can't find the function (say, `introductory()`) unless I already know how to spell it! And if I know how to spell it (say, my IDE has a sidebar index of all the functions in the current file) then I likely don't care where in the file it is (since I can jump there using my IDE). But everyone has an \"IDE\" for the filesystem (`ls`), and the filenames themselves make a rough \"index by topic\" — dictionary problem solved!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T05:35:41.573", "Id": "406651", "Score": "0", "body": "I see...organize by similarities." } ]
[ { "body": "<pre><code>data = json.load(open(\"vocabulary.json\"))\n</code></pre>\n\n<p>Unless Python 3 has changed this, I think you're leaking the open file handle here. What you want is more like</p>\n\n<pre><code>with open(\"vocabulary.json\") as f:\n data = json.load(f)\n</code></pre>\n\n<p>which IMHO is even a bit easier to read because it breaks up the mass of nested parentheses.</p>\n\n<pre><code>vocab = random.choice(list(data.keys())).lower()\n</code></pre>\n\n<p>Same deal with the nested parentheses here. We can save one pair by eliminating the unnecessary materialization into a <code>list</code>. [EDIT: Graipher points out that my suggestion works only in Python 2. Oops!]</p>\n\n<p>Also, <code>vocab</code> (short for <em>vocabulary</em>, a set of words) isn't really what this variable represents. <code>data.keys()</code> is our <em>vocabulary</em>; what we're computing on this particular line is a single <em>vocabulary word</em>. So:</p>\n\n<pre><code>word = random.choice(data.keys()).lower()\nprint(word)\nprint(hangman_game(word))\n</code></pre>\n\n<p>I can tell you're using Python 3 because of the ugly parentheses on these <code>print</code>s. ;) But what's this? Function <code>hangman_game</code> doesn't contain any <code>return</code> statements! So it basically returns <code>None</code>. Why would we want to print <code>None</code> to the screen? We shouldn't be <em>printing</em> the result of <code>hangman_game</code>; we should just call it and discard the <code>None</code> result.</p>\n\n<pre><code>word = random.choice(data.keys()).lower()\nprint(word)\nhangman_game(word)\n</code></pre>\n\n<hr>\n\n<pre><code>def hangman_game(vocab):\n</code></pre>\n\n<p>Same comment about <code>vocab</code> versus <code>word</code> here.</p>\n\n<pre><code>'Preliminary Conditions'\n</code></pre>\n\n<p>This looks like you maybe forgot a <code>print</code>? Or maybe you're trying to make a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a>? But single quotes don't make a docstring AFAIK, and even if they did, \"Preliminary Conditions\" is not a useful comment. I'd just delete this useless line.</p>\n\n<pre><code>print(introductory(vocab=vocab))\n</code></pre>\n\n<p>In all of these function calls, you don't need to write the argument's name twice. It's a very common convention that if you're calling a function with only one argument, the argument you pass it is precisely the argument it needs. ;) Also, even if the function takes multiple parameters, the reader will generally expect that you pass it the right number of arguments <em>in the right order</em>. You don't have to keyword-argument-ize each one of them unless you're doing something tricky that needs calling out. So:</p>\n\n<pre><code>print(introductory(word))\n</code></pre>\n\n<p>And then you can inline <code>introductory</code> since it's only ever used in this one place and it's a one-liner already:</p>\n\n<pre><code>print(\n \"HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. \"\n \"WORD COUNT : \" + str(len(vocab))\n)\n</code></pre>\n\n<p>Personally, I would avoid stringifying and string-concatenation in Python, and write simply</p>\n\n<pre><code>print(\n \"HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. \"\n \"WORD COUNT : %d\" % len(vocab)\n)\n</code></pre>\n\n<p>I know plenty of working programmers who would write</p>\n\n<pre><code>print(\n \"HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. \"\n \"WORD COUNT : {}\".format(len(vocab))\n)\n</code></pre>\n\n<p>instead. (I find that version needlessly verbose, but it's definitely a popular alternative.)</p>\n\n<pre><code>tries = num_of_tries(vocab=vocab)\nblank_line = produce_blank_lines(vocab=vocab)\nprint(blank_line)\nprint(guessing(tries=tries,vocab=vocab,blank_line=blank_line))\n</code></pre>\n\n<p>It's odd that you abbreviated <code>number_of_tries</code> to <code>num_...</code>, but then left in the word <code>of</code>. I would expect either <code>number_of_tries</code> or <code>num_tries</code> (or <code>ntries</code> for the C programmers in the audience); <code>num_of_tries</code> is in a weird no-man's-land.</p>\n\n<p>It's weird that you have a function named <code>produce_blank_lines</code> that produces actually a <em>single</em> <code>blank_line</code>. It's even weirder that the value of <code>blank_line</code> is not a constant <code>\"\\n\"</code>! This suggests that everything here is misnamed. You probably meant <code>underscores = produce_underscores(word)</code> or even <code>blanks = shape_of(word)</code>.</p>\n\n<p>Finally, it is weird that <code>blank_line</code> is not even a string, but rather a <code>list</code> of characters.</p>\n\n<p>I would replace this entire dance with something like</p>\n\n<pre><code>blanks = ''.join('_' if c.isalpha() else ch for ch in word)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>blanks = re.sub('[A-Za-z]', '_', word)\n</code></pre>\n\n<p>This would lose your addition of a blank space after each non-space-non-alpha character, but IMHO that's actually an <em>improvement</em> over your version. (Your sample JSON doesn't show any examples of words containing non-space-non-alpha characters. My version certainly performs better for words like <code>non-space</code> or <code>Route 66</code>.)</p>\n\n<hr>\n\n<pre><code>if not(user_input in blank_line):\n</code></pre>\n\n<p>This would be idiomatically expressed (both in Python and in English) as</p>\n\n<pre><code>if user_input not in blank_line:\n</code></pre>\n\n<hr>\n\n<pre><code>index = find_letter(user_input=user_input,vocab=vocab)\ni = 0\nwhile i &lt; len(index):\n blank_line[index[i]] = user_input\n i += 1\n</code></pre>\n\n<p>You have another singular/plural problem here (just like with <code>blank_line[s]</code>). It doesn't make sense to get the <code>len</code> of a singular <code>index</code>. Since the variable actually represents a list of indices, we should <em>name</em> it <code>[list_of_]indices</code>.</p>\n\n<p>Also, this style of for-loop is very un-Pythonic. In Python we can say simply</p>\n\n<pre><code>for i in find_letter(user_input, word):\n blank_line[i] = user_input\n</code></pre>\n\n<p>And then we can inline the single-use <code>find_letter</code>:</p>\n\n<pre><code>for m in re.finditer(user_input, word):\n blank_line[m.start()] = user_input\n</code></pre>\n\n<p>(Using <code>m</code> as the conventional name for a match object.)\nAnd then we can eliminate the regex and just loop over the <code>word</code> directly:</p>\n\n<pre><code>for i, ch in enumerate(word):\n if ch == user_input:\n blank_line[i] = user_input\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for i in range(len(word)):\n if word[i] == user_input:\n blank_line[i] = user_input\n</code></pre>\n\n<p>In fact, <a href=\"http://regex.info/blog/2006-09-15/247\" rel=\"nofollow noreferrer\">by not using regexes, we fix a bug</a> in your code: if the chosen vocabulary word contains <code>.</code> as one of its non-space-non-alpha characters, a user who enters <code>.</code> as their guess will win the game immediately! :D</p>\n\n<p>Anyway, that's enough for one answer, I think.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:13:49.380", "Id": "406673", "Score": "2", "body": "Unfortunately your second recommendation produces the error `TypeError: 'dict_keys' object does not support indexing` when trying to randomly choose a key, so the wrapping with `list` is needed. In Python 2 this worked since the keys were a list already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:15:35.750", "Id": "406674", "Score": "0", "body": "But you can get rid of the `.keys()`, `random.choice(list(data))` works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:17:40.147", "Id": "406675", "Score": "2", "body": "And nowadays `f\"WORD COUNT : {len(vocab)}\"` is all the rage, which is at least shorter again :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T16:09:03.157", "Id": "406735", "Score": "2", "body": "Ah, I mistakenly thought `random.choice` could handle any iterable. If OP had written `random.choice(list(data))` I probably would have complained that that approach was too \"cute\" and not expressive enough. ;) The problem of a `random.choice` that works on arbitrary iterables is discussed here: https://stackoverflow.com/questions/12581437/python-random-sample-with-a-generator-iterable-iterator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:21:53.937", "Id": "406922", "Score": "0", "body": "If I have many variables to concatenate in a string, isn't it better to use +. But if I only have a variable to concatenate at the end of the string, then is it better to use %s or %d?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T22:31:48.647", "Id": "406958", "Score": "0", "body": "The two advantages of `%d` (or `\"{}\".format`, or `f\"{}\"`) are that you can format many variables at once, which is handy for [i18n](https://www.mattlayman.com/blog/2015/i18n/); and that they have their own concise DSL for formatting, such as `%02d`, `{:^x}`, etc. Which is easier to write and to read — `\"(0x\" + hex(p)[2:].zfill(8) + \")\"` or `\"(0x%08x)\" % p`?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T03:24:58.630", "Id": "210402", "ParentId": "210386", "Score": "3" } } ]
{ "AcceptedAnswerId": "210402", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T20:21:42.117", "Id": "210386", "Score": "4", "Tags": [ "python", "json", "hangman" ], "Title": "Hangman program w/ Python and JSON" }
210386
<p>I've implemented a graph for a course and i'd like to know what i could improve. The graph is created from a adjacency list from a file with the following format per row:</p> <pre><code>node_name [neighbor_1_name[:edge_weight[:edge_flow]]]* </code></pre> <p>Nodes that do not have neighbors must not be declared in a own row (a node is created when the name is encountered for the first time). The first row of the file can indicate whether the graph is directed or not and empty lines and lines starting with <code>//</code> are ignored when parsing the data.</p> <p>An example file could look like this:</p> <pre><code>// Floyd-Warshall test graph. 1 3:-2 2 1:4 3:3 3 4:2 4 2:-1 </code></pre> <p>The used compiler is the one shipped with Visual Studio 2017.</p> <p><strong>Node.h</strong></p> <pre><code>#pragma once #ifndef _NODE_ #define _NODE_ #include &lt;string&gt; /// Defines a node of a graph. class Node { private: const std::string name; public: /// &lt;summary&gt; /// Initializes a new instance of the Node class with the given name. /// &lt;/summary&gt; /// &lt;param name="name"&gt;The name of the node.&lt;/param&gt; Node(std::string name); /// &lt;summary&gt; /// Returns the name of the node. /// &lt;/summary&gt; /// &lt;returns&gt;The name of the node.&lt;/returns&gt; std::string GetName() const; /// &lt;summary&gt; /// Determines whether the node is equal to &lt;paramref name="other"/&gt;. /// &lt;/summary&gt; /// &lt;param name="other"&gt;The other node to compare this node to.&lt;/param&gt; /// &lt;returns&gt;true, if the node's name equals the other node's name; false, otherwise.&lt;/returns&gt; bool operator==(const Node&amp; other) const; }; #endif // !_NODE_ </code></pre> <p><strong>Node.cpp</strong></p> <pre><code>#include "Node.h" Node::Node(const std::string name) : name(name) { } std::string Node::GetName() const { return this-&gt;name; } bool Node::operator==(const Node&amp; other) const { if (this == &amp;other) { return true; } return this-&gt;name.compare(other.name) == 0; } </code></pre> <p><strong>Edge.h</strong></p> <pre><code>#pragma once #ifndef _EDGE_ #define _EDGE_ #include &lt;memory&gt; #include "Node.h" /// Defines an edge of a graph. class Edge { private: const std::shared_ptr&lt;Node&gt; source; const std::shared_ptr&lt;Node&gt; destination; double weight; double flow; public: /// &lt;summary&gt; /// Initializes a new instance of the Edge class with /// the given source and destination nodes and a weight of 1. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="destination"&gt;The source node of the edge.&lt;/param&gt; Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination); /// &lt;summary&gt; /// Initializes a new instance of the Edge class with /// the given source and destination nodes and weight. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="destination"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="weight"&gt;The weight of the edge.&lt;/param&gt; Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination, double weight); /// &lt;summary&gt; /// Initializes a new instance of the Edge class with /// the given source and destination nodes, weight and flow. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="destination"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="weight"&gt;The weight of the edge.&lt;/param&gt; /// &lt;param name="flow"&gt;The flow of the edge.&lt;/param&gt; Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination, double weight, double flow); /// &lt;summary&gt; /// Gets a pointer to the source node of the edge. /// &lt;/summary&gt; /// &lt;returns&gt;A pointer to the source node of the edge.&lt;/returns&gt; const std::shared_ptr&lt;Node&gt; GetSourceNode() const; /// &lt;summary&gt; /// Gets a pointer to the destination node of the edge. /// &lt;/summary&gt; /// &lt;returns&gt;A pointer to the destination node of the edge.&lt;/returns&gt; const std::shared_ptr&lt;Node&gt; GetDestinationNode() const; /// &lt;summary&gt; /// Gets the weight of the edge. /// &lt;/summary&gt; /// &lt;returns&gt;The weight of the edge.&lt;/returns&gt; double GetWeight() const; /// &lt;summary&gt; /// Sets the weight of the edge. If the current flow of the node is /// greater than the new weight, the flow is set to the new weight. /// &lt;/summary&gt; /// &lt;param name="weight"&gt;The new weight of the edge.&lt;/param&gt; void SetWeight(double weight); /// &lt;summary&gt; /// Gets the flow of the edge. /// &lt;/summary&gt; /// &lt;returns&gt;The flow of the edge.&lt;/returns&gt; double GetFlow() const; /// &lt;summary&gt; /// Sets the flow of the edge. Throws std::out_of_range when // &lt;paramref name="flow"/&gt; is greater than &lt;see cref="weight"/&gt;. /// &lt;/summary&gt; /// &lt;param name="flow"&gt;The new flow of the edge.&lt;/param&gt; void SetFlow(double flow); }; #endif // !_EDGE_ </code></pre> <p><strong>Edge.cpp</strong></p> <pre><code>#include "Edge.h" Edge::Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination) : source(source), destination(destination), weight(1), flow(0) { } Edge::Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination, double weight) : source(source), destination(destination), weight(weight), flow(0) { } Edge::Edge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination, double weight, double flow) : source(source), destination(destination), weight(weight), flow(flow) { } double Edge::GetWeight() const { return this-&gt;weight; } void Edge::SetWeight(double weight) { this-&gt;weight = weight; if (this-&gt;weight &lt; this-&gt;flow) { this-&gt;flow = this-&gt;weight; } } double Edge::GetFlow() const { return this-&gt;flow; } void Edge::SetFlow(double flow) { if (this-&gt;weight &lt; flow) { throw std::out_of_range("The flow of an edge cannot exceed it's capacity."); } this-&gt;flow = flow; } const std::shared_ptr&lt;Node&gt; Edge::GetSourceNode() const { return this-&gt;source; } const std::shared_ptr&lt;Node&gt; Edge::GetDestinationNode() const { return this-&gt;destination; } </code></pre> <p><strong>string_helper.h</strong></p> <pre><code>#pragma once #ifndef _STRING_HELPER_ #define _STRING_HELPER_ #define WHITESPACE " \t\f\v\r\n" #include &lt;string&gt; #include &lt;vector&gt; namespace string_helper { /// Defines how to split a string. enum class string_split_options { None, RemoveEmptyEntries }; /// &lt;summary&gt; /// Splits the given string using the given delimiter and returns a vector with /// the string's parts. /// &lt;/summary&gt; /// &lt;param name="str"&gt;The string to split.&lt;/param&gt; /// &lt;param name="delimiter"&gt;The delimiter to use when splitting the string.&lt;/param&gt; /// &lt;param name="splitOptions"&gt;Split options for the string to split.&lt;/param&gt; /// &lt;returns&gt;A vector containing the string parts.&lt;/returns&gt; const std::vector&lt;std::string&gt; split(std::string str, std::string delimiter, string_split_options splitOptions = string_split_options::None); /// &lt;summary&gt; /// Checks whether the given string consists only of whitespace // characters or whether the given string has a length of 0. /// &lt;/summary&gt; /// &lt;param name="str"&gt;The string to check.&lt;/param&gt; /// &lt;returns&gt;true, if the string is empty; false, otherwise.&lt;/returns&gt; bool is_empty(std::string str); /// &lt;summary&gt; /// Checks whether the given string starts with the given value. /// &lt;/summary&gt; /// &lt;param name="str"&gt;The string to check.&lt;/param&gt; /// &lt;param name="value"&gt;The value to check.&lt;/param&gt; /// &lt;returns&gt;true, if the string starts with &lt;paramref name="value"/&gt;; false, otherwise.&lt;/returns&gt; bool starts_with(std::string str, std::string value); } #endif // !_STRING_HELPER_ </code></pre> <p><strong>string_helper.cpp</strong></p> <pre><code>#include "string_helper.h" using split_options = string_helper::string_split_options; const std::vector&lt;std::string&gt; string_helper::split( const std::string str, const std::string delimiter, string_helper::string_split_options splitOptions /* = None */ ) { std::vector&lt;std::string&gt; result; size_t delimiterIndex = -1; size_t oldDelimiterIndex = -1; while ((delimiterIndex = str.find(delimiter, delimiterIndex + 1)) != std::string::npos) { ++oldDelimiterIndex; std::string substr = str.substr(oldDelimiterIndex, delimiterIndex - oldDelimiterIndex); oldDelimiterIndex = delimiterIndex; if (splitOptions == split_options::RemoveEmptyEntries &amp;&amp; substr.length() == 0) { continue; } result.push_back(substr); } // If there are more characters after the last index of the delimiter // add them to the result vector as well. ++oldDelimiterIndex; if (oldDelimiterIndex != str.length()) { result.push_back(str.substr(oldDelimiterIndex)); } return result; } bool string_helper::is_empty(const std::string str) { return str.length() == 0 || str.find_first_not_of(WHITESPACE) == std::string::npos; } bool string_helper::starts_with(const std::string str, const std::string value) { return str.length() &gt;= value.length() &amp;&amp; str.substr(0, value.length()) == value; } </code></pre> <p><strong>Graph.h</strong></p> <pre><code>#pragma once #ifndef _GRAPH_ #define _GRAPH_ #include &lt;memory&gt; #include &lt;set&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; #include "Edge.h" #include "Node.h" /// Defines a graph with nodes and edges. class Graph { private: bool directed; std::set&lt;std::shared_ptr&lt;Node&gt;&gt; nodes; std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; edges; public: /// &lt;summary&gt; /// Initializes a new instance of the Graph class. /// &lt;/summary&gt; Graph() { } /// &lt;summary&gt; /// Creates a graph from the adjacency list stored in the file with the given path. /// &lt;/summary&gt; /// &lt;param name="file"&gt;The path to the file that contains the adjacency list.&lt;/param&gt; /// &lt;returns&gt;A shared pointer to the created graph.&lt;/returns&gt; static std::shared_ptr&lt;Graph&gt; FromAdjacencyList(std::string file); #pragma region Node stuff. /// &lt;summary&gt; /// Creates a new node with the given name and adds it to the graph. /// &lt;/summary&gt; /// &lt;param name="name"&gt;The name of the node to create.&lt;/param&gt; /// &lt;returns&gt;A shared pointer to the created node.&lt;/returns&gt; const std::shared_ptr&lt;Node&gt; AddNode(std::string name); /// &lt;summary&gt; /// Adds the given node to the graph. /// &lt;/summary&gt; /// &lt;param name="node"&gt;A pointer to the node to add.&lt;/param&gt; void AddNode(const std::shared_ptr&lt;Node&gt; node); /// &lt;summary&gt; /// Adds a node with the given name to the graph, if there is no node with the name /// or returns a pointer to the node with the given name. /// &lt;/summary&gt; /// &lt;param name="name"&gt;The name of the node to create.&lt;/param&gt; /// &lt;returns&gt;A shared pointer to the created or existent node.&lt;/returns&gt; const std::shared_ptr&lt;Node&gt; AddNodeIfNotExist(std::string name); /// &lt;summary&gt; /// Returns a pointer to the node with the given name or a null pointer /// if no node with the given name exists. /// &lt;/summary&gt; /// &lt;param name="edge"&gt;The name of the node to which to return a pointer.&lt;/param&gt; /// &lt;returns&gt;A pointer to the node with the given name.&lt;/returns&gt; const std::shared_ptr&lt;Node&gt; GetNode(std::string name) const; /// &lt;summary&gt; /// Returns a set of the nodes of the graph. /// &lt;/summary&gt; /// &lt;returns&gt;A set containing pointers to all nodes of the graph.&lt;/returns&gt; const std::set&lt;std::shared_ptr&lt;Node&gt;&gt; GetNodes() const; /// &lt;summary&gt; /// Returns the number of nodes in the graph. /// &lt;/summary&gt; /// &lt;returns&gt;The number of nodes in the graph.&lt;/returns&gt; const size_t NodeCount() const; #pragma endregion #pragma region Edge stuff. /// &lt;summary&gt; /// Adds a new edge between the given nodes to the graph and returns the created edge or /// a null pointer if any of both nodes is not part of the graph. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="destination"&gt;The destination node of the edge.&lt;/param&gt; /// &lt;returns&gt;A shared pointer for the created edge or a null pointer if any of both nodes is not part of the graph.&lt;/returns&gt; const std::shared_ptr&lt;Edge&gt; AddEdge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination); /// &lt;summary&gt; /// Returns a pointer to the egde with the given source and destination /// nodes or a null pointer if no such edge exists. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edge.&lt;/param&gt; /// &lt;param name="destination"&gt;The destination node of the edge.&lt;/param&gt; /// &lt;returns&gt;A pointer to the edge with the given source and destination.&lt;/returns&gt; const std::shared_ptr&lt;Edge&gt; GetEdge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination) const; /// &lt;summary&gt; /// Returns a vector of all edges of the graph. /// &lt;/summary&gt; /// &lt;returns&gt;A vector containing pointers to all edges of the graph.&lt;/returns&gt; const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; GetEdges() const; /// &lt;summary&gt; /// Returns a vector containing all edges of the graph that have the given node as source node. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The source node of the edges to fetch.&lt;/param&gt; /// &lt;returns&gt;A vector of pointers to edges with the given node as source node.&lt;/returns&gt; const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; GetEdgesFrom(const std::shared_ptr&lt;Node&gt; source) const; /// &lt;summary&gt; /// Returns a vector containing all edges of the graph that have the given node as destination node. /// &lt;/summary&gt; /// &lt;param name="source"&gt;The destination node of the edges to fetch.&lt;/param&gt; /// &lt;returns&gt;A vector of pointers to edges with the given node as destination node.&lt;/returns&gt; const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; GetEdgesTo(const std::shared_ptr&lt;Node&gt; destination) const; #pragma endregion /// &lt;summary&gt; /// Gets whether the graph is directed. /// &lt;/summary&gt; /// &lt;returns&gt;true, if the graph is directed; false, otherwise.&lt;/returns&gt; bool IsDirected() const; /// &lt;summary&gt; /// Sets whether the graph is directed. /// &lt;/summary&gt; /// &lt;param name="directed"&gt;true, if the graph is directed; false, otherwise.&lt;/param&gt; void SetIsDirected(bool directed); #pragma region Functionality. /// &lt;summary&gt; /// Checks whether there is a path between &lt;paramref name="root"/&gt; and &lt;paramref name="destination"/&gt; /// in the current graph using a depth-first-search algorithm and returns the result. /// &lt;/summary&gt; /// &lt;param name="root"&gt;The root node of the search.&lt;/param&gt; /// &lt;param name="destination"&gt;The destination node of the search.&lt;/param&gt; /// &lt;returns&gt;true, if there is a path from &lt;paramref name="root"/&gt; to &lt;paramref name="destination"/&gt;; false, otherwise.&lt;/returns&gt; bool DepthFirstSearch(std::shared_ptr&lt;Node&gt; root, std::shared_ptr&lt;Node&gt; destination) const; /// &lt;summary&gt; /// Calculates the shortes distance for all nodes to all other nodes. /// &lt;/summary&gt; /// &lt;returns&gt;An unordered map with the node as key and the distance to other nodes as value.&lt;/returns&gt; const std::unordered_map&lt;std::shared_ptr&lt;Node&gt;, std::unordered_map&lt;std::shared_ptr&lt;Node&gt;, double&gt;&gt; FloydWarshall() const; // And some more... #pragma endregion }; #endif // !_GRAPH_ </code></pre> <p><strong>Graph.cpp</strong></p> <pre><code>#include &lt;experimental/filesystem&gt; #include &lt;fstream&gt; #include &lt;queue&gt; #include &lt;regex&gt; #include "Graph.h" #include "string_helper.h" #include "UnionContainer.h" using edge_ptr = std::shared_ptr&lt;Edge&gt;; using node_ptr = std::shared_ptr&lt;Node&gt;; /////////////////////////////////////////////////////////////////////// /// Helpers for implementing the functionality of the graph. /////////////////////////////////////////////////////////////////////// namespace graph_helpers { // Depth-first-search implementation. bool depth_first_search( const Graph* graph, const node_ptr root, const node_ptr destination, std::set&lt;node_ptr&gt;&amp; visitedNodes, std::vector&lt;node_ptr&gt;&amp; path ) { path.push_back(root); if (root == destination) { return true; } visitedNodes.emplace(root); for (const auto edge : graph-&gt;GetEdgesFrom(root)) { const auto edgeDestination = edge-&gt;GetDestinationNode(); if (visitedNodes.find(edgeDestination) != visitedNodes.end()) { // Node has already been visited. continue; } if (depth_first_search(graph, edgeDestination, destination, visitedNodes, path)) { return true; } } path.pop_back(); return false; } // Floyd-Warshall shortest path implementation. const std::unordered_map&lt;node_ptr, std::unordered_map&lt;node_ptr, double&gt;&gt; floyd_warshall(const Graph* graph) { std::unordered_map&lt;node_ptr, std::unordered_map&lt;node_ptr, double&gt;&gt; distances; const auto nodes = graph-&gt;GetNodes(); // Initialize the initial distances based on a edge between nodes. for (const auto n1 : nodes) { for (const auto n2 : nodes) { const auto edge = graph-&gt;GetEdge(n1, n2); if (n1 == n2) { // Distance to itself is 0. distances[n1][n2] = 0; } else { if (edge) { distances[n1][n2] = edge-&gt;GetWeight(); } else { distances[n1][n2] = DBL_MAX; } } } } for (const auto n1 : nodes) { for (const auto n2 : nodes) { for (const auto n3 : nodes) { if (distances[n2][n3] &gt; distances[n2][n1] + distances[n1][n3]) { distances[n2][n3] = distances[n2][n1] + distances[n1][n3]; } } } } return distances; }; /////////////////////////////////////////////////////////////////////// /// Graph parsing. /////////////////////////////////////////////////////////////////////// std::shared_ptr&lt;Graph&gt; Graph::FromAdjacencyList(const std::string file) { if (!std::experimental::filesystem::exists(file)) { return nullptr; } const auto graph = std::make_shared&lt;Graph&gt;(); std::ifstream fileStream(file); std::string line; int lineNumber = 0; while (std::getline(fileStream, line)) { ++lineNumber; if (lineNumber == 1) { // First line can contain an indication for whether the graph is directed or not. // Example: directed=true, directed=t, directed=f, directed=false std::regex graphTypeRegex("^directed=(f|false|t|true)$"); std::smatch match; if (std::regex_search(line, match, graphTypeRegex)) { const bool directed = match[1] == "t" || match[1] == "true"; graph-&gt;SetIsDirected(directed); continue; } else { // Graph is directed by default. graph-&gt;SetIsDirected(true); } } // Check if the string is empty or whitespace only or // if the line is a comment line (starts with //) if (string_helper::starts_with(line, "//") || string_helper::is_empty(line)) { continue; } // Create the node and its neighbors. const auto nodes = string_helper::split(line, " ", string_helper::string_split_options::RemoveEmptyEntries); // There is at least one node, because the string is neither empty nor a comment. const auto currentNode = graph-&gt;AddNodeIfNotExist(nodes[0]); for (size_t i = 1; i &lt; nodes.size(); ++i) { // Format for a neighbor is name:edge_weight:egde_flow. // name should always be given, weight and flow are optional. const auto edgeData = string_helper::split(nodes[i], ":", string_helper::string_split_options::None); const auto edgeDestination = graph-&gt;AddNodeIfNotExist(edgeData[0]); const auto edge = graph-&gt;AddEdge(currentNode, edgeDestination); // Edge weight. if (edgeData.size() &gt; 1 &amp;&amp; edgeData[1] != "") { edge-&gt;SetWeight(std::stod(edgeData[1])); } // Edge flow. if (edgeData.size() &gt; 2 &amp;&amp; edgeData[2] != "") { edge-&gt;SetFlow(std::stod(edgeData[2])); } } } return graph; } /////////////////////////////////////////////////////////////////////// /// Node functions. /////////////////////////////////////////////////////////////////////// const std::shared_ptr&lt;Node&gt; Graph::AddNode(const std::string name) { auto node = std::make_shared&lt;Node&gt;(name); this-&gt;nodes.emplace(node); return node; } const std::shared_ptr&lt;Node&gt; Graph::AddNodeIfNotExist(const std::string name) { const auto existentNode = GetNode(name); if (existentNode) { return existentNode; } auto node = std::make_shared&lt;Node&gt;(name); this-&gt;nodes.emplace(node); return node; } void Graph::AddNode(const std::shared_ptr&lt;Node&gt; node) { this-&gt;nodes.emplace(node); } const std::set&lt;std::shared_ptr&lt;Node&gt;&gt; Graph::GetNodes() const { return std::set&lt;node_ptr&gt;(this-&gt;nodes); } const std::shared_ptr&lt;Node&gt; Graph::GetNode(const std::string name) const { for (auto node : this-&gt;nodes) { if (node-&gt;GetName() == name) { return node; } } return nullptr; } const size_t Graph::NodeCount() const { return this-&gt;nodes.size(); } /////////////////////////////////////////////////////////////////////// /// Edge functions. /////////////////////////////////////////////////////////////////////// const std::shared_ptr&lt;Edge&gt; Graph::AddEdge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination) { if (this-&gt;nodes.find(source) == this-&gt;nodes.end() || this-&gt;nodes.find(destination) == this-&gt;nodes.end()) { return nullptr; } auto edge = std::make_shared&lt;Edge&gt;(source, destination); this-&gt;edges.push_back(edge); return edge; } const std::shared_ptr&lt;Edge&gt; Graph::GetEdge(const std::shared_ptr&lt;Node&gt; source, const std::shared_ptr&lt;Node&gt; destination) const { for (auto edge : this-&gt;edges) { if (edge-&gt;GetSourceNode() == source &amp;&amp; edge-&gt;GetDestinationNode() == destination) { return edge; } } return nullptr; } const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; Graph::GetEdges() const { return std::vector&lt;edge_ptr&gt;(this-&gt;edges); } const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; Graph::GetEdgesFrom(const std::shared_ptr&lt;Node&gt; source) const { std::vector&lt;edge_ptr&gt; edgesWithSource; for (auto edge : this-&gt;edges) { if (edge-&gt;GetSourceNode() == source) { edgesWithSource.push_back(edge); } } return edgesWithSource; } const std::vector&lt;std::shared_ptr&lt;Edge&gt;&gt; Graph::GetEdgesTo(const std::shared_ptr&lt;Node&gt; destination) const { std::vector&lt;edge_ptr&gt; edgesWithDestination; for (auto edge : this-&gt;edges) { if (edge-&gt;GetDestinationNode() == destination) { edgesWithDestination.push_back(edge); } } return edgesWithDestination; } /////////////////////////////////////////////////////////////////////// /// Traits. /////////////////////////////////////////////////////////////////////// bool Graph::IsDirected() const { return this-&gt;directed; } void Graph::SetIsDirected(bool directed) { this-&gt;directed = directed; } /////////////////////////////////////////////////////////////////////// /// Functionality. /////////////////////////////////////////////////////////////////////// bool Graph::DepthFirstSearch(std::shared_ptr&lt;Node&gt; root, std::shared_ptr&lt;Node&gt; destination) const { std::set&lt;node_ptr&gt; visitedNodes; std::vector&lt;node_ptr&gt; path; return graph_helpers::depth_first_search(this, root, destination, visitedNodes, path); } const std::unordered_map&lt;std::shared_ptr&lt;Node&gt;, std::unordered_map&lt;std::shared_ptr&lt;Node&gt;, double&gt;&gt; Graph::FloydWarshall() const { return graph_helpers::floyd_warshall(this); } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "Graph.h" void print_edge(const std::shared_ptr&lt;Edge&gt;&amp; edge) { std::cout &lt;&lt; edge-&gt;GetSourceNode()-&gt;GetName() &lt;&lt; " -&gt; " &lt;&lt; edge-&gt;GetDestinationNode()-&gt;GetName() &lt;&lt; ", " &lt;&lt; edge-&gt;GetWeight() &lt;&lt; "[" &lt;&lt; edge-&gt;GetFlow() &lt;&lt; "]" &lt;&lt; std::endl; } void print_node(const std::shared_ptr&lt;Node&gt;&amp; node) { std::cout &lt;&lt; node-&gt;GetName() &lt;&lt; std::endl; } void print_graph(const std::shared_ptr&lt;Graph&gt;&amp; g) { std::cout &lt;&lt; "Directed: " &lt;&lt; g-&gt;IsDirected() &lt;&lt; std::endl; std::cout &lt;&lt; "Nodes" &lt;&lt; std::endl; for (auto node : g-&gt;GetNodes()) { print_node(node); } std::cout &lt;&lt; std::endl &lt;&lt; "Edges" &lt;&lt; std::endl; for (auto edge : g-&gt;GetEdges()) { print_edge(edge); } } int main() { const auto g = Graph::FromAdjacencyList("SampleGraph_5.txt"); print_graph(g); std::cout &lt;&lt; std::endl; const auto distances = g-&gt;FloydWarshall(); for (const auto source : distances) { for (const auto destination : source.second) { std::cout &lt;&lt; "Distance from '" &lt;&lt; source.first-&gt;GetName() &lt;&lt; "' to '" &lt;&lt; destination.first-&gt;GetName() &lt;&lt; "': " &lt;&lt; destination.second &lt;&lt; std::endl; } } std::cin.get(); return 0; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T22:14:58.930", "Id": "210388", "Score": "1", "Tags": [ "c++", "graph" ], "Title": "Graph implementation from adjacency list" }
210388
<p>Problem:</p> <blockquote> <p>Given a square or rectangular matrix, print its element in spiral order.</p> <p>For example, if input matrix is this:</p> <pre><code> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 </code></pre> <p>Output should be:</p> <pre><code>1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 </code></pre> </blockquote> <p>This code assumes a matrix of 6X5. I do feel it can look more elegant or functional. I want to get rid of vars.</p> <pre><code>import scala.util.Random object MatrixSpiral extends App { val matrix = Array.fill(6)(Array.fill(5)(Random.nextInt(10))) matrix foreach (row =&gt; println(row.mkString(","))) var rows = 6 var cols = 5 var r = 0 var c = 0 var startR = 0 var startC = 0 println while (r &lt; rows &amp;&amp; c &lt; cols) { for (i &lt;- c until cols) { c = i; print(matrix(r)(i) + " ") } r += 1 for (j &lt;- r until rows) { r = j; print(matrix(j)(c) + " ") } c -= 1 for (k &lt;- c to startC by -1) { c = k; print(matrix(r)(k) + " ") } r -= 1 for (l &lt;- r to startR + 1 by -1) { r = l; print(matrix(l)(c) + " ") } rows -= 1 cols -= 1 c += 1 startR = r startC = c } } </code></pre>
[]
[ { "body": "<p>You are using many indexes in your code.</p>\n\n<p>That is, you are using an imperative style of programming.</p>\n\n<p>Functional style is more about decomposing the problem in smaller even tiny steps and using recursion where reasonable.</p>\n\n<p>To print out as a spiral the outermost part of a matrix what do you do?</p>\n\n<pre><code>1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n</code></pre>\n\n<p>Output should be -</p>\n\n<pre><code>1 2 3 4 8 12 16\n^ ^\nFirst row Last column reversed but avoiding repeating 4\n\n\n15 14 13\n^\nLast row reversed (again careful on repetions)\n\n9 5\n^\nFirst column reversed omitting both first and last\n</code></pre>\n\n<p>And then? How to print the inside as a spiral? You just remove the outside, the first and last columns and the first and last items of each row and apply this process again.</p>\n\n<p>This allows you to think, as much as possible in terms in concepts (print given row or column maybe reversed) instead of indexes, you find a way to simplify the problem and then establish a trivial base case (matrix empty = do not print)</p>\n\n<p>So you can a program like this, in pseudocode:</p>\n\n<pre><code>def nth_row\ndef nth_column\ndef except_first\ndef except_last\ndef reversed\n\ndef spiral_print(matrix):\n if len(matrix) == 0: end\n L = len(matrix)\n print(nth_row(0, matrix))\n print(except_first(nth_column(L, matrix)))\n # last row and first column handling missing\n print_spiral(inside_matrix(matrix))\n</code></pre>\n\n<p>I do not know Scala specifics semantics, but here is an implementation in Python:</p>\n\n<pre><code>def column(i, matrix):\n return [row[i] for row in matrix]\n\ndef spiral(matrix):\n if len(matrix) == 0:\n return\n print(matrix[0])\n print(column(-1, matrix)[1:])\n print(matrix[-1][::-1][1:])\n print(column(0, matrix)[::-1][1:-1])\n spiral([row[1:-1] for row in matrix[1:-1]])\n</code></pre>\n\n<p><code>[::-1]</code> means \"reversed\", and [1:-1] means \"except first and last\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T06:29:59.330", "Id": "406653", "Score": "1", "body": "thanks for these directions. They were really helpful and I am able to proceed on them and came up with a more functional solution of this problem. Posting that version as an answer of the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T00:12:45.970", "Id": "210390", "ParentId": "210389", "Score": "1" } }, { "body": "<p>As suggested by @Caridorc I tried implementing a more functional version of the solution. I do feel that this code can be made more elegant and some checks may be redundant.</p>\n\n<pre><code>def getRow(row: Int, m: Array[Array[Int]]): Seq[Int] = m(row)\n def getCol(col: Int, m: Array[Array[Int]]): Seq[Int] = (0 until m.length).map(i =&gt; m(i)(col)).toSeq\n def printNonEmpty(s: Seq[Int]) : Unit = if (s.isEmpty) print(\"\") else print(s.mkString(\",\"))\n\n def dropOuter(m: Array[Array[Int]]): Array[Array[Int]] = {\n val rows = m.length -1\n val cols = m(0).length -1\n (1 until rows).map { r =&gt;\n (1 until cols).map { c =&gt;\n m(r)(c)\n }.toArray\n }.toArray\n }\n\n def printSpiral(m: Array[Array[Int]]) : Unit ={\n m.size match {\n case 0 =&gt; print(\"\")\n case _=&gt;\n printNonEmpty(getRow(0, m));print(\",\")\n if (m(0).length &gt; 0 ) {\n printNonEmpty(getCol(m(0).length -1, m).tail);print(\",\")\n }\n val bottom = getRow(m.length - 1, m)\n if (m.length &gt; 0 &amp;&amp; bottom.nonEmpty) {\n printNonEmpty(bottom.init.reverse);print(\",\")\n }\n if (m(0).size &gt; 1) {\n val left = getCol(0, m).init\n if (left.tail.nonEmpty) {\n printNonEmpty(left.tail.reverse);\n print(\",\")\n }\n }\n printSpiral(dropOuter(m))\n }\n }\n\n println(\"==================\")\n printSpiral(matrix)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:42:42.667", "Id": "406855", "Score": "1", "body": "Cool, thanks for implementing this. You can ask a new follow-up question with this code if you think It can still be improved :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T19:36:28.280", "Id": "406941", "Score": "0", "body": "yes, I am going to do that. Meanwhile posted a question which require similar kind of traversal and will highly value your feedback.\nhttps://codereview.stackexchange.com/questions/210450/clockwise-rotate-a-matrix-in-scala" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T06:33:01.863", "Id": "210406", "ParentId": "210389", "Score": "1" } } ]
{ "AcceptedAnswerId": "210390", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-26T23:10:34.793", "Id": "210389", "Score": "1", "Tags": [ "interview-questions", "functional-programming", "matrix", "scala" ], "Title": "Print matrix in spiral order in Scala" }
210389
<p>I'm fairly new to C, and this is my first time using <code>pthread</code>. I am pretty sure I implemented it correctly, however I'd like to verify it is indeed executing the tasks parallel instead of sequentially. Here is my <code>main.c</code> code:</p> <h3>main.c</h3> <pre><code>#include "frequency.h" /** * The main function. Runs {@code getMedianWord()} in parallel threads for each file, * then outputs the sorted elements in FileArray file_array. */ int main(int argc, char **argv) { int actual_args = argc - 1; pthread_t tid[argc]; for (int i = 0; i &lt; actual_args; ++i) pthread_create(&amp;tid[i], NULL, getMedianWord, (void *) &amp;argv[i + 1]); for (int j = 0; j &lt; actual_args; ++j) pthread_join(tid[j], NULL); qsort(file_array, (size_t) actual_args, sizeof(FileArray), (int (*)(const void *, const void *)) file_cmp ); for (int k = 0; k &lt; actual_args; ++k) printf("\n%s %d %s", file_array[k].filename, file_array[k].num, file_array[k].median_word ); pthread_exit(NULL); } </code></pre> <h3>frequency.c</h3> <pre><code>... void *getMedianWord(void *vargp) { char *filename = *(char **) vargp; WordArray word_array[MAX_WORDS]; FILE *fp = fopen(filename, "r"); char word[101]; int n = 0; while (!feof(fp)) { fscanf(fp, "%s", word); insert_word(word_array, &amp;n, word); } insert_arr(file_array, filename, n, word_array); pthread_exit(NULL); } </code></pre> <p>The intended code to be executed in parallel is the function <code>getMedianWord</code>, which adds a result to a global array of structs (<code>file_array</code>), and terminates via <code>pthread_exit(NULL)</code>.</p> <p>Please let me know if this is actually using threads properly, thanks!</p> <p><strong>PS.</strong> If you're interested in seeing the rest of my code, <a href="https://github.com/richardrobinson0924/unique_words" rel="nofollow noreferrer">here</a> it is.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T01:17:09.437", "Id": "406631", "Score": "2", "body": "The question would greatly benefit from adding `getMedianWord` code directly. As posted, it is on the verge of being closed as hypothetical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:13:50.653", "Id": "406634", "Score": "0", "body": "@vnp just added `getMedianWord`, thanks!!" } ]
[ { "body": "<p>I agree with commenter @vnp, who says, \"The question would greatly benefit from adding <code>getMedianWord</code> code directly. As posted, it is on the verge of being closed as hypothetical.\" All the interesting stuff is going on in <code>getMedianWord</code>.</p>\n\n<p>TLDR: yep, your use of <code>pthread_create</code> and <code>pthread_join</code> looks fine.</p>\n\n<p>However, I couldn't be sure of that without knowing the declaration of <code>getMedianWord</code>, for which I had to click through to <a href=\"https://github.com/richardrobinson0924/unique_words/blob/master/frequency.c#L47-L48\" rel=\"nofollow noreferrer\">frequency.c</a>:</p>\n\n<pre><code>void *getMedianWord(void *vargp) {\n char *filename = *(char **) vargp;\n</code></pre>\n\n<p>Okay, this is fine.</p>\n\n<hr>\n\n<p>However, you could do better by passing the char pointer itself as your <code>void*</code> argument, instead of passing the <em>address</em> of the pointer. That is, if you rewrote your <code>getMedianWord</code> function —</p>\n\n<pre><code>void *getMedianWord(void *vargp) {\n const char *filename = vargp;\n</code></pre>\n\n<p>— then you could rewrite your <code>main</code> loop correspondingly —</p>\n\n<pre><code>for (int i = 1; i &lt; argc; ++i) {\n pthread_create(&amp;tid[i], NULL, getMedianWord, argv[i]);\n}\n</code></pre>\n\n<p>Notice that I've made two other cosmetic changes here. First, I put braces around every compound statement; see <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"nofollow noreferrer\">goto fail</a> for why. Second, I took your complicated <code>actual_args</code>/<code>i + 1</code> logic and turned it into an idiomatic loop running over the half-open range <code>[1, argc)</code>. Use the most common idioms you can! It saves your reader some brain cells.</p>\n\n<p>The functional change here is replacing <code>&amp;argv[...]</code> with simply <code>argv[...]</code>. (The cast to <code>void*</code> is not required in C. And likewise the cast back from <code>void*</code> inside <code>getMedianWord</code> is not required in C, although it would be required if you wanted to port this code to C++.)</p>\n\n<hr>\n\n<p>I won't very closely review the rest of <code>getMedianWord</code> because you didn't post it.</p>\n\n<p>It is definitely <strong>not</strong> thread-safe, though; there's a data race on <code>file_index</code>. Look up the <code>_Atomic</code> keyword. </p>\n\n<hr>\n\n<p>I notice that <code>getMedianWord</code> spends most of its time <em>reading from files</em>, which means that it's not likely to parallelize very well. You'll end up being bounded by the speed of your file-reading. Splitting up those reads into different threads doesn't achieve any speedup; in fact it probably <em>wastes</em> time because now you have to wait for a context-switch between each pair of reads. (OTOH, the files will be buffered at the stdio level and also probably brought into memory at the OS level, so maybe I'm wrong about its hurting. I think I'm right about its not helping, though.)</p>\n\n<p>Try reading all the files into memory first, and then splitting up <em>just the computational processing</em> of those files into multiple threads.</p>\n\n<p>In other words, think of \"the filesystem\" as a contended resource which will destroy your parallelism if everyone's trying to access it at once. (Also think of the <code>malloc</code>/<code>free</code> heap and <code>stdout</code> as contended resources. Looks like you're doing well on those fronts.)</p>\n\n<hr>\n\n<p>Your <code>WordArray word_array[MAX_WORDS];</code> is a <a href=\"https://en.cppreference.com/w/c/language/array#Variable-length_arrays\" rel=\"nofollow noreferrer\">variable-length array</a>, which might blow up your (thread's) stack if <code>MAX_WORDS</code> is increased to, say, <code>2000000 / sizeof(WordArray)</code> — that is, if <code>MAX_WORDS * MAX_STRING &gt;= 2000000</code>. So watch out for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:16:40.290", "Id": "406635", "Score": "0", "body": "Thank you so much for all your feedback!! I'll be sure to work on everything you pointed out. Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T01:48:36.450", "Id": "210394", "ParentId": "210391", "Score": "3" } } ]
{ "AcceptedAnswerId": "210394", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T00:26:40.980", "Id": "210391", "Score": "2", "Tags": [ "c", "multithreading", "sorting", "thread-safety", "pthreads" ], "Title": "Simple multithreading C project" }
210391
<p>Is this reliable, or have I missed something?</p> <p>I want a drop-in replacement for WaitForSingleObject (sans the return type, I like <code>HRESULT</code> much better than any other error codes).</p> <p>This code works in a plugin DLL for third party closed-source software. I don’t have source code of that app, i.e. if you ask “what else might happen on the same thread while it waits?” the answer is “anything at all”.</p> <pre><code>constexpr HRESULT E_TIMEOUT = HRESULT_FROM_WIN32( ERROR_TIMEOUT ); constexpr int MSGF_SLEEPMSG = 0x5300; inline HRESULT getLastHr() { return HRESULT_FROM_WIN32( GetLastError() ); } // Same as WaitForSingleObject but processes windows messages while it waits. HRESULT msgWaitForSingleObject( HANDLE h, DWORD ms ) { // https://blogs.msdn.microsoft.com/oldnewthing/20060126-00/?p=32513/ while( true ) { const DWORD started = GetTickCount(); const DWORD res = MsgWaitForMultipleObjectsEx( 1, &amp;h, ms, QS_ALLINPUT, MWMO_INPUTAVAILABLE ); if( WAIT_OBJECT_0 == res ) return S_OK; if( WAIT_OBJECT_0 + 1 == res ) { MSG msg; while( PeekMessage( &amp;msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) { PostQuitMessage( (int)msg.wParam ); return S_FALSE; // Abandoned due to WM_QUIT } if( !CallMsgFilter( &amp;msg, MSGF_SLEEPMSG ) ) { TranslateMessage( &amp;msg ); DispatchMessage( &amp;msg ); } } const DWORD elapsed = GetTickCount() - started; //&lt; This works OK even when DWORD overflows: https://codereview.stackexchange.com/a/129670/46194 if( elapsed &gt; ms ) return E_TIMEOUT; ms -= elapsed; continue; } if( WAIT_TIMEOUT == res ) return E_TIMEOUT; HRESULT hr = getLastHr(); if( FAILED( hr ) ) return hr; return E_UNEXPECTED; // Unasked IO_COMPLETION or ABANDONED? } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:51:22.290", "Id": "407037", "Score": "0", "body": "From puristic code-review point of view: why parameters are mutable variables in this function? `ms -= elapsed`. I myself would make such int parameter const and copy it to non-const variable. The optimization compiler would completely minimize the overhead but it helps in debug mode so that we see the parameter without going up the stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T18:07:09.783", "Id": "407038", "Score": "0", "body": "@AlexanderV With 2 variables, you can accidentally use the wrong one of them, introducing a bug. Timeouts happen rarely, such bug will likely go unnoticed until it’s too late and the code’s deployed in production. When there’s only a single variable for remaining time, you can’t fail like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T22:57:59.843", "Id": "407056", "Score": "0", "body": "Right, use `const` modifier for the parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T01:35:43.873", "Id": "407058", "Score": "0", "body": "@AlexanderV Doesn’t help. `MsgWaitForMultipleObjectsEx` will happily accept `const` input variable instead of the non-const." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T02:32:12.067", "Id": "210399", "Score": "3", "Tags": [ "c++", "winapi" ], "Title": "WaitForSingleObject with windows messages processing" }
210399
<p>I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The idea was to use those routines as means to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.</p> <p>This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.</p> <p>NOTES: </p> <ol> <li><p>I know that using lists might not be the most efficient thing to do, but they allowed me to program in a more functional way without using <code>vector-set!</code></p></li> <li><p>If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.</p></li> <li><p>Sadly Emacs uses tabs for indentation so formatting may be a little messy.</p></li> </ol> <p>An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to. If no pair contains a specific character then it defaults to the invalid state (index = 0).</p> <p>The <code>run-automata</code> function searches a matching substring and returns its offset or <code>#f</code> if it is not contained inside <code>string</code>.</p> <pre><code>(define (string-null? s) (= (string-length s) 0)) (define (string-append-c s c) (string-append s (string c))) (define (string-tail str) (substring str 1 (string-length str))) ;; is s2 a prefix of s1? ;; [TODO] - Use offset instead of string-tail (define (string-prefix? s1 s2) (cond [(string-null? s2) #t] [(string-null? s1) #f] [(not (char=? (string-ref s2 0) (string-ref s1 0))) #f] [else (string-prefix? (string-tail s1) (string-tail s2))])) (define (enumerate start end) (define (iter start end acc) (if (&gt; start end) acc (iter start (- end 1) (cons end acc)))) (iter start end '())) (define (build-automata needle) (define (max-suffix-that-is-prefix str) (cond [(string-null? str) ""] [(not (string-prefix? needle str)) (max-suffix-that-is-prefix (string-tail str))] [else str])) (define (build-transitions state-string transitions dictionary) (if (null? dictionary) transitions (let* ([c (car dictionary)] [suffix (max-suffix-that-is-prefix (string-append-c state-string c))]) (build-transitions state-string (if (string-null? suffix) transitions (cons (cons c (string-length suffix)) transitions)) (cdr dictionary))))) ;; Last state does not require a transition as it is the final state. ;; "We are done by that point". (let ([dictionary (string-&gt;list "abcdefghijkmnopqrstuvwxyz")]) (map (lambda (n) (build-transitions (substring needle 0 n) '() dictionary)) (enumerate 0 (- (string-length needle) 1))))) ;; Takes an automata and a string and returns the offset of the pattern the ;; automata was built to search (define (run-automata automata string) (define (search-transition c state-transitions) (cond [(null? state-transitions) 0] [(char=? (caar state-transitions) c) (cdar state-transitions)] [else (search-transition c (cdr state-transitions))])) (define (step state automata-size offset) (cond [(= state automata-size) (- offset automata-size)] [(&gt;= offset (string-length string)) #f] [else (step (search-transition (string-ref string offset) (list-ref automata state)) automata-size (+ offset 1))])) (step 0 (length automata) 0)) </code></pre>
[]
[ { "body": "<p>My suggestions are less about your design of the automaton, but rather a few comments on the style and language which I hope you will find useful.</p>\n\n<p><strong>Know your functions</strong><br>\nNote that, <code>string-null?</code> is <code>#t</code> if the string has zero length. Thus, <code>if ((string-null? str) \"\")</code> is the same as <code>if ((string-null? str) str)</code>. And that combines well with the <code>else</code> part in <code>max-suffix-that-is-prefix</code> which also returns <code>str</code>.</p>\n\n<pre><code> (define (max-suffix-that-is-prefix str)\n (if (string-prefix? needle str)\n str\n (max-suffix-that-is-prefix (string-tail str))))\n</code></pre>\n\n<p><strong>Named <code>let</code></strong><br>\nI noticed that some functions (<code>enumerate</code> and <code>run-automata</code>) define local functions only to then call them with initial values. Scheme provides a syntactic form for that, the named <code>let</code>:</p>\n\n<p><code>(let proc-id ([id init-expr] ...) body ...+)</code></p>\n\n<p>More on named <code>let</code>: <a href=\"https://docs.racket-lang.org/reference/let.html\" rel=\"nofollow noreferrer\">https://docs.racket-lang.org/reference/let.html</a></p>\n\n<p><strong>Adhering to the declarative paradigm</strong><br>\nThe <code>enumerate</code> function could be written in a declarative style. To enumerate from <code>start</code> to <code>end</code> is to <code>cons</code> <code>start</code> to the enumeration from <code>(+ start 1)</code> to <code>end</code>.</p>\n\n<pre><code>(define (enumerate start end)\n (if (= start end)\n `(,end)\n (cons start (enumerate (+ start 1) end))))\n</code></pre>\n\n<p>Note, however, that this is not an equivalent formulation of the iterative style using an accumulator since the call the <code>enumerate</code> in the call to <code>cons</code> prevents tail-recursion optimisation.</p>\n\n<p>Cleaner syntax using a named <code>let</code>:</p>\n\n<pre><code>(define (enumerate start end)\n (let iter ([start start] \n [end end] \n [acc '()])\n (if (&gt; start end)\n acc\n (iter start (- end 1) (cons end acc)))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:54:49.253", "Id": "408191", "Score": "0", "body": "Thanks for your comments. I didn't know about named let which I find now very useful as I had that recurring problem of declaring functions just to call them with the initial arguments. What I don't understand completely is, what do you mean by \"adhering to the declarative paradigm\". I did know the alternative way to enumerate, but I went with this one specifically because of the tail-recursion optimization. I would like to understand your point though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T07:17:47.603", "Id": "408266", "Score": "0", "body": "@Thomas I brought it up because you said that you came from a C background and sometimes have difficulties to switch to a functional approach. -- I can imagine it to be quite common for those who come from an imperative paradigm to think in terms of loops and conditionals and then try to write that with the means available in e.g. Scheme. That would result in codes using such auxiliary functions to iterate. But if you did it intentionally and for a good reason, than it is quite all right ^^" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:34:21.057", "Id": "211095", "ParentId": "210400", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T03:10:00.863", "Id": "210400", "Score": "2", "Tags": [ "strings", "search", "scheme", "state-machine" ], "Title": "Scheme: FSM substring search" }
210400
<p>This is a continuation from my original <a href="https://codereview.stackexchange.com/questions/210207">question</a>. After the improvements suggested by @<a href="https://codereview.stackexchange.com/users/25834/reinderien">Reinderien</a> and some of my own.<br/> This approach I've taken is kinda obvious. And I'm not using any parallel processing. I think there's scope for improvement because I know of a crate, <a href="https://github.com/rayon-rs/rayon" rel="nofollow noreferrer">Rayon</a> in Rust which could have run the steps I'm currently running, parallelly. I'll explain why I think this is possible below.</p> <pre><code>""" Find the number of 'exceptions' and 'added' event's in the exception log with respect to the device ID. author: clmno date: 2018-12-23 updated: 2018-12-27 """ from time import time import re def timer(fn): """ Used to time a function's execution""" def f(*args, **kwargs): before = time() rv = fn(*args, **kwargs) after = time() print("elapsed", after - before) return rv return f #compile the regex globally re_prefix = '.*?' re_guid='([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})' rg = re.compile(re_prefix+re_guid, re.IGNORECASE|re.DOTALL) def find_sql_guid(txt): """ From the passed in txt, find the SQL guid using re""" m = rg.search(txt) if m: guid1 = m.group(1) else: print("ERROR: No SQL guid in line. Check the code") exit(-1) return guid1 @timer def find_device_IDs(file_obj, element): """ Find the element (type: str) within the file (file path is provide as arg). Then find the SQL guid from the line at hand. (Each line has a SQL guid) Return a dict of {element: [&lt;list of SQL guids&gt;]} """ lines = set() for line in file_obj: if element in line: #find the sql-guid from the line-str &amp; append lines.add(find_sql_guid(line)) file_obj.seek(0) return lines @timer def find_num_occurences(file_obj, key, search_val, unique_values): """ Find and append SQL guids that are in a line that contains a string that's in search_val into 'exception' and 'added' Return a dict of {'exception':set(&lt;set of SQL guids&gt;), 'added': set(&lt;set of SQL guids&gt;)} """ lines = {'exception':set(), 'added': set()} for line in file_obj: for value in unique_values: if value in line: if search_val[0] in line: lines['exception'].add(value) elif search_val[1] in line: lines['added'].add(value) file_obj.seek(0) return lines def print_stats(num_exceptions_dict): for key in num_exceptions_dict.keys(): print("{} added ".format(key) + str(len(list(num_exceptions_dict[key]["added"])))) print("{} exceptions ".format(key) + str(len(list(num_exceptions_dict[key]["exception"])))) if __name__ == "__main__": path = 'log/server.log' search_list = ('3BAA5C42', '3BAA5B84', '3BAA5C57', '3BAA5B67') with open(path) as file_obj: #find every occurance of device ID and find their corresponding SQL # guids (unique ID) unique_ids_dict = { element: find_device_IDs(file_obj, element) for element in search_list } #Now for each unique ID find if string ["Exception occurred", # "Packet record has been added"] is found in it's SQL guid list. search_with_in_deviceID = ("Exception occurred", "Packet record has been added") #reset the file pointer file_obj.seek(0) num_exceptions_dict = { elem: find_num_occurences(file_obj, elem, search_with_in_deviceID, unique_ids_dict[elem]) for elem in search_list } print_stats(num_exceptions_dict) </code></pre> <p>and <a href="https://pastebin.com/puqaUkzi" rel="nofollow noreferrer">here</a>'s a small server log for you to experiment on</p> <p><strong>Improvements</strong></p> <ul> <li>More pythonic with some help from Reinderien.<br/></li> <li>Opening the file only once. Can't see a significant change in execution speed. </li> <li>Using better data structure model. Was using <code>dict</code>s everywhere, <code>set</code>s made sense.</li> </ul> <p><strong>My current approach is to</strong></p> <ol> <li>Find the device ID (eg 3BAA5C42) and their corresponding SQL GUIDs.</li> <li>For each SQL GUID find if it resulted in an <code>exception</code> or <code>added</code> event. Store them in dict.<br/></li> <li>Print the stats</li> </ol> <p><strong>Parallelize</strong><br/> Step one and two are just <em>going through the file searching for a particular string and performing a set of instructions</em> once the sting is found. And so each process (both within steps one and two, and step one and two as a whole) is independent of each other / <code>mutually exclusive</code>. And so running them in parallel makes more sense.</p> <p>How should I get going to improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T06:36:00.683", "Id": "406654", "Score": "0", "body": "And I've read of Donald Knuth's famour string search algo [Knuth-Morris-Pratt](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). What I'm doing is a string search. Just wondering" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:03:25.963", "Id": "406671", "Score": "0", "body": "Your dictionary comprehension to find the unique IDs does not work. After `find_device_IDs` has run for the first time, you have reached the end of the file, so all except one ID are empty sets. A `file_obj.seek(0)` at the end of the function would help for now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:08:52.157", "Id": "406672", "Score": "0", "body": "The signature of that function should also be `def find_device_IDs(file_obj, element):`, otherwise it just accesses the global variable `file_obj`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:22:34.740", "Id": "406677", "Score": "0", "body": "@Graipher Fixed that in the code and tried running again. Sadly, there isn't a significant improvement from my previous version. (its 45s now, used to be 47s)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:24:28.787", "Id": "406678", "Score": "0", "body": "Well, of course there is, you are now reading the file four times again, instead of only once and then quitting ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:25:30.503", "Id": "406679", "Score": "1", "body": "Will write an answer to see if you can get away with a single pass over the file." } ]
[ { "body": "<p>As evidenced by your timings a major bottleneck of your code is having to read the file multiple times. At least it is now only opened once, but the actual content is still read eight times (once for each unique ID, so four times in your example, and then once again each for the exceptions).</p>\n\n<p>First, let's reduce this to two passes, once for the IDs and once for the exceptions/added events:</p>\n\n<pre><code>from collections import defaultdict\n\n@timer\ndef find_device_IDs(file_obj, search_list):\n \"\"\" Find the element (type: str) within the file (file path is \n provide as arg). Then find the SQL guid from the line at hand.\n (Each line has a SQL guid)\n Return a dict of {element: [&lt;list of SQL guids&gt;]}\n \"\"\"\n sql_guids = defaultdict(set)\n for line in file_obj:\n for element in search_list:\n if element in line:\n #find the sql-guid from the line-str &amp; append\n sql_guids[element].add(find_sql_guid(line))\n return sql_guids\n</code></pre>\n\n<p>The exception/added finding function is a bit more complicated. Here we first need to invert the dictionary:</p>\n\n<pre><code>device_ids = {sql_guid: device_id for device_id, values in unique_ids_dict.items() for sql_guid in values}\n# {'0af229d1-283e-4575-a818-901617a762a7': '3BAA5C57',\n# '2f4a7f93-d7ed-4514-bef0-9bb0f025ecd3': '3BAA5C42',\n# '4e720c6e-1866-4c9b-b967-dfab049266fb': '3BAA5B67',\n# '85708e5d-768d-4a90-ab71-60a737de96e3': '3BAA5B67',\n# 'e268b224-bfb7-40c7-8ae5-500eaecb292b': '3BAA5B84',\n# 'e4ced298-530c-41cc-98a7-42a2e4fe5987': '3BAA5B67'}\n</code></pre>\n\n<p>Then we can use that:</p>\n\n<pre><code>@timer\ndef find_num_occurences(file_obj, sql_guids, search_vals):\n device_ids = {sql_guid: device_id for device_id, values in sql_guids.items() for sql_guid in values}\n data = defaultdict(lambda: defaultdict(set))\n\n for line in file_obj:\n for sql_guid, device_id in device_ids.items():\n if sql_guid in line:\n for key, search_val in search_vals.items():\n if search_val in line:\n data[device_id][key].add(sql_guid)\n return data\n</code></pre>\n\n<p>The usage is almost the same as your code:</p>\n\n<pre><code>with open(path) as file_obj:\n device_ids = ('3BAA5C42', '3BAA5B84', '3BAA5C57', '3BAA5B67')\n sql_guids = find_device_IDs(file_obj, device_ids)\n file_obj.seek(0)\n\n search_with_in_deviceID = {\"exception\": \"Exception occurred\", \n \"added\": \"Packet record has been added\"}\n print(find_num_occurences(file_obj, sql_guids, search_with_in_deviceID))\n\n# defaultdict(&lt;function __main__.find_num_occurences.&lt;locals&gt;.&lt;lambda&gt;&gt;,\n# {'3BAA5B67': defaultdict(set,\n# {'added': {'4e720c6e-1866-4c9b-b967-dfab049266fb'},\n# 'exception': {'85708e5d-768d-4a90-ab71-60a737de96e3',\n# 'e4ced298-530c-41cc-98a7-42a2e4fe5987'}}),\n# '3BAA5B84': defaultdict(set,\n# {'added': {'e268b224-bfb7-40c7-8ae5-500eaecb292b'}}),\n# '3BAA5C42': defaultdict(set,\n# {'added': {'2f4a7f93-d7ed-4514-bef0-9bb0f025ecd3'}}),\n# '3BAA5C57': defaultdict(set,\n# {'added': {'0af229d1-283e-4575-a818-901617a762a7'}})})\n</code></pre>\n\n<hr>\n\n<p>You can actually get this down to a single pass, by collecting all IDs where an exception occurred and only at the end joining that with the elements you are actually searching for:</p>\n\n<pre><code>def get_data(file_obj, device_ids, search_vals):\n sql_guid_to_device_id = {}\n data = defaultdict(set)\n\n for line in file_obj:\n # search for an sql_guid\n m = rg.search(line)\n if m:\n sql_guid = m.group(1)\n\n # Add to mapping\n for device_id in device_ids:\n if device_id in line:\n sql_guid_to_device_id[sql_guid] = device_id\n\n # Add to exceptions/added\n for key, search_val in search_vals.items():\n if search_val in line:\n data[sql_guid].add(key)\n return sql_guid_to_device_id, data\n\ndef merge(sql_guid_to_device_id, data):\n data2 = defaultdict(lambda: defaultdict(set))\n\n for sql_guid, values in data.items():\n if sql_guid in sql_guid_to_device_id:\n for key in values:\n data2[sql_guid_to_device_id[sql_guid]][key].add(sql_guid)\n return data2\n</code></pre>\n\n<p>With the following usage:</p>\n\n<pre><code>with open(path) as file_obj:\n device_ids = ('3BAA5C42', '3BAA5B84', '3BAA5C57', '3BAA5B67')\n search_with_in_deviceID = {\"exception\": \"Exception occurred\", \n \"added\": \"Packet record has been added\"}\n sql_guid_to_device_id, data = get_data(file_obj, device_ids, search_with_in_deviceID)\n data2 = merge(sql_guid_to_device_id, data)\n\n for device_id, values in data2.items():\n for key, sql_guids in values.items():\n print(f\"{device_id} {key} {len(sql_guids)}\")\n\n# 3BAA5B67 exception 2\n# 3BAA5B67 added 1\n# 3BAA5C42 added 1\n# 3BAA5B84 added 1\n# 3BAA5C57 added 1\n</code></pre>\n\n<p><code>get_data</code>, <code>data</code> and <code>data2</code> still need better names...</p>\n\n<p>Other than that this should be faster because it reads the file only once. It does consume more memory, though, because it also saves exceptions or added events for SQL guids which you later don't need. If this trade-off is not worth it, go back to the first half of this answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:18:31.930", "Id": "406696", "Score": "2", "body": "The `one pass` solution was pretty awesome! It has brought it down to 6 seconds! TIL Lesser IO operations, faster your code. Coming from hardware/fw we always use IOs and rarely have enough RAM. ty" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:40:23.440", "Id": "210417", "ParentId": "210405", "Score": "3" } } ]
{ "AcceptedAnswerId": "210417", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T06:17:58.453", "Id": "210405", "Score": "2", "Tags": [ "python" ], "Title": "Counting SQL GUIDs from a server log and printing the stats, improved" }
210405
<h1>0x2048</h1> <p><a href="https://i.stack.imgur.com/hW3mb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hW3mb.png" alt="enter image description here"></a></p> <hr> <p>This is my implementation of the classic game "2048" in C. The instruction to build/run the project (GitHub repo) can be found <a href="https://github.com/GnikDroy/0x2048/tree/af0ec805c1cc02177d6b1ad04b7a9e660bf2414c" rel="noreferrer">here</a>.</p> <p>I started with the core game and then built a GUI interface out of it. I would love some feedback on my design. How the same implementation can be better written. Idioms, conventions, anything that comes to your mind.</p> <p>There is some information about the functions in the header files. Hope that improves readability and understanding.</p> <p>Improvements I am aware of:</p> <ul> <li><p>I create the texture for the text 2,4,8.. every time I draw the tiles. This is wasting resource since I can simply create the 16 tiles once and never have to worry about it again.</p></li> <li><p>There might be some brace inconsistency between Java and C style since my IDE doesn't do this automatically.</p></li> </ul> <p>Improvements I am unaware of:</p> <ul> <li><p>Am I leaking memory anywhere?</p></li> <li><p>style/convention/performance/memory and everything else.</p></li> <li><p>techniques to make my code more versatile/generic. Using matrix structs, as suggested by one of the answers, would help to create rectangular boards.</p></li> </ul> <p><strong>Edit: The repo is updated constantly. Please use the link above to see the version of repo when this question was posted. I wouldn't mind comments on the latest version either.</strong></p> <hr> <p><strong>game.h</strong></p> <pre><code>/** * @file game.h * @author Gnik Droy * @brief File containing function declarations for the game gui. * */ #pragma once #include "../include/core.h" #include "SDL2/SDL.h" #include "SDL2/SDL_ttf.h" #define SCREEN_WIDTH 500 #define SCREEN_HEIGHT 600 /** * @brief Initializes the SDL window. * * When two pointers to the pointer of gWindow and gRenderer are provided, * the function initializes both values with the values of created window * and renderer. * * If initialization is failed it may display error to stderr but * does not exit. * * @param gWindow The window of the game. * @param gRenderer The renderer for the game * @return If the initialization was successful. */ bool initSDL(SDL_Window **gWindow,SDL_Renderer** gRenderer); /** * @brief Closes the SDL window. * * Frees up resource by closing destroying the SDL window * * @param gWindow The window of the game. */ void SDLclose(SDL_Window* gWindow); /** * @brief Draws text centered inside a rect. * * When two pointers to the pointer of gWindow and gRenderer are provided, * the function initializes both values with the values of created window * and renderer. * * If initialization is failed it may display error to stderr but * does not exit. * * @param gRenderer The renderer for the game * @param font The font for the text * @param text The text to write * @param rect The SDL_Rect object inside which text is written * @param color The color of the text */ void draw_text(SDL_Renderer* gRenderer,TTF_Font* font,const char* text, SDL_Rect rect, SDL_Color color); /** * @brief Draws white text centered inside a rect. * * Same as draw_text(..., SDL_Color White) * * @param gRenderer The renderer for the game * @param font The font for the text * @param text The text to write * @param rect The SDL_Rect object inside which text is written */ void draw_text_white(SDL_Renderer* gRenderer,TTF_Font* font,const char* text, SDL_Rect rect); /** * @brief Clears the window * * Fills a color to entire screen. * * @param gRenderer The renderer for the game */ void SDLclear(SDL_Renderer* gRenderer); /** * @brief Draws black text centered inside the window. * * @param gRenderer The renderer for the game * @param size The size for the text * @param text The text to write */ void display_text(SDL_Renderer* gRenderer,const char* text,int size); /** * @brief Draws the game tiles. * * It draws the SIZE*SIZE game tiles to the window. * * @param gRenderer The renderer for the game * @param font The font for the tiles * @param matrix The game matrix. */ void draw_matrix(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font); /** * @brief Draws the new game button. * * It draws the new game button to the bottom corner. * * @param gRenderer The renderer for the game * @param font The font for the button * @param matrix The game matrix. Needed to reset game. */ void draw_button(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font); /** * @brief Handles the action of New Game button. * * Resets the game board for a new game, if the correct mouse event * had occured. * Function is run if left mouse button is released * * @param gRenderer The renderer for the game * @param e The mouse event * @param matrix The game matrix. */ void button_action(SDL_Event e,unsigned char matrix[][SIZE]); /** * @brief Draws the current game score * * It draws the current game score to the window * * @param gRenderer The renderer for the game * @param font The font for the tiles * @param matrix The game matrix. */ void draw_score(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font); /** * @brief Draws everything for the game and renders it to screen. * * It calls SDLclear(),draw_matrix(),draw_score() and draw_button() * and also renders it to screem. * * @param gRenderer The renderer for the game * @param font The font for the tiles * @param matrix The game matrix. */ void render_game(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font); /** * @brief This is the main game loop that handles all events and drawing * * @param gRenderer The renderer for the game * @param font The font for the tiles * @param matrix The game matrix. */ void gameLoop(unsigned char matrix[][SIZE],SDL_Renderer* gRenderer); /** * @brief Handles keyboard presses that correspond with the arrowkeys. * * It transforms the game matrix according to the keypresses. * It also checks if the game has been finished, draws game over screen * and resets the board if game over. * * @param gRenderer The renderer for the game * @param font The font for the tiles * @param matrix The game matrix. */ void handle_move(SDL_Event e,unsigned char matrix[][SIZE], SDL_Renderer * gRenderer); </code></pre> <p><strong>styles.h</strong></p> <pre><code>/** * @file styles.h * @author Gnik Droy * @brief File containing tile colors and related structs. * */ #pragma once /** @struct COLOR * @brief This structure defines a RBGA color * All values are stored in chars. * * @var COLOR::r * The red value * @var COLOR::g * The green value * @var COLOR::b * The blue value * @var COLOR::a * The alpha value * */ //Screen dimension constants #define SCREEN_WIDTH 500 #define SCREEN_HEIGHT 600 #define SCREEN_PAD 10 //FONT settings #define FONT_PATH "UbuntuMono-R.ttf" #define TITLE_FONT_SIZE 200 #define GOVER_FONT_SIZE 100 //Game Over font size #define CELL_FONT_SIZE 40 struct COLOR{ char r; char g; char b; char a; }; struct COLOR g_bg={211, 204, 201, 255}; struct COLOR g_fg={80, 80, 80, 255}; struct COLOR g_button_bg={255, 153, 102,255}; struct COLOR g_score_bg={143, 122, 102,255}; struct COLOR g_COLORS[]={ {230, 227, 232,255}, {255, 127, 89,255}, {224, 74, 69,255}, {237, 207, 114,255}, {65, 216, 127,255}, {54, 63, 135,255}, {78, 89, 178,255}, {109, 118, 191,255}, {84, 47, 132,255}, {125, 77, 188,255}, {163, 77, 188,255}, {176, 109, 196,255}, {0, 102, 204,255}, {0, 153, 255,255}, {51, 153, 255,255}, {153, 204, 255,255}, {102, 255, 102,255} }; </code></pre> <p><strong>core.h</strong></p> <pre><code>/** * @file core.h * @author Gnik Droy * @brief File containing function declarations for the core game. * */ #pragma once #include &lt;stdio.h&gt; #define SIZE 4 #define BASE 2 typedef char bool; /** * @brief Write the game matrix to the stream. * * The matrix is written as a comma seperated list of indices. * Each row is seperated by a '\n' character. * Each empty cell is represented by '-' character. * * The indices can be used to calculate the actual integers. * * You can use the constant stdout from &lt;stdio.h&gt; for printing to * standard output * * @param matrix The game matrix that is to be printed. * @param stream The file stream to use. */ void print_matrix(unsigned char matrix[][SIZE],FILE* stream); /** * @brief Checks if there are possible moves left on the game board. * * Checks for both movement and combinations of tiles. * * @param matrix The game matrix. * @return Either 0 or 1 */ bool is_game_over(unsigned char matrix[][SIZE]); /** * @brief This clears out the game matrix * * This zeros out the entire game matrix. * * @param matrix The game matrix. */ void clear_matrix(unsigned char matrix[][SIZE]); /** * @brief Adds a value of 1 to random place to the matrix. * * The function adds 1 to a random place in the matrix. * The 1 is placed in empty tiles. i.e tiles containing 0. * 1 is kept since you can use raise it with BASE to get required value. * Also it keeps the size of matrix to a low value. * * NOTE: It has no checks if there are any empty places for keeping * the random value. * If no empty place is found a floating point exception will occur. */ void add_random(unsigned char matrix[][SIZE]); /** * @brief Calculates the score of a game matrix * * It score the matrix in a simple way. * Each element in the matrix is used as exponents of the BASE. And the * sum of all BASE^element is returned. * * @return An integer that represents the current score */ int calculate_score(unsigned char matrix[][SIZE]); /** * @brief Shifts the game matrix in X direction. * * It shifts all the elements of the game matrix in the X direction. * If the direction is given as 0, it shifts the game matrix in the left * direction. Any other non zero value shifts it to the right direction. * * @param matrix The game matrix. * @param opp The direction of the shift. * * @return If the shift was successful */ bool shift_x(unsigned char matrix[][SIZE], bool opp); /** * @brief Merges the elements in X direction. * * It merges consecutive successive elements of the game matrix in the X direction. * If the direction is given as 0, it merges the game matrix to the left * direction. Any other non zero value merges it to the right direction. * * @param matrix The game matrix. * @param opp The direction of the shift. * * @return If the merge was successful */ bool merge_x(unsigned char matrix[][SIZE],bool opp); /** * @brief Moves the elements in X direction. * * It simply performs shift_x() and merge_x(). * If either of them were successful, it also calls add_random() * * @param matrix The game matrix. * @param opp The direction of the move. * */ void move_x(unsigned char matrix[][SIZE], bool opp); /** * @brief Shifts the game matrix in Y direction. * * It shifts all the elements of the game matrix in the Y direction. * If the direction is given as 0, it shifts the game matrix in the top * direction. Any other non-zero value shifts it to the bottom. * * @param matrix The game matrix. * @param opp The direction of the shift. * * @return If the shift was successful */ bool shift_y(unsigned char matrix[][SIZE], bool opp); /** * @brief Merges the elements in Y direction. * * It merges consecutive successive elements of the game matrix in the Y direction. * If the direction is given as 0, it merges the game matrix to the top * direction. Any other non zero value merges it to the bottom. * * @param matrix The game matrix. * @param opp The direction of the shift. * * @return If the merge was successful */ bool merge_y(unsigned char matrix[][SIZE],bool opp); /** * @brief Moves the elements in Y direction. * * It simply performs shift_y() and merge_y(). * If either of them were successful, it also calls add_random() * * @param matrix The game matrix. * @param opp The direction of the move. * */ void move_y(unsigned char matrix[][SIZE],bool opp); </code></pre> <p><strong>core.c</strong></p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;math.h&gt; #include "../include/core.h" void clear_matrix(unsigned char matrix[][SIZE]) { for (unsigned int x=0;x&lt;SIZE;x++) { for(unsigned int y=0;y&lt;SIZE;y++) { matrix[x][y]=0; } } } int calculate_score(unsigned char matrix[][SIZE]) { int score=0; for (unsigned int x=0;x&lt;SIZE;x++) { for(unsigned int y=0;y&lt;SIZE;y++) { if(matrix[x][y]!=0) { score+=pow(BASE,matrix[x][y]); } } } return score; } void print_matrix(unsigned char matrix[][SIZE],FILE* stream) { for (unsigned int x=0;x&lt;SIZE;x++) { for(unsigned int y=0;y&lt;SIZE;y++) { if (matrix[x][y]) { fprintf(stream,"%d," ,matrix[x][y]); } else{ fprintf(stream,"-,"); } } fprintf(stream,"\n"); } fprintf(stream,"\n"); } void add_random(unsigned char matrix[][SIZE]) { unsigned int pos[SIZE*SIZE]; unsigned int len=0; for(unsigned int x=0;x&lt;SIZE;x++) { for (unsigned int y=0;y&lt;SIZE;y++) { if (matrix[x][y]==0){ pos[len]=x*SIZE+y; len++; } } } unsigned int index=rand() % len; matrix[pos[index]/SIZE][pos[index]%SIZE] = 1; } bool is_game_over(unsigned char matrix[][SIZE]) { for(unsigned int x=0;x&lt;SIZE-1;x++) { for (unsigned int y=0;y&lt;SIZE-1;y++) { if ( matrix[x][y]==matrix[x][y+1] || matrix[x][y]==matrix[x+1][y] || matrix[x][y]==0) {return 0;} } if( matrix[x][SIZE-1]==matrix[x+1][SIZE-1] || matrix[x][SIZE-1]==0) return 0; if( matrix[SIZE-1][x]==matrix[SIZE-1][x+1] || matrix[SIZE-1][x]==0) return 0; } return 1; } bool shift_x(unsigned char matrix[][SIZE], bool opp) { bool moved=0; int start=0,end=SIZE,increment=1; if (opp) { start=SIZE-1; end=-1; increment=-1; } for (int x=0;x&lt;SIZE;x++) { int index=start; for(int y=start;y!=end;y+=increment) { if (matrix[x][y]!=0) { matrix[x][index]=matrix[x][y]; if(index!=y) { matrix[x][y]=0; moved=1; } index+=increment; } } } return moved; } bool merge_x(unsigned char matrix[][SIZE],bool opp) { bool merged=0; int start=0,end=SIZE-1,increment=1; if (opp) { start=SIZE-1; end=0; increment=-1; } for (int x=0;x&lt;SIZE;x++) { int index=start; for(int y=start;y!=end;y+=increment) { if(matrix[x][y]!=0) { if(matrix[x][y]==matrix[x][y+increment]) { matrix[x][index]=matrix[x][y]+1; matrix[x][y+increment]=0; if(index!=y) matrix[x][y]=0; merged=1; index+=increment; } else { matrix[x][index]=matrix[x][y]; if(index!=y) matrix[x][y]=0; index+=increment; } } } if(matrix[x][end]!=0) { matrix[x][index]=matrix[x][end]; if(index!=end) matrix[x][end]=0; } } return merged; } bool merge_y(unsigned char matrix[][SIZE],bool opp) { bool merged=0; int start=0,end=SIZE-1,increment=1; if (opp) { start=SIZE-1; end=0; increment=-1; } for (int y=0;y&lt;SIZE;y++) { int index=start; for(int x=start;x!=end;x+=increment) { if(matrix[x][y]!=0) { if(matrix[x][y]==matrix[x+increment][y]) { matrix[index][y]=matrix[x][y]+1; matrix[x+increment][y]=0; if(index!=x) matrix[x][y]=0; index+=increment; merged=1; } else { matrix[index][y]=matrix[x][y]; if(index!=x) matrix[x][y]=0; index+=increment; } } } if(matrix[end][y]!=0) { matrix[index][y]=matrix[end][y]; if(index!=end) matrix[end][y]=0; } } return merged; } bool shift_y(unsigned char matrix[][SIZE],bool opp) { bool moved=0; int start=0,end=SIZE,increment=1; if (opp) { start=SIZE-1; end=-1; increment=-1; } for (int y=0;y&lt;SIZE;y++) { int index=start; for(int x=start;x!=end;x+=increment) { if (matrix[x][y]!=0) { matrix[index][y]=matrix[x][y]; if(index!=x) { matrix[x][y]=0; moved=1; } index+=increment; } } } return moved; } inline void move_y(unsigned char matrix[][SIZE],bool opp) { //Assigning values insted of evaluating directly to force both operations //Bypassing lazy 'OR' evaluation bool a=shift_y(matrix,opp),b=merge_y(matrix,opp); if( a||b) add_random(matrix); } inline void move_x(unsigned char matrix[][SIZE],bool opp) { //Assigning values insted of evaluating directly to force both operations //Bypassing lazy 'OR' evaluation bool a=shift_x(matrix,opp), b=merge_x(matrix,opp); if(a||b)add_random(matrix); } </code></pre> <p><strong>game.c</strong></p> <pre><code>#include "../include/styles.h" #include "../include/game.h" #include &lt;time.h&gt; #include &lt;stdlib.h&gt; bool initSDL(SDL_Window **gWindow,SDL_Renderer** gRenderer) { bool success = 1; TTF_Init(); if( SDL_Init( SDL_INIT_VIDEO ) &lt; 0 ) { perror( "SDL could not initialize!" ); success = 0; } else { *gWindow = SDL_CreateWindow( "2048", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { perror( "Window could not be created!" ); success = 0; } else { *gRenderer = SDL_CreateRenderer( *gWindow, -1, SDL_RENDERER_ACCELERATED ); if( gRenderer == NULL ) { perror( "Renderer could not be created!" ); success = 0; } else { SDL_SetRenderDrawColor( *gRenderer, g_bg.r,g_bg.g,g_bg.b,g_bg.a ); } } } return success; } void draw_text(SDL_Renderer* gRenderer,TTF_Font* font,const char* text, SDL_Rect rect, SDL_Color color){ SDL_Surface* surfaceMessage = TTF_RenderText_Blended(font, text, color); SDL_Texture* Message = SDL_CreateTextureFromSurface(gRenderer, surfaceMessage); SDL_Rect message_rect; TTF_SizeText(font, text, &amp;message_rect.w, &amp;message_rect.h); message_rect.x = rect.x+rect.w/2-message_rect.w/2; message_rect.y = rect.y+rect.h/2-message_rect.h/2; SDL_RenderCopy(gRenderer, Message, NULL, &amp;message_rect); SDL_DestroyTexture(Message); SDL_FreeSurface(surfaceMessage); } void draw_text_white(SDL_Renderer* gRenderer,TTF_Font* font,const char* text, SDL_Rect rect) { SDL_Color White = {255, 255, 255}; draw_text(gRenderer,font,text,rect,White); } void SDLclose(SDL_Window* gWindow) { SDL_DestroyWindow( gWindow ); gWindow = NULL; TTF_Quit(); SDL_Quit(); } void SDLclear(SDL_Renderer* gRenderer) { SDL_SetRenderDrawColor( gRenderer, g_bg.r,g_bg.g,g_bg.b,g_bg.a ); SDL_RenderClear( gRenderer ); } void display_text(SDL_Renderer* gRenderer,const char* text,int size) { TTF_Font* font =NULL; font= TTF_OpenFont(FONT_PATH, size); if(font==NULL){ perror("The required font was not found"); exit(1); } SDL_Color black = {g_fg.r,g_fg.g, g_fg.b}; SDLclear(gRenderer); SDL_Rect rect = {SCREEN_PAD ,SCREEN_HEIGHT/4 , SCREEN_WIDTH-2*SCREEN_PAD , SCREEN_HEIGHT/2 }; draw_text(gRenderer,font,text,rect,black); SDL_RenderPresent( gRenderer ); SDL_Delay(1000); TTF_CloseFont(font); font=NULL; } void draw_matrix(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font) { int squareSize=(SCREEN_WIDTH - 2*SCREEN_PAD)/SIZE-SCREEN_PAD; for(int x=0;x&lt;SIZE;x++) { for(int y=0;y&lt;SIZE;y++) { SDL_Rect fillRect = { SCREEN_PAD+x*(squareSize+SCREEN_PAD), SCREEN_PAD+y*(squareSize+SCREEN_PAD), squareSize , squareSize }; struct COLOR s=g_COLORS[matrix[y][x]]; SDL_SetRenderDrawColor( gRenderer, s.r, s.g, s.b, s.a ); SDL_RenderFillRect( gRenderer, &amp;fillRect ); char str[15]; // 15 chars is enough for 2^16 sprintf(str, "%d", (int)pow(BASE,matrix[y][x])); if(matrix[y][x]==0){ str[0]=' '; str[1]='\0'; } draw_text_white(gRenderer,font,str,fillRect); } } } void handle_move(SDL_Event e,unsigned char matrix[][SIZE], SDL_Renderer * gRenderer) { if(is_game_over(matrix)) { display_text(gRenderer,"Game Over",GOVER_FONT_SIZE); clear_matrix(matrix); add_random(matrix); return; } switch(e.key.keysym.sym) { case SDLK_UP: move_y(matrix,0); break; case SDLK_DOWN: move_y(matrix,1); break; case SDLK_LEFT: move_x(matrix,0); break; case SDLK_RIGHT: move_x(matrix,1); break; default:; } } void draw_button(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font) { char txt[]="New Game"; SDL_Rect fillRect = { SCREEN_PAD/2 , SCREEN_WIDTH+SCREEN_PAD , SCREEN_WIDTH/2-2*SCREEN_PAD , (SCREEN_HEIGHT-SCREEN_WIDTH)-2*SCREEN_PAD }; SDL_SetRenderDrawColor( gRenderer,g_button_bg.r, g_button_bg.g, g_button_bg.b,g_button_bg.a ); SDL_RenderFillRect( gRenderer, &amp;fillRect ); draw_text_white(gRenderer,font,txt,fillRect); } void button_action(SDL_Event e,unsigned char matrix[][SIZE]) { SDL_Rect draw_rect = { SCREEN_PAD/2 , SCREEN_WIDTH+SCREEN_PAD , SCREEN_WIDTH/2-2*SCREEN_PAD , SCREEN_HEIGHT-SCREEN_WIDTH-2*SCREEN_PAD }; if(e.button.button == SDL_BUTTON_LEFT &amp;&amp; e.button.x &gt;= draw_rect.x &amp;&amp; e.button.x &lt;= (draw_rect.x + draw_rect.w) &amp;&amp; e.button.y &gt;= draw_rect.y &amp;&amp; e.button.y &lt;= (draw_rect.y + draw_rect.h)) { clear_matrix(matrix); add_random(matrix); } } void draw_score(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font) { char score[15]; //15 chars is enough for score. sprintf(score, "%d", calculate_score(matrix)); char scoreText[30]="Score:"; strncat(scoreText,score,15); SDL_Rect fillRect = { SCREEN_WIDTH/2+5, SCREEN_WIDTH+SCREEN_PAD, SCREEN_WIDTH/2-2*SCREEN_PAD, SCREEN_HEIGHT-SCREEN_WIDTH-2*SCREEN_PAD }; SDL_SetRenderDrawColor( gRenderer,g_score_bg.r,g_score_bg.g,g_score_bg.b,g_score_bg.a ); SDL_RenderFillRect( gRenderer, &amp;fillRect ); draw_text_white(gRenderer,font,scoreText,fillRect); } void render_game(SDL_Renderer* gRenderer,unsigned char matrix[][SIZE], TTF_Font* font) { SDLclear(gRenderer); draw_matrix(gRenderer,matrix,font); draw_score(gRenderer,matrix,font); draw_button(gRenderer,matrix,font); SDL_RenderPresent( gRenderer ); } void gameLoop(unsigned char matrix[][SIZE],SDL_Renderer* gRenderer) { TTF_Font* font =NULL; font= TTF_OpenFont(FONT_PATH, CELL_FONT_SIZE); if(font==NULL){ perror("The required font was not found"); exit(1); } render_game(gRenderer,matrix,font); bool quit=0; SDL_Event e; while (!quit) { while( SDL_PollEvent( &amp;e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = 1; } else if(e.type==SDL_KEYUP) { handle_move(e,matrix,gRenderer); //Redraw all portions of game render_game(gRenderer,matrix,font); } else if(e.type==SDL_MOUSEBUTTONUP) { button_action(e,matrix); render_game(gRenderer,matrix,font); } } } TTF_CloseFont(font); //No need to null out font. } int main(int argc,char** argv) { //Set up the seed srand(time(NULL)); //Set up the game matrix. unsigned char matrix[SIZE][SIZE]; clear_matrix(matrix); add_random(matrix); //Init the SDL gui variables SDL_Window* gWindow = NULL; SDL_Renderer* gRenderer = NULL; if(!initSDL(&amp;gWindow,&amp;gRenderer)){exit(0);}; display_text(gRenderer,"2048",TITLE_FONT_SIZE); gameLoop(matrix,gRenderer); //Releases all resource SDLclose(gWindow); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T19:57:45.440", "Id": "406780", "Score": "3", "body": "This is a great question and I enjoyed reading it and the review. Just a note: only the code embedded directly into the question is eligible for review. (The GitHub link can stay for anyone interested in viewing it *BUT* it isn't valid for review.) If you want a review of the updated code it is perfectly acceptable to post a new question when you've implemented the changes. We love iterative reviews especially on fun questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:53:04.813", "Id": "406794", "Score": "1", "body": "Maybe irrelevant to your need, but can I make 2048 with javascript as frontend and python as backend?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T01:58:13.723", "Id": "406819", "Score": "2", "body": "@austingae 2048 was originally written in javascript. It was a single player game so no backend was used. But you can easily use a python backend and make a (multiplayer) 2048 with leaderboards and other modes/variants." } ]
[ { "body": "<p>Well done. This is not a complete review, but instead a (short) list of possible improvements I found when I skimmed your code.</p>\n\n<h1>Documentation</h1>\n\n<p>First of all: <strong><em>thank you!</em></strong> It's great to have documentation. </p>\n\n<p>Note that there is some debate whether to put the documentation into the header or the source. I'd like to remark that I would put only a <code>@brief</code> description in the header and a complete documentation into the source. That way, one can get a quick overview of all functions and look into the details if they found the correct one. However, that's <strong>personal preference</strong>, and in a team project you would stick to whatever guideline is already present. The generated documentation by doxygen will stay the same, either way.</p>\n\n<h1>Matrices and <code>arr[][SIZE]</code></h1>\n\n<p>While it's possible to model a matrix this way, it's inflexible. The game is now stuck at a size that was chosen when it was compiled. If you want to enable other board sizes, you have to add some logic to keep the board in the matrix anyway, so a variable <code>SIZE</code> will be necessary. Also, interesting boards like 4x6 are downright impossible at the moment.</p>\n\n<p>Furthermore, there is a lot of duplication, as <code>unsigned char matrix[][SIZE]</code> is everywhere in the code. If you <em>really</em> want to follow the approach, use a type alias:</p>\n\n<pre><code>typedef unsigned char board_type[][SIZE];\n</code></pre>\n\n<p>However, with arbitrary board sizes in mind, you probably want to introduce a proper matrix type at some point:</p>\n\n<pre><code>struct board_type {\n unsigned width;\n unsigned height;\n unsigned char * actual_board;\n};\n</code></pre>\n\n<p>Whether you use a single allocated <code>malloc(sizeof(*actual_board)*SIZE*SIZE)</code> or <code>SIZE</code> times <code>malloc(sizeof(*actual_board)*SIZE)</code> is, at least for small sizes, not important. The former is easier to handle in terms of memory, the latter is easier in terms of access.</p>\n\n<p>In case you ever want to swap between those, a set of small <code>inline</code> function can come in handy:</p>\n\n<pre><code>unsigned char board_get(struct board_type *board, unsigned row, unsigned col) {\n assert(row &lt; board-&gt;height);\n assert(col &lt; board-&gt;width);\n return board-&gt;actual_board[row * board-&gt;width + col];\n // or, if actual_board is a `unsigned char**`\n return board-&gt;actual_board[row][col];\n}\n\nvoid board_set(struct board_type *board, unsigned row, unsigned col, unsigned char value) {\n assert(row &lt; board-&gt;height);\n assert(col &lt; board-&gt;width);\n board-&gt;actual_board[row * board-&gt;width + col] = value;\n // or, if actual_board is a `unsigned char**`\n board-&gt;actual_board[row][col] = value;\n}\n</code></pre>\n\n<h1><code>pow</code> is not for integers</h1>\n\n<p>The <code>pow</code> function takes a <code>double</code> for both arguments, and that's fine. However, it's a complete overkill for simple integers. <a href=\"https://codereview.stackexchange.com/questions/145221/disproving-euler-proposition-by-brute-force-in-c/145228#145228\">In a past review, I share some more details,</a> but for your game a simple bitshift is enough:</p>\n\n<pre><code>unsigned long pow_integral(unsigned char base, unsigned char exponent) {\n if(base == 2) {\n return (1lu &lt;&lt; exponent);\n } else {\n // exercise; use \"double-and-add\" method for logarithmic speed\n }\n}\n</code></pre>\n\n<h1>No magic numbers</h1>\n\n<p>Just like documentation, this is a great feature of your code. There are no magic numbers in the code, every number is properly <code>define</code>d to provide some self-documentation. However, some comments on <code>#define</code>s are usually expected, and Doxygen <em>should</em> give out some warnings.</p>\n\n<p>There is a single magic number, though, in <code>main</code>. See \"blindness\" below.</p>\n\n<h1>C99 has <code>bool</code></h1>\n\n<p>That being said, occasionally there is <code>bool success = 1</code> or <code>0</code>. Due to <code>bool</code>, it's clear that they mean <code>true</code> and <code>false</code>. You could, however, just <code>#include &lt;stdbool.h&gt;</code> and instead use the language defined boolean.</p>\n\n<h1>Tabs and spaces</h1>\n\n<p>There are tabs and spaces mixed in the code. It's not evident in the code here on StackExchange, but on GitHub. You probably want to fix this, as several editors use 8 spaces for tabs, not 4.</p>\n\n<h1><code>perror</code> is not for general errors</h1>\n\n<p><a href=\"https://en.cppreference.com/w/c/io/perror\" rel=\"nofollow noreferrer\"><code>perror</code></a> will show the user supplied string, as well as a textual description of the error code stored on <strong><em><code>errno</code></em></strong>. None of the SDL functions set <code>errno</code> as far as I know, so <code>perror</code> won't report the correct errors.</p>\n\n<p>Instead, use <code>printf</code> or <code>fprintf</code> and <a href=\"https://wiki.libsdl.org/SDL_GetError\" rel=\"nofollow noreferrer\"><code>SDL_GetError</code></a>.</p>\n\n<h1>Early returns</h1>\n\n<p>Some of your functions have a return code ready, for example <code>initSDL</code>:</p>\n\n<pre><code>bool initSDL(SDL_Window **gWindow,SDL_Renderer** gRenderer)\n{\n bool success = 1;\n TTF_Init();\n if( SDL_Init( SDL_INIT_VIDEO ) &lt; 0 )\n {\n perror( \"SDL could not initialize!\" );\n success = 0;\n }\n else\n {\n *gWindow = SDL_CreateWindow( \"2048\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );\n if( gWindow == NULL )\n {\n perror( \"Window could not be created!\" );\n success = 0;\n }\n else\n {\n *gRenderer = SDL_CreateRenderer( *gWindow, -1, SDL_RENDERER_ACCELERATED );\n if( gRenderer == NULL )\n {\n perror( \"Renderer could not be created!\" );\n success = 0;\n }\n else\n {\n SDL_SetRenderDrawColor( *gRenderer, g_bg.r,g_bg.g,g_bg.b,g_bg.a );\n\n }\n }\n }\n\n return success;\n}\n</code></pre>\n\n<p>This code suffers a little bit from the <a href=\"https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)\" rel=\"nofollow noreferrer\">pyramid of doom</a>. However, in none of the <code>if</code>s do we actually clean up resources, so we can instead write the following:</p>\n\n<pre><code>bool initSDL(SDL_Window **gWindow,SDL_Renderer** gRenderer)\n{\n TTF_Init();\n if( SDL_Init( SDL_INIT_VIDEO ) &lt; 0 )\n {\n fprintf(stderr, \"SDL could not initialize: %s\\n\", SDL_GetError());\n return false;\n }\n *gWindow = SDL_CreateWindow( \"2048\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );\n if( gWindow == NULL )\n {\n fprintf(stderr, \"Window could not be created: %s\\n\", SDL_GetError());\n return false;\n }\n *gRenderer = SDL_CreateRenderer( *gWindow, -1, SDL_RENDERER_ACCELERATED );\n if( gRenderer == NULL )\n {\n fprintf(stderr, \"Renderer could not be created: %s\\n\", SDL_GetError());\n // What about gWindow?\n // We should probably do something about it\n return false;\n }\n SDL_SetRenderDrawColor( *gRenderer, g_bg.r,g_bg.g,g_bg.b,g_bg.a );\n}\n</code></pre>\n\n<h1>Resource management and boolean blindness</h1>\n\n<p>As hinted in the code above, when <code>CreateWindow</code> succeeds but <code>CreateRenderer</code> fails, the <code>gWindow</code> isn't properly destroyed. Furthermore, <code>initSDL</code>'s caller cannot find out <em>why</em> the initialization failed. Enums are usually the solution in that circumstance, at least as long as we don't clean up.</p>\n\n<p>That being said, <code>exit(0)</code> in <code>main</code> is off. A zero exit value indicates that the game was able to run and exit. However, if <code>initSDL</code> fails, then the game cannot run, and we should probably report that to the operating system:</p>\n\n<pre><code>if(!initSDL(&amp;gWindow,&amp;gRenderer)){exit(EXIT_FAILURE);};\n</code></pre>\n\n<h1>Always use (proper) blocks for <code>if</code>s</h1>\n\n<p>However, the line is strange for another reason: it doesn't follow your usual indentation. Let's fix that:</p>\n\n<pre><code>if(!initSDL(&amp;gWindow,&amp;gRenderer)){\n exit(EXIT_FAILURE);\n}; // &lt;&lt;--- ?\n</code></pre>\n\n<p>There was a stray semicolon. While it's not an error, it indicates that the code was previously <code>if(!initSDL(&amp;gWindow,&amp;gRenderer))exit(0);</code>, then some things got changed, and changed back.</p>\n\n<p>If you use braces all the time (with proper indentation), it's easier to see conditionals, so make sure to make the code as clean as possible.</p>\n\n<h1>Readability</h1>\n\n<p>The compiler doesn't care whether you write</p>\n\n<pre><code>a=foo(), b=too(), c=quux()+a*b; if(a&lt;b)c-=t;\n</code></pre>\n\n<p>but a human will have a hard time. Make your code easy for humans too:</p>\n\n<pre><code>a = foo();\nb = too();\nc = quux() + a * b;\n\nif ( a &lt; b ) {\n c -= t;\n}\n</code></pre>\n\n<p>At least <code>move_x</code> and <code>move_y</code> can be improved that way.</p>\n\n<h1>Naming</h1>\n\n<p>In computer sciences, there are two hard problems: naming, caches and off-by one errors. Here we focus on the first one.</p>\n\n<h2>Use prefixes only if they have a meaning</h2>\n\n<p>The <code>gRenderer</code> and <code>gWindow</code> have a <code>g</code> prefix that's not explained. None of the other variables have a prefix.</p>\n\n<p>If <code>g</code> is a common prefix for SDL objects, then it's fine, however, I <em>guess</em> it's for <code>g</code>ame. However, it's strange that the board itself then is prefix-free.</p>\n\n<p>That being said...</p>\n\n<h2>Name by function, not by form</h2>\n\n<p>The board is called <code>matrix</code> throughout the whole game. However, <code>matrix</code> is a term from Mathematics or a film title, but doesn't quite fit the \"board\" function. <code>board</code> on the other hand would be a perfect name. Also, the plural is a lot easier, in case you ever want to implement a variant where the player plays on two boards at the same time.</p>\n\n<h2>Don't surprise the others</h2>\n\n<p>The <code>SDLclose</code> and <code>SDLclear</code> took me by surprise. Both functions don't follow the usual <code>SDL_&lt;name&gt;</code> approach, because both aren't from <code>SDL</code>.</p>\n\n<p>In C++, you would put those functions into your own namespace, but in C, use a prefix that you defined. Alternatively, follow the <code>initSDL</code> approach and call the functions <code>clearSDL</code> and <code>closeSDL</code>. Those names are completely unambiguous.</p>\n\n<h1>Symmetry between creation and destruction</h1>\n\n<p>There is something amiss in <code>SDLclose</code>:</p>\n\n<pre><code>void SDLclose(SDL_Window* gWindow)\n{\n SDL_DestroyWindow( gWindow );\n gWindow = NULL;\n TTF_Quit();\n SDL_Quit();\n}\n</code></pre>\n\n<p>Given that we act on a local pointer, <code>gWindow = NULL</code> isn't visible from the outside. This is probably just a small mistake. However, if <code>SDLclos</code> and <code>initSDL</code> were to be used in a symmetric way, we'd end up with</p>\n\n<pre><code>void SDLclose(SDL_Window** gWindow)\n{\n SDL_DestroyWindow( *gWindow );\n *gWindow = NULL;\n TTF_Quit();\n SDL_Quit();\n}\n</code></pre>\n\n<p>Here, <code>*gWindow = NULL</code> makes sense. However, as <code>SDLclose</code> is one of the few functions that don't have accommodating documentation, it's not clear what the intended behaviour is, so I'd stick to the former, e.g. </p>\n\n<pre><code>/**\n * @brief Destroy the @a gWindow and quit SDL.\n *\n * @param gWindow is the window that will be destroyed.\n*/\nvoid SDLclose(SDL_Window* gWindow)\n{\n //! @warning `gWindow` **must not** be used afterwards.\n SDL_DestroyWindow( gWindow );\n TTF_Quit();\n SDL_Quit();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T15:15:47.393", "Id": "406729", "Score": "0", "body": "Thank you for the excellent review! I didn't think about bitshifts or `pow()`'s runtime. `SDL_GetError` was also a very helpful and specific comment. I was pretty sure I had removed all magic numbers. I didn't realize `exit(0/1)` could be removed as well. It was a pleasant surprise. I selected the `matrix[][SIZE]` format in the view that I would never fiddle with non-square boards. But, now that you mention it, it seems fun to implement. Thank you once again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T22:00:36.627", "Id": "406804", "Score": "0", "body": "Not the OP, but can you explain: \"Whether you use a single allocated malloc(sizeof(*actual_board)*SIZE*SIZE) or SIZE times malloc(sizeof(*actual_board)*SIZE) is, at least for small sizes, not important. The former is easier to handle in terms of memory, the latter is easier in terms of access. \", specifically why the latter is easier in terms of access." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T02:19:37.630", "Id": "406820", "Score": "0", "body": "The SDLclose function definitely contains a bug. I had fixed that in the latest revision but changes were still left here. Maybe I will post the updated question after some implementation changes in a few weeks. It is also scary how well you understood the code. I really appreciate the time you game for this review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:10:46.867", "Id": "406837", "Score": "0", "body": "@MarDev Sure. The first one will lead to a `TYPE * matrix`. The valid indices are now \\$0,1,\\ldots,\\text{N}^2-1\\$. This is very handy for resetting, as you only need `memset`, but now you need `matrix[row + column * N]` or similar. The latter leads to `TYPE **matrix`. We now have an indirection and must use `matrix[i][j]`. This is a lot easier if you want to use positions, as we don't have to transform \\$\\{0,\\ldots\\,N-1\\}\\times\\{0,\\ldots\\,N-1\\}\\to\\{0,\\ldots,N^2-1\\}\\$ by hand with \\$ind = xN+y\\$. However, the is unlikely to be continuous anymore. I've added examples to the answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:26:43.937", "Id": "210419", "ParentId": "210408", "Score": "23" } }, { "body": "<p>Adding to @Zeta's excellent answer.</p>\n\n<hr>\n\n<h1>Whitespace</h1>\n\n<p>Your whitespace policy is pretty inconsistent. Sometimes you call functions like this:</p>\n\n<pre><code>SDL_SetRenderDrawColor( *gRenderer, g_bg.r,g_bg.g,g_bg.b,g_bg.a );\n</code></pre>\n\n<p>with spaces just inside the <code>()</code>, while other times you call them like this:</p>\n\n<pre><code>TTF_SizeText(font, text, &amp;message_rect.w, &amp;message_rect.h);\n</code></pre>\n\n<p>with no spaces inside. Similarly, you sometimes put spaces after commas, as above, and other times you don't, like here:</p>\n\n<pre><code>display_text(gRenderer,\"2048\",TITLE_FONT_SIZE);\ngameLoop(matrix,gRenderer);\n</code></pre>\n\n<p>On some lines you mix the two styles, like here:</p>\n\n<pre><code>struct COLOR g_COLORS[]={\n {230, 227, 232,255},\n {255, 127, 89,255},\n // etc.\n};\n</code></pre>\n\n<p>Sometimes you put spaces around arithmetic operators, but you usually don't.</p>\n\n<pre><code>int squareSize=(SCREEN_WIDTH - 2*SCREEN_PAD)/SIZE-SCREEN_PAD;\n</code></pre>\n\n<p>You also sometimes associate pointers with the type, and other times with the variable:</p>\n\n<pre><code>bool initSDL(SDL_Window **gWindow,SDL_Renderer** gRenderer)\n</code></pre>\n\n<p>Lastly, in your header you sometimes have two blank lines separating docstring-forward-declaration pairs, and sometimes you have just one.</p>\n\n<p>I would encourage you to use <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\"><code>clang-format</code></a> to keep your style consistent.</p>\n\n<h1>Correctness</h1>\n\n<p>Code like this <em>always</em> has bugs, even if they're just theoretical portability bugs. It's best to get out of the habit of writing it, even if it's working on your computer.</p>\n\n<pre><code>char score[15]; //15 chars is enough for score.\nsprintf(score, \"%d\", calculate_score(matrix));\nchar scoreText[30]=\"Score:\";\nstrncat(scoreText,score,15);\n</code></pre>\n\n<p>In particular, the C standard <em>allows</em> <code>int</code> to occupy more than 4 bytes. Instead, you should either ask <code>snprintf</code> for the length at runtime and allocate yourself or use <a href=\"http://man7.org/linux/man-pages/man3/asprintf.3.html\" rel=\"nofollow noreferrer\"><code>asprintf</code></a> (which is a GNU extension). To ask <code>snprintf</code> for the required buffer size, give it a null pointer and zero length, like so:</p>\n\n<pre><code>int score = calculate_score(matrix);\nint score_bufsize = snprintf(NULL, 0, \"Score: %d\", score);\nchar* score_str = malloc(score_bufsize * sizeof(*score));\nif (!score_str) {\n perror(\"malloc\");\n exit(EXIT_FAILURE);\n}\n\nsnprintf(score_str, score_bufsize, \"Score: %d\", score);\n\n// ...\n\ndraw_text_white(gRenderer,font,score_str,fillRect);\nfree(score_str);\n</code></pre>\n\n<p>This pattern is made easier if you're willing to use GNU extensions, as in:</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;stdio.h&gt;\n\n// ...\n\nint score = calculate_score(matrix);\n\nchar* score_str;\nif (asprintf(&amp;score_str, \"Score: %d\", score) &lt; 0) {\n perror(\"asprintf\");\n exit(EXIT_FAILURE);\n}\n\n// ...\n\ndraw_text_white(gRenderer,font,score_str,fillRect);\nfree(score_str);\n</code></pre>\n\n<p>Of course, you could always just use <code>snprintf</code> with a fixed size buffer and just truncate when things get too large.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:09:09.210", "Id": "406847", "Score": "0", "body": "I will take clang-format into consideration next time I write something. It seems most of the issues can be prevented just by using a better build system/IDE. Also, setting buffer size at runtime is definitely the way to go here. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T08:28:27.330", "Id": "210469", "ParentId": "210408", "Score": "3" } }, { "body": "<p>Since the other reviews have already hit most points, I'll just mention a few not already covered. </p>\n\n<h2>Avoid relative paths in <code>#include</code>s</h2>\n\n<p>Generally it's better to omit relative path names from <code>#include</code> files and instead point the compiler to the appropriate location. So instead of this:</p>\n\n<pre><code>#include \"../include/styles.h\"\n#include \"../include/game.h\"\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>#include \"styles.h\"\n#include \"game.h\"\n</code></pre>\n\n<p>This makes the code less dependent on the actual file structure, and leaving such details in a single location: a <code>Makefile</code> or compiler configuration file. With <code>cmake</code>, we can use <code>include_directories</code>. Since you've already got that in your toplevel <code>CMakeLists.txt</code>, just append the <code>include</code> directory in that <code>CMake</code> directive.</p>\n\n<h2>Understand how <code>#include</code> works</h2>\n\n<p>On most platforms, the difference between <code>#include \"math.h\"</code> and <code>#include &lt;math.h&gt;</code> is that the former looks first in the current directory. So for system files such as <code>SDL2/SDL.h</code>, you should really use <code>#include &lt;SDL2/SDL.h&gt;</code> instead. See <a href=\"http://stackoverflow.com/questions/3162030/difference-between-angle-bracket-and-double-quotes-while-including-heade\">this question</a> for more details.</p>\n\n<p>In many cases, it's likely that either will work, but to the human reader convention is that files in your project use <code>\"\"</code> while system includes (files not in your project) use <code>&lt;&gt;</code>. That's an imprecise differentiation, but a useful way to think about it.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The <code>merge_x</code> and <code>merge_y</code> functions are almost identical. I think it would make sense to combine them into a single <code>merge</code> function that would take a direction as an additional parameter. The same approach can be taken with the <code>shift</code> and <code>move</code> functions.</p>\n\n<p>For example, here's a combined <code>shift()</code> function that takes an extra parameter indicating <code>ydir</code>:</p>\n\n<pre><code>bool shift(Board board, bool opp, bool ydir)\n{\n bool moved=false;\n int start=0,end=SIZE,increment=1;\n if (opp)\n {\n start=SIZE-1;\n end=-1;\n increment=-1;\n }\n for (int a=0;a&lt;SIZE;a++)\n {\n int index=start;\n for(int b=start;b!=end;b+=increment)\n {\n int x = ydir ? b : a;\n int y = ydir ? a : b;\n if (board[x][y]!=0)\n {\n if (ydir) {\n board[index][y]=board[x][y];\n } else {\n board[x][index]=board[x][y];\n }\n if(index!=b) {\n board[x][y]=0;\n moved=true;\n }\n index+=increment;\n }\n }\n }\n return moved;\n}\n</code></pre>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>Board</code> is not and should not be altered by the <code>print_board</code> function. For that reason, I would advise changing the signature of the function to this:</p>\n\n<pre><code>void print_board(const Board board, FILE* stream);\n</code></pre>\n\n<p>A similar change can be made to <code>is_game_over</code> and <code>calculate_score</code></p>\n\n<h2>Don't leak memory</h2>\n\n<p>The SDL interface is hard to use correctly without leaking memory, because it isn't always readily apparent which functions allocate and which functions de-allocate. In this code, <code>initSDL</code> creates a <code>renderer</code> but never calls <code>SDL_DestroyRenderer</code>. I'd recommend adding a pointer to the renderer as a parameter to <code>closeSDL</code> and making sure it's non-NULL before calling <code>SDL_DestroyRenderer</code>.</p>\n\n<h2>Simplify code</h2>\n\n<p>The code currently contains this function:</p>\n\n<pre><code>inline void move_x(Board board, bool opp)\n{\n //Assigning values insted of evaluating directly to force both operations\n //Bypassing lazy 'OR' evaluation\n bool a=shift_x(board,opp), b=merge_x(board,opp);\n if(a||b)add_random(board);\n}\n</code></pre>\n\n<p>It could be more clearly written as:</p>\n\n<pre><code>inline void move_x(Board board, bool opp)\n{\n bool move_or_shift = shift_x(board,opp);\n move_or_shift |= merge_x(board,opp);\n if (move_or_shift) {\n add_random(board);\n }\n}\n</code></pre>\n\n<h2>Think of the user</h2>\n\n<p>There are a few small enhancements that would make the game better. First is to allow the user to see and savor the high score instead of immediately launching a new game. Second would be to detect whether any moves are <em>possible</em> rather than waiting for the user to attempt to move before evaluating this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T03:17:06.420", "Id": "406980", "Score": "0", "body": "Great review! One thing I would like to be clarified is the DRY principle. I tried to make a single function for shift instead of shift_x and shift_y. Could you show me if that is possible? I thought about repeating code for clarity instead of writing a complex shift function. How would you go about this? Also for the **Simplify Code** section. I didn't get what you mean. You just provided the code and I think the function is simple enough. How could I make it simpler? Thank you once more!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T03:39:09.273", "Id": "406981", "Score": "0", "body": "About the includes. I am rather inconsistent with the style but isn't it almost always better to write \" \" instead of <>? Especially since `#include \"SDL2/SDL2.h\"` fallbacks to `#include <SDL2/SDL2.h>` if nothing is found in the source directory. Therefore, the user can provide his own implementation of \"math\" and \"time\" for example if need be. Maybe reduce file size by only providing certain functions of the library and so on. Is there any advantage to using < >?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T04:04:43.443", "Id": "406983", "Score": "1", "body": "I've added to my answer to try to answer all of your questions. If anything's still not clear, please ask again." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:31:55.977", "Id": "210505", "ParentId": "210408", "Score": "4" } } ]
{ "AcceptedAnswerId": "210419", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T08:14:23.853", "Id": "210408", "Score": "25", "Tags": [ "c", "game", "gui", "sdl", "2048" ], "Title": "2048 with GUI in C" }
210408
<p>This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.</p> <p>The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.</p> <p>It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.</p> <p>I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.</p> <pre><code>import os # Declare Functions def jsonStart(): return "{\n" def jsonEnd(indent): return "\n" + jsonIndent(indent) + "}" def jsonIndent(amount): amount = amount * 4 return " " * amount def jsonKeyValue(key, value, indent = 0): return jsonIndent(indent) + jsonKey(key) + jsonValue(value) def jsonKey(key, indent = 0): return jsonIndent(indent) + "\"" + key + "\"" + ": " def jsonValue(value): return "\"" + value + "\"" def deleteCreatedFiles(): print("\nSomething went wrong") for file in createdFiles: print("Deleting: " + file) os.remove(file) print("\n") def createFile(filename, data): try: os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w+")as newFile: newFile.write(data) except: deleteCreatedFiles() raise else: createdFiles.append(os.path.relpath(newFile.name)) print("Created" + os.path.relpath(newFile.name)) def blockStatesFile(): data = jsonStart() data += jsonKey("variants", 1) + jsonStart() data += jsonKey("normal", 2) + "{ " + jsonKeyValue("model", modid + ":" + blockName) + "}" data += jsonEnd(1) data += jsonEnd(0) return data def modelsItemFile(): data = jsonStart() data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",\n" data += jsonKey("textures", 1) + jsonStart() data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2) data += jsonEnd(1) data += jsonEnd(0) return data def modelsBlockFile(): data = jsonStart() data += jsonKeyValue("parent", "block/cube_all", 1) + ",\n" data += jsonKey("textures", 1) + jsonStart() data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2) data += jsonEnd(1) data += jsonEnd(0) return data # Run Script createdFiles = [] blockName = input("block name: ") modid = input("modid: ") createFile("blockstates/" + blockName + ".json", blockStatesFile()) createFile("models/item/" + blockName + ".json", modelsItemFile()) createFile("models/block/" + blockName + ".json", modelsBlockFile()) </code></pre>
[]
[ { "body": "<p>If all you need is <em>just readability and maintainability, and general best practice</em>, don't reinvent the wheel. You have the <a href=\"https://docs.python.org/3/library/json.html\" rel=\"noreferrer\">json</a> library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).</p>\n\n<p>I rewrote your code and you have the opportunity to compare them:</p>\n\n<pre><code>import os, json\n\n# Declare Functions\ndef deleteCreatedFiles():\n print(\"\\nSomething went wrong\")\n for file in createdFiles:\n print(\"Deleting: \" + file)\n os.remove(file)\n print(\"\\n\")\n\ndef createFile(filename, data):\n try:\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"w+\") as newFile:\n jstr = json.dumps(data, indent=4)\n newFile.write(jstr)\n except:\n deleteCreatedFiles()\n raise\n else:\n createdFiles.append(os.path.relpath(newFile.name))\n print(\"Created\" + os.path.relpath(newFile.name))\n\ndef blockStatesFile():\n return {\n 'variants': {\n 'normal': {\n 'model': modid + \":\" + blockName\n }\n }\n }\n\ndef modelsItemFile():\n return {\n 'parent': modid + \":block/\" + blockName,\n 'textures': {\n 'layer0': modid + \":items/\" + blockName\n }\n }\n\ndef modelsBlockFile():\n return {\n 'parent': 'block/cube_all',\n 'textures': {\n 'all': modid + \":blocks/\" + blockName\n }\n }\n\n# Run Script\ncreatedFiles = []\nblockName = input(\"block name: \")\nmodid = input(\"modid: \")\ncreateFile(\"blockstates/\" + blockName + \".json\", blockStatesFile())\ncreateFile(\"models/item/\" + blockName + \".json\", modelsItemFile())\ncreateFile(\"models/block/\" + blockName + \".json\", modelsBlockFile())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:01:44.783", "Id": "406693", "Score": "0", "body": "This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:05:18.987", "Id": "406694", "Score": "2", "body": "With Python 3.6 and f-strings: `f\"{modid}:{blockName}\"`, `f\"blockstates/{blockName}.json\"`, ... are a bit shorter and more readable IMO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:34:32.343", "Id": "406701", "Score": "0", "body": "@Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T11:52:08.730", "Id": "210418", "ParentId": "210414", "Score": "10" } }, { "body": "<p>I won't repeat <a href=\"https://codereview.stackexchange.com/a/210418/84718\">@victor's answer</a>, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.</p>\n\n<p>Python also comes with an official style guide: <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which is advised to follow if you want your code to look like Python code to others.</p>\n\n<p>Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.</p>\n\n<p>Lastly, you should avoid keeping code at the top-level of the file, protect it with an <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__'</code></a> guard:</p>\n\n<pre><code>import os\nimport json\n\n\ndef delete_files(files):\n for filename in files:\n os.remove(filename)\n\n\ndef create_file(filename, data, created_files):\n try:\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"w+\") as new_file:\n json.dump(data, new_file, indent=4)\n except:\n print(\"\\nSomething went wrong\")\n print(\"Deleting:\", *created_files)\n print(\"\\n\")\n delete_files(created_files)\n raise\n else:\n filepath = os.path.relpath(new_file.name)\n created_files.append(filepath)\n print(\"Created\", filepath)\n\n\ndef block_states(modid, block_name):\n return {\n 'variants': {\n 'normal': {\n 'model': f'{modid}:{block_name}',\n },\n },\n }\n\n\ndef models_item(modid, block_name):\n return {\n 'parent': f'{modid}:block/{block_name}',\n 'textures': {\n 'layer0': f'{modid}:items/{block_name}',\n },\n }\n\n\ndef models_block(modid, block_name):\n return {\n 'parent': 'block/cube_all',\n 'textures': {\n 'all': f'{modid}:blocks/{block_name}',\n },\n }\n\n\ndef main(modid, block_name): \n created_files = []\n create_file(\n f'blockstates/{block_name}.json',\n block_states(modid, block_name),\n created_files)\n create_file(\n f'models/item/{block_name}.json',\n models_item(modid, block_name),\n created_files)\n create_file(\n f'models/block/{block_name}.json',\n models_block(modid, block_name),\n created_files)\n\n\nif __name__ == '__main__':\n block_name = input(\"block name: \")\n modid = input(\"modid: \")\n main(modid, block_name)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T13:50:02.840", "Id": "406704", "Score": "0", "body": "Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if __name__ == '__main__': and the official style guide updates" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:59:06.963", "Id": "210423", "ParentId": "210414", "Score": "13" } } ]
{ "AcceptedAnswerId": "210423", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T10:40:26.607", "Id": "210414", "Score": "16", "Tags": [ "python", "beginner", "json", "minecraft" ], "Title": "Minecraft block generator" }
210414
<p>I recently ported a blog of mine from Python to Go (to improve speed and performance) and while all is great so far, I'd like some help optimising the <code>Markdown</code> function to improve the general performance, maintenance and readability of the function.</p> <p>I have this function because I write my blog articles in Markdown (<code>.md</code>) and then use <s>Python</s> Go to convert the raw Markdown to HTML for output as this saves me from having to write ridiculous amounts of HTML. (which can be tedious to say the least)</p> <p>The <code>Markdown</code> function takes one argument (<code>raw</code>) which is a string that contains the raw Markdown (obtained using <code>ioutil.ReadFile</code>).</p> <p>It then splits the Markdown by <code>\n</code> (removing the empty lines) and converts:</p> <ul> <li>Bold and italic text (***,**,*)</li> <li>Strikethrough text (~~blah blah blah~~)</li> <li>Underscored text (__blah blah blah__)</li> <li>Links ([https://example.com](Example Link))</li> <li>Blockquotes (> sample quote by an important person)</li> <li>Inline code (`abcccc`)</li> <li>Headings (h1-h6)</li> </ul> <p>While some of the supported features aren't exactly standard, this function works and outputs the expected result without any errors but being a new Go programmer and this being my first <em>"real"</em> Go project I'd like to know whether or not my code could be optimised for better performance, maintainability and readability.</p> <p>Here a few questions I have regarding optimisation:</p> <ul> <li>Would it make a difference to performance if I reduced the amount of imports?</li> <li>Would it improve readability if I put the <code>regexp.MustCompile</code> functions into variables above the <code>Markdown</code> function?</li> <li>Would it improve performance if I used individual regexes to convert Markdown headings instead of using <code>for i := 6; i &gt;= 1; i-- {...}</code>?</li> <li>If not, is there a way to convert <code>i</code> (an integer) to a string without using <code>strconv.Itoa(i)</code> (to help reduce the amount of imports)?</li> </ul> <p>Here is my code:</p> <pre><code>package parse import ( "regexp" "strings" "strconv" ) func Markdown(raw string) string { // ignore empty lines with "string.Split(...)" lines := strings.FieldsFunc(raw, func(c rune) bool { return c == '\n' }) for i, line := range lines { // wrap bold and italic text in "&lt;b&gt;" and "&lt;i&gt;" elements line = regexp.MustCompile(`\*\*\*(.*?)\*\*\*`).ReplaceAllString(line, `&lt;b&gt;&lt;i&gt;$1&lt;/i&gt;&lt;/b&gt;`) line = regexp.MustCompile(`\*\*(.*?)\*\*`).ReplaceAllString(line, `&lt;b&gt;$1&lt;/b&gt;`) line = regexp.MustCompile(`\*(.*?)\*`).ReplaceAllString(line, `&lt;i&gt;$1&lt;/i&gt;`) // wrap strikethrough text in "&lt;s&gt;" tags line = regexp.MustCompile(`\~\~(.*?)\~\~`).ReplaceAllString(line, `&lt;s&gt;$1&lt;/s&gt;`) // wrap underscored text in "&lt;u&gt;" tags line = regexp.MustCompile(`__(.*?)__`).ReplaceAllString(line, `&lt;u&gt;$1&lt;/u&gt;`) // convert links to anchor tags line = regexp.MustCompile(`\[(.*?)\]\((.*?)\)[^\)]`).ReplaceAllString(line, `&lt;a href="$2"&gt;$1&lt;/a&gt;`) // escape and wrap blockquotes in "&lt;blockquote&gt;" tags line = regexp.MustCompile(`^\&gt;(\s|)`).ReplaceAllString(line, `&amp;gt;`) line = regexp.MustCompile(`\&amp;gt\;(.*?)$`).ReplaceAllString(line, `&lt;blockquote&gt;$1&lt;/blockquote&gt;`) // wrap the content of backticks inside of "&lt;code&gt;" tags line = regexp.MustCompile("`(.*?)`").ReplaceAllString(line, `&lt;code&gt;$1&lt;/code&gt;`) // convert headings for i := 6; i &gt;= 1; i-- { size, md_header := strconv.Itoa(i), strings.Repeat("#", i) line = regexp.MustCompile(`^` + md_header + `(\s|)(.*?)$`).ReplaceAllString(line, `&lt;h` + size + `&gt;$2&lt;/h` + size + `&gt;`) } // update the line lines[i] = line } // return the joined lines return strings.Join(lines, "\n") } </code></pre>
[]
[ { "body": "<h2>Performance</h2>\n\n<h3>Regex</h3>\n\n<p><code>regex.MustCompile()</code> is very expensive! Do not use this method inside a loop ! </p>\n\n<p>instead, define your regex as global variables only once: </p>\n\n<pre><code>var (\n boldItalicReg = regexp.MustCompile(`\\*\\*\\*(.*?)\\*\\*\\*`)\n boldReg = regexp.MustCompile(`\\*\\*(.*?)\\*\\*`)\n ...\n)\n</code></pre>\n\n<h3>Headers</h3>\n\n<p>If a line is a header, it will start by a <code>#</code>. We can check for this before calling <code>ReplaceAllString()</code> 6 times ! All we need \n to do is to trim the line, and then check if it starts with <code>#</code>:</p>\n\n<pre><code>line = strings.TrimSpace(line)\nif strings.HasPrefix(line, \"#\") {\n // convert headings\n ...\n}\n</code></pre>\n\n<p>We could go further and unrolling the loop to avoid unecessary allocations: </p>\n\n<pre><code>count := strings.Count(line, \"#\")\nswitch count {\ncase 1:\n line = h1Reg.ReplaceAllString(line, `&lt;h1&gt;$2&lt;/h1&gt;`)\ncase 2: \n ...\n}\n</code></pre>\n\n<h3>Use a scanner</h3>\n\n<p>The idiomatic way to read a file line by line in go is to use a <code>scanner</code>. It takes an <code>io.Reader</code> as parameters, so you can directly pass\nyour mardown file instead of converting it into a string first: </p>\n\n<pre><code>func NewMarkdown(input io.Reader) string {\n\n\n scanner := bufio.NewScanner(input)\n for scanner.Scan() {\n\n line := scanner.Text()\n ...\n }\n}\n</code></pre>\n\n<h3>Use <code>[]byte</code> instead of <code>string</code></h3>\n\n<p>In go, a <code>string</code> is a read-only slice of bytes. Working with strings is usually more expensive than working with slice of bytes, \nso use <code>[]byte</code> instead of <code>strings</code> when you can:</p>\n\n<pre><code>line := scanner.Bytes()\nline = boldItalicReg.ReplaceAll(line, []byte(`&lt;b&gt;&lt;i&gt;$1&lt;/i&gt;&lt;/b&gt;`))\n</code></pre>\n\n<h3>Write result to a <code>bytes.Buffer</code></h3>\n\n<p>Instead of <code>string.Join()</code>, we can use a buffer to write each line in order to further reduce the number of allocations: </p>\n\n<pre><code>buf := bytes.NewBuffer(nil)\nscanner := bufio.NewScanner(input)\nfor scanner.Scan() {\n\n line := scanner.Bytes()\n ...\n buf.Write(line)\n buf.WriteByte('\\n')\n}\n\nreturn buf.String()\n</code></pre>\n\n<p>final code: </p>\n\n<pre><code>package parse\n\nimport (\n \"bufio\"\n \"bytes\"\n \"io\"\n \"regexp\"\n)\n\nvar (\n boldItalicReg = regexp.MustCompile(`\\*\\*\\*(.*?)\\*\\*\\*`)\n boldReg = regexp.MustCompile(`\\*\\*(.*?)\\*\\*`)\n italicReg = regexp.MustCompile(`\\*(.*?)\\*`)\n strikeReg = regexp.MustCompile(`\\~\\~(.*?)\\~\\~`)\n underscoreReg = regexp.MustCompile(`__(.*?)__`)\n anchorReg = regexp.MustCompile(`\\[(.*?)\\]\\((.*?)\\)[^\\)]`)\n escapeReg = regexp.MustCompile(`^\\&gt;(\\s|)`)\n blockquoteReg = regexp.MustCompile(`\\&amp;gt\\;(.*?)$`)\n backtipReg = regexp.MustCompile(\"`(.*?)`\")\n\n h1Reg = regexp.MustCompile(`^#(\\s|)(.*?)$`)\n h2Reg = regexp.MustCompile(`^##(\\s|)(.*?)$`)\n h3Reg = regexp.MustCompile(`^###(\\s|)(.*?)$`)\n h4Reg = regexp.MustCompile(`^####(\\s|)(.*?)$`)\n h5Reg = regexp.MustCompile(`^#####(\\s|)(.*?)$`)\n h6Reg = regexp.MustCompile(`^######(\\s|)(.*?)$`)\n)\n\nfunc NewMarkdown(input io.Reader) string {\n\n buf := bytes.NewBuffer(nil)\n\n scanner := bufio.NewScanner(input)\n for scanner.Scan() {\n\n line := bytes.TrimSpace(scanner.Bytes())\n if len(line) == 0 {\n buf.WriteByte('\\n')\n continue\n }\n\n // wrap bold and italic text in \"&lt;b&gt;\" and \"&lt;i&gt;\" elements\n line = boldItalicReg.ReplaceAll(line, []byte(`&lt;b&gt;&lt;i&gt;$1&lt;/i&gt;&lt;/b&gt;`))\n line = boldReg.ReplaceAll(line, []byte(`&lt;b&gt;$1&lt;/b&gt;`))\n line = italicReg.ReplaceAll(line, []byte(`&lt;i&gt;$1&lt;/i&gt;`))\n // wrap strikethrough text in \"&lt;s&gt;\" tags\n line = strikeReg.ReplaceAll(line, []byte(`&lt;s&gt;$1&lt;/s&gt;`))\n // wrap underscored text in \"&lt;u&gt;\" tags\n line = underscoreReg.ReplaceAll(line, []byte(`&lt;u&gt;$1&lt;/u&gt;`))\n // convert links to anchor tags\n line = anchorReg.ReplaceAll(line, []byte(`&lt;a href=\"$2\"&gt;$1&lt;/a&gt;`))\n // escape and wrap blockquotes in \"&lt;blockquote&gt;\" tags\n line = escapeReg.ReplaceAll(line, []byte(`&amp;gt;`))\n line = blockquoteReg.ReplaceAll(line, []byte(`&lt;blockquote&gt;$1&lt;/blockquote&gt;`))\n // wrap the content of backticks inside of \"&lt;code&gt;\" tags\n line = backtipReg.ReplaceAll(line, []byte(`&lt;code&gt;$1&lt;/code&gt;`))\n // convert headings\n if line[0] == '#' {\n\n count := bytes.Count(line, []byte(`#`))\n switch count {\n case 1:\n line = h1Reg.ReplaceAll(line, []byte(`&lt;h1&gt;$2&lt;/h1&gt;`))\n case 2:\n line = h2Reg.ReplaceAll(line, []byte(`&lt;h2&gt;$2&lt;/h2&gt;`))\n case 3:\n line = h3Reg.ReplaceAll(line, []byte(`&lt;h3&gt;$2&lt;/h3&gt;`))\n case 4:\n line = h4Reg.ReplaceAll(line, []byte(`&lt;h4&gt;$2&lt;/h4&gt;`))\n case 5:\n line = h5Reg.ReplaceAll(line, []byte(`&lt;h5&gt;$2&lt;/h5&gt;`))\n case 6:\n line = h6Reg.ReplaceAll(line, []byte(`&lt;h6&gt;$2&lt;/h6&gt;`))\n }\n }\n buf.Write(line)\n buf.WriteByte('\\n')\n }\n return buf.String()\n}\n</code></pre>\n\n<h2>Benchmarks</h2>\n\n<p>I used the folowing code for benchmarks, on a 20kB md file: </p>\n\n<pre><code>func BenchmarkMarkdown(b *testing.B) {\n\n md, err := ioutil.ReadFile(\"README.md\")\n if err != nil {\n b.Fail()\n }\n raw := string(md)\n b.ResetTimer()\n\n for n := 0; n &lt; b.N; n++ {\n _ = Markdown(raw)\n }\n}\n\nfunc BenchmarkMarkdownNew(b *testing.B) {\n\n for n := 0; n &lt; b.N; n++ {\n file, err := os.Open(\"README.md\")\n if err != nil {\n b.Fail()\n }\n _ = NewMarkdown(file)\n file.Close()\n }\n}\n</code></pre>\n\n<p>Results: </p>\n\n<pre><code>&gt; go test -bench=. -benchmem\n\ngoos: linux\ngoarch: amd64\nBenchmarkMarkdown-4 10 104990431 ns/op 364617427 B/op 493813 allocs/op\nBenchmarkMarkdownNew-4 1000 1464745 ns/op 379376 B/op 11085 allocs/op\n</code></pre>\n\n<p>benchstat diff: </p>\n\n<pre><code>name old time/op new time/op delta\nMarkdown-4 105ms ± 0% 1ms ± 0% ~ (p=1.000 n=1+1)\n\nname old alloc/op new alloc/op delta\nMarkdown-4 365MB ± 0% 0MB ± 0% ~ (p=1.000 n=1+1)\n\nname old allocs/op new allocs/op delta\nMarkdown-4 494k ± 0% 11k ± 0% ~ (p=1.000 n=1+1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:48:27.940", "Id": "210477", "ParentId": "210422", "Score": "2" } } ]
{ "AcceptedAnswerId": "210477", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T12:56:39.277", "Id": "210422", "Score": "4", "Tags": [ "performance", "html", "regex", "go", "markdown" ], "Title": "Converting Markdown to HTML using Go" }
210422
<p>Bulls and Cows is a simple code-breaking game sometimes better known as "Mastermind." The rules are explained here: <a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" rel="noreferrer">https://en.wikipedia.org/wiki/Bulls_and_Cows</a></p> <p>I would appreciate some feedback on the following implementation in terms of overall code quality, layout and logic. It's meant to be at a fairly basic level so I don't want to over complicate things, but want to avoid any obviously bad choices. Suggestions for improvements very welcome.</p> <pre><code>import random SECRET_NUMBER_SIZE = 2 MAX_GUESSES = 5 # Generate secret number with SECRET_NUMBER_SIZE digits and no duplicates secret_number = "" while len(secret_number) &lt; SECRET_NUMBER_SIZE: new_digit = str(random.randint(0, 9)) if new_digit not in secret_number: secret_number += new_digit # print(f"For testing. Secret number is: {secret_number}") print(f"Guess my number. It contains {SECRET_NUMBER_SIZE}\ unique digits from 0-9") remaining_turns = MAX_GUESSES while remaining_turns &lt;= MAX_GUESSES: # Get user guess and validate length player_guess = input("Please enter your guess: ") if len(player_guess) != SECRET_NUMBER_SIZE: print(f"Your guess must be {SECRET_NUMBER_SIZE} digits long.") continue # Main game logic if player_guess == secret_number: print("Yay, you guessed it!") break else: bulls = 0 cows = 0 for i in range(SECRET_NUMBER_SIZE): if player_guess[i] == secret_number[i]: bulls += 1 for j in range(SECRET_NUMBER_SIZE): if player_guess[j] in secret_number and \ player_guess[j] != secret_number[j]: cows += 1 print(f"Bulls: {bulls}") print(f"Cows: {cows}") remaining_turns -= 1 if remaining_turns &lt; 1: print("You lost the game.") break </code></pre>
[]
[ { "body": "<p>Looks quite clean. I can only see two things:</p>\n\n<ul>\n<li>Create a <code>main</code> function to pull your code out of global scope</li>\n<li>Do some list comprehension sums.</li>\n</ul>\n\n<p>This:</p>\n\n<pre><code>for i in range(SECRET_NUMBER_SIZE):\n if player_guess[i] == secret_number[i]:\n bulls += 1\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>bulls = sum(1 for p, s in zip(player_guess, secret_guess)\n if p == s)\n</code></pre>\n\n<p>Similarly, this:</p>\n\n<pre><code>for j in range(SECRET_NUMBER_SIZE):\n if player_guess[j] in secret_number and \\\n player_guess[j] != secret_number[j]:\n cows += 1\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>cows = sum(1 for p, s in zip(player_guess, secret_number)\n if p != s and p in secret_number)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T15:09:55.733", "Id": "210429", "ParentId": "210426", "Score": "3" } }, { "body": "<p>Your code looks good and uses modern techniques like f-strings which is a nice touch. Let's see can be improved.</p>\n\n<p><em>Warning: I did not know the game <a href=\"https://en.wikipedia.org/wiki/Bulls_and_Cows\" rel=\"noreferrer\">Bulls and Cows</a> until I read your question so I won't be able to judge on that part.</em></p>\n\n<p><strong>Small functions</strong></p>\n\n<p>You should try to split your code into small functions.</p>\n\n<p>The most obvious one could be:</p>\n\n<pre><code>def generate_secret_number(length):\n \"\"\"Generate secret number with `length` digits and no duplicates.\"\"\"\n secret_number = \"\"\n while len(secret_number) &lt; length:\n new_digit = str(random.randint(0, 9))\n if new_digit not in secret_number:\n secret_number += new_digit\n return secret_number\n</code></pre>\n\n<p>Another one could be:</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = 0\n cows = 0\n for i in range(SECRET_NUMBER_SIZE):\n if player_guess[i] == secret_number[i]:\n bulls += 1\n for j in range(SECRET_NUMBER_SIZE):\n if player_guess[j] in secret_number and \\\n player_guess[j] != secret_number[j]:\n cows += 1\n return cows, bulls\n</code></pre>\n\n<p>Then, we can try to improve these independently</p>\n\n<p><strong>Improving <code>generate_secret_number</code></strong></p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8, the Python Code Style Guide</a> suggests:</p>\n\n<blockquote>\n <p>For example, do not rely on CPython's efficient implementation of\n in-place string concatenation for statements in the form a += b or a =\n a + b. This optimization is fragile even in CPython (it only works for\n some types) and isn't present at all in implementations that don't use\n refcounting. In performance sensitive parts of the library, the\n ''.join() form should be used instead. This will ensure that\n concatenation occurs in linear time across various implementations.</p>\n</blockquote>\n\n<p>It really doesn't matter in your case because we use a length of 2 but it is also a good chance to take nice habits. We could write:</p>\n\n<pre><code>def generate_secret_number(length):\n \"\"\"Generate secret number with `length` digits and no duplicates.\"\"\"\n digits = []\n while len(digits) &lt; length:\n new_digit = str(random.randint(0, 9))\n if new_digit not in digits:\n digits.append(new_digit)\n return \"\".join(digits)\n</code></pre>\n\n<p>Also, we could one again split the logic into smaller function. As we do so, we stop checking the length of <code>digits</code> when we do not change it</p>\n\n<pre><code>def generate_new_digit_not_in(lst):\n while True:\n d = str(random.randint(0, 9))\n if d not in lst:\n return d\n\ndef generate_secret_number(length):\n \"\"\"Generate secret number with `length` digits and no duplicates.\"\"\"\n digits = []\n while len(digits) &lt; length:\n digits.append(generate_new_digit_not_in(digits))\n return \"\".join(digits)\n</code></pre>\n\n<p>Now, because we know the number of iterations, instead of using a <code>while</code> loop, we could use a <code>for</code> loop:</p>\n\n<pre><code>def generate_new_digit_not_in(lst):\n while True:\n d = str(random.randint(0, 9))\n if d not in lst:\n return d\n\ndef generate_secret_number(length):\n \"\"\"Generate secret number with `length` digits and no duplicates.\"\"\"\n digits = []\n for _ in range(length):\n digits.append(generate_new_digit_not_in(digits))\n return \"\".join(digits)\n</code></pre>\n\n<p><strong>Improving <code>compute_cows_and_bulls</code></strong></p>\n\n<p>First detail is that we could use <code>i</code> for both loops:</p>\n\n<pre><code>for i in range(SECRET_NUMBER_SIZE):\n if player_guess[i] == secret_number[i]:\n bulls += 1\nfor i in range(SECRET_NUMBER_SIZE):\n if player_guess[i] in secret_number and \\\n player_guess[i] != secret_number[i]:\n cows += 1\n</code></pre>\n\n<p>Then, and more importantly, I highly recommend <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">Ned Batchelder's talk \"Loop like a native\"</a>.</p>\n\n<p>One of the key hindsight is that when you are given iterable(s), you usually do not need to use index access and when you don't need it, you should avoid it.</p>\n\n<p>Thus, usually, when you write <code>for i in range(list_length)</code>, you can do things in a better way as Python offers many tools to work on iterables.</p>\n\n<p>Here, we need to index to iterate over 2 lists in the same time. We could use <a href=\"https://docs.python.org/3.8/library/functions.html?highlight=zip#zip\" rel=\"noreferrer\"><code>zip</code></a> and get something like:</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = 0\n cows = 0\n for p, s in zip(player_guess, secret_number):\n if p == s:\n bulls += 1\n for p, s in zip(player_guess, secret_number):\n if p in secret_number and p != s:\n cows += 1\n return cows, bulls\n</code></pre>\n\n<p>Then, we could decide to have a single loop:</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = 0\n cows = 0\n for p, s in zip(player_guess, secret_number):\n if p == s:\n bulls += 1\n elif p in secret_number:\n cows += 1\n return cows, bulls\n</code></pre>\n\n<p>However, the previous version of the code is better if we want to introduce more helpful tools.</p>\n\n<p>We could use the <a href=\"https://docs.python.org/3.8/library/functions.html?highlight=zip#sum\" rel=\"noreferrer\"><code>sum</code></a> builtin to write for instance:</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = sum(1 for p, s in zip(player_guess, secret_number) if p == s)\n cows = sum(1 for p, s in zip(player_guess, secret_number) if p in secret_number and p != s)\n return cows, bulls\n</code></pre>\n\n<p>Or the equivalent:</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = sum(p == s for p, s in zip(player_guess, secret_number))\n cows = sum(p in secret_number and p != s for p, s in zip(player_guess, secret_number))\n return cows, bulls\n</code></pre>\n\n<p>Also, for <code>cows</code> we could try to be more clever and realise that instead of checking <code>p != s</code>, we could include them and then at the end substract <code>bulls</code> from <code>cows</code>.</p>\n\n<pre><code>def compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = sum(p == s for p, s in zip(player_guess, secret_number))\n cows = sum(p in secret_number for p in player_guess)\n return cows - bulls, bulls\n</code></pre>\n\n<p>Note: in order to test my changes, I wrote the following tests:</p>\n\n<pre><code>assert compute_cows_and_bulls(\"10\", \"23\") == (0, 0)\nassert compute_cows_and_bulls(\"10\", \"13\") == (0, 1)\nassert compute_cows_and_bulls(\"10\", \"31\") == (1, 0)\nassert compute_cows_and_bulls(\"10\", \"01\") == (2, 0)\nassert compute_cows_and_bulls(\"10\", \"10\") == (0, 2)\n</code></pre>\n\n<p>Indeed, one of the benefits of writing small functions with a well-defined behavior is that you can easily write unit-tests for these. In a more serious context, you'd use a proper unit-test frameworks.</p>\n\n<p><strong>Improving the main loop</strong></p>\n\n<p>Here again, we can reuse the techniques seen previously.</p>\n\n<p>For instance, we could have a smaller function to handle and validate user input.</p>\n\n<pre><code>def get_user_guess(length):\n \"\"\"Get user guess and validate length.\"\"\"\n while True:\n player_guess = input(\"Please enter your guess: \")\n if len(player_guess) == length:\n return player_guess\n print(f\"Your guess must be {length} digits long.\")\n</code></pre>\n\n<p>Then realise that we never exit the main loop because of the <code>while remaining_turns &lt;= MAX_GUESSES</code> condition: we could simply write <code>while True</code> - the game always ends on either a victory or a defeat.</p>\n\n<p>Also, instead of counting the number of remaining turns, we could count the number of turns like this:</p>\n\n<pre><code>turns = 0\nwhile True:\n turns += 1\n player_guess = get_user_guess(SECRET_NUMBER_SIZE)\n\n # Main game logic\n if player_guess == secret_number:\n print(\"Yay, you guessed it!\")\n break\n cows, bulls = compute_cows_and_bulls(player_guess, secret_number)\n print(f\"Bulls: {bulls}\")\n print(f\"Cows: {cows}\")\n if turns &gt;= MAX_GUESSES:\n print(\"You lost the game.\")\n break\n</code></pre>\n\n<p>But then maybe we could reuse a simple <code>for</code> loop here.</p>\n\n<p><strong>Final code</strong></p>\n\n<p>Taking into account everything, we end up with:</p>\n\n<pre><code>import random\n\n\ndef generate_new_digit_not_in(lst):\n \"\"\"Generate a random digit not in `lst`.\"\"\"\n while True:\n d = str(random.randint(0, 9))\n if d not in lst:\n return d\n\n\ndef generate_secret_number(length):\n \"\"\"Generate secret number with `length` digits and no duplicates.\"\"\"\n digits = []\n for _ in range(length):\n digits.append(generate_new_digit_not_in(digits))\n return \"\".join(digits)\n\n\ndef compute_cows_and_bulls(player_guess, secret_number):\n \"\"\"Return the tuple (cows, bulls) for player_guess.\"\"\"\n bulls = sum(p == s for p, s in zip(player_guess, secret_number))\n cows = sum(p in secret_number for p in player_guess)\n return cows - bulls, bulls\n\n\ndef get_user_guess(length):\n \"\"\"Get user guess and validate length.\"\"\"\n while True:\n player_guess = input(\"Please enter your guess: \")\n if len(player_guess) == length:\n return player_guess\n print(f\"Your guess must be {length} digits long.\")\n\n\ndef play_game(secret_number_len, nb_guesses):\n secret_number = generate_secret_number(secret_number_len)\n print(f\"For testing. Secret number is: {secret_number}\")\n print(f\"Guess my number. It contains {secret_number_len} unique digits from 0-9\")\n\n for t in range(nb_guesses):\n player_guess = get_user_guess(secret_number_len)\n\n # Main game logic\n if player_guess == secret_number:\n print(\"Yay, you guessed it!\")\n return\n cows, bulls = compute_cows_and_bulls(player_guess, secret_number)\n print(f\"Bulls: {bulls}\")\n print(f\"Cows: {cows}\")\n print(\"You lost the game.\")\n\n\ndef unit_test_compute_cows_and_bulls():\n assert compute_cows_and_bulls(\"10\", \"23\") == (0, 0)\n assert compute_cows_and_bulls(\"10\", \"13\") == (0, 1)\n assert compute_cows_and_bulls(\"10\", \"31\") == (1, 0)\n assert compute_cows_and_bulls(\"10\", \"01\") == (2, 0)\n assert compute_cows_and_bulls(\"10\", \"10\") == (0, 2)\n\n\nif __name__ == '__main__':\n SECRET_NUMBER_SIZE = 2\n MAX_GUESSES = 50\n play_game(SECRET_NUMBER_SIZE, MAX_GUESSES)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T16:13:55.067", "Id": "406736", "Score": "1", "body": "Interesting strategy of iteratively editing your answer to add more content. Do you do this often, and do you find it useful for generating cohesive answers? In the past I've written long answers all at once, because it helps me to prioritize the most important points to the beginning (though admittedly, I am imperfect), while recently, I've been trending towards shorter answers that fill in the gaps for other answers. For a question like this though, there's not too many deep structural levels to analyze, so I can imagine this iterative approach working out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T16:33:02.010", "Id": "406738", "Score": "2", "body": "@Graham It is not a real strategy as per se. Just that I sometime come here to fill small periods of free time (compilations, tests, etc). As for the cohesion of the answer, it is not my strong point. I usually do whatever I can to get a better understanding of the code (tests, refactoring) then edit things little by little. Going step by step can be interesting for the OP as it shows how to improve pieces of code that may not end up in the final code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T15:28:57.237", "Id": "210430", "ParentId": "210426", "Score": "6" } }, { "body": "<p>@Josay's and @Reinderien's answers both give useful advice, with @Josay's being particularly comprehensive. However, there is one point that I've noticed neither of them have covered</p>\n\n<h2>Generation of the secret number</h2>\n\n<pre><code># Generate secret number with SECRET_NUMBER_SIZE digits and no duplicates\nsecret_number = \"\"\nwhile len(secret_number) &lt; SECRET_NUMBER_SIZE:\n new_digit = str(random.randint(0, 9))\n if new_digit not in secret_number:\n secret_number += new_digit\n</code></pre>\n\n<p>This is an inelegant way of generating the secret number for two reasons:</p>\n\n<ol>\n<li><p>You concatenate to a string, an immutable type. This is much more expensive than necessary, which does not a notable impact on a program of this size, but could become problematic as you scale up; it's better to practice good techniques, even at small scales. Additionally, you should never need to iteratively concatenate to a string in situations where the string's contents are generated all at once, because there are two successively more efficient ways:</p>\n\n<ul>\n<li>Since Python uses dynamic lists, you can create a list with the string's contents, and then use <code>\"\".join(str(i) for i in src_lst)</code></li>\n<li>To improve the efficiency even further, you can utilize the fact that you know the list's size already, and \"pre-allocate\" the list using <code>lst = [None] * SECRET_NUMBER_SIZE</code> and then iteratively fill in its contents using a numerical index variable. This is a bit unpythonic, as @Josay goes over in their answer, and is probably a bit of premature optimization, but it's a good trick to have up your sleave if you want to eek out a bit more performance, and may be extremely useful depending on the situation.</li>\n<li>But there's an even better way, which we'll get to in a second...</li>\n</ul></li>\n<li><p>Every number is checked to ensure it hasn't already occurred in the result list. The reason this is not ideal is because at larger scales, one could end up generating many numbers before they stumble upon one that hasn't already been chosen. To mitigate this, one could lower the generation range each time, and offset the numbers accordingly, but it's probably not worth the effort because this isn't much of a practical concern, even at larger scales; generating random numbers using the Mersenne Twister is very cheap. But this concern helps lead to an elegant solution...</p></li>\n</ol>\n\n<p><a href=\"https://docs.python.org/library/random.html#random.sample\" rel=\"noreferrer\"><code>random.sample()</code></a> is your friend here. It allows you to generate multiple distinct random numbers quite easily; all you have to provide is a population sequence and the size of the sample. For this situation, a population sequence is quite simple: <code>range(10)</code> supplies all the numbers between 0 and 9 inclusive. You can now simplify your 5 lines above into ~1 line:</p>\n\n<pre><code>secret_number = \"\".join((str(i) for i in\n random.sample(range(10), SECRET_NUMBER_SIZE)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:36:43.237", "Id": "406788", "Score": "0", "body": "What about `secret_number = ''.join(map(str, random.sample(range(10), SECRET_NUMBER_SIZE)))`? Also note that your version used generator expressions, not lists." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:52:07.850", "Id": "406793", "Score": "1", "body": "@SolomonUcko that is also a good solution, and probably a bit faster; I just stuck with generator expressions because they're a bit more versatile and it's my general habit, but `map` does work well in situations like this. Regarding the list comment, I never claimed my final solution used lists; I just used lists as an example during the explanation of my thought process. I think you may be referring to when I initially mentioned the `join` operator, but in that context, `src_lst` was the list in question. I could be a bit more explicit on how list comprehensions work, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T16:31:01.487", "Id": "210433", "ParentId": "210426", "Score": "9" } } ]
{ "AcceptedAnswerId": "210433", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T14:48:16.127", "Id": "210426", "Score": "7", "Tags": [ "python", "game" ], "Title": "Python Bulls and Cows" }
210426
<p>I'm working my way through the examples in an OpenGL website; I'm now on <a href="http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/" rel="nofollow noreferrer">tutorial 2 ("the first triangle")</a>.</p> <p>Among the (many) things I've changed from the sample include:</p> <ul> <li>Replacing the hodge-podge of C and C++ with pure C</li> <li>Adding more error handling output</li> <li>Adding a makefile</li> <li>Moving all of the pertinent code from their <code>common</code> folder into the main file for legibility of beginners</li> <li>Renaming the shader files to end in <code>.glsl</code></li> <li>Other minor tweaks.</li> </ul> <p>I'm open to constructive feedback of any kind. The complete source is on <a href="https://github.com/shirishkarveer/OpenGL_GEOM_2D" rel="nofollow noreferrer">GitHub</a>.</p> <h2>makefile</h2> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/make -f cflags=-ggdb -Wall -std=c17 all: 02 # These are used instead of implicit rules, for clarity 02: 02.o makefile gcc $(cflags) -o $@ $&lt; $(shell pkg-config --libs glew glfw3) 02.o: 02.c makefile gcc $(cflags) -o $@ $&lt; $(shell pkg-config --cflags glew glfw3) -c </code></pre> <h2>simple-fragment.glsl</h2> <pre><code>#version 330 core // Output data out vec3 color; void main() { // Output color = red color = vec3(1,0,0); } </code></pre> <h2>simple-vertex.glsl</h2> <pre><code>#version 330 core // Input vertex data, different for all executions of this shader. layout(location = 0) in vec3 vertexPosition_modelspace; void main() { gl_Position.xyz = vertexPosition_modelspace; gl_Position.w = 1; } </code></pre> <h2>02.c</h2> <pre><code>#include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;GL/glew.h&gt; #include &lt;GLFW/glfw3.h&gt; static void glfwCB(int error, const char *desc) { fprintf(stderr, "GLFW error 0x%08X: %s\n", error, desc); } static GLuint loadShader(const char *fn, GLenum shaderType) { printf("Compiling shader '%s'...\n", fn); GLuint shaderID = glCreateShader(shaderType); if (!shaderID) { fprintf(stderr, "Failed to create shader\n"); exit(1); } FILE *f = fopen(fn, "r"); if (!f) { perror("Failed to load shader file"); exit(1); } if (fseek(f, 0, SEEK_END)) { perror("Failed to get file size"); exit(1); } GLint size[1] = {ftell(f)}; if (size[0] == -1) { perror("Failed to get file size"); exit(1); } rewind(f); char *source = malloc(size[0]); if (!source) { perror("Failed to allocate source memory"); exit(1); } if (fread(source, 1, size[0], f) != size[0]) { perror("Failed to read file"); exit(1); } if (fclose(f)) perror("Warning: failed to close source file"); const GLchar *rosource = source; glShaderSource(shaderID, 1, &amp;rosource, size); free(source); glCompileShader(shaderID); GLint logLength; glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &amp;logLength); if (logLength) { GLchar *log = malloc(logLength); if (!log) { perror("Couldn't allocate shader compile log"); exit(1); } glGetShaderInfoLog(shaderID, logLength, NULL, log); printf("Shader compile message: %s\n", log); free(log); } GLint status; glGetShaderiv(shaderID, GL_COMPILE_STATUS, &amp;status); if (!status) exit(1); return shaderID; } static GLuint loadShaders(const char *vertex_fn, const char *fragment_fn) { // Compile the shaders GLuint vertexShaderID = loadShader(vertex_fn, GL_VERTEX_SHADER), fragmentShaderID = loadShader(fragment_fn, GL_FRAGMENT_SHADER); puts("Linking shader program..."); GLuint programID = glCreateProgram(); glAttachShader(programID, vertexShaderID); glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); // Check the program GLint logLength; glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &amp;logLength); if (logLength &gt; 0) { char *log = malloc(logLength); if (!log) { perror("Couldn't allocate shader compile log"); exit(1); } glGetProgramInfoLog(programID, logLength, NULL, log); printf("Shader link message: %s\n", log); free(log); } GLint status; glGetProgramiv(programID, GL_LINK_STATUS, &amp;status); if (!status) exit(1); glDetachShader(programID, vertexShaderID); glDetachShader(programID, fragmentShaderID); glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); return programID; } int main() { // Set error callback to see more detailed failure info glfwSetErrorCallback(glfwCB); if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing // To ensure compatiblity, check the output of this command: // $ glxinfo | grep 'Max core profile version' glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // We don't want the old OpenGL glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context GLFWwindow *window = glfwCreateWindow(1024, 768, "Tutorial 02 - Red triangle", NULL, NULL); if (!window) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, " "they are not 3.3 compatible. Try the 2.1 version of " "the tutorials.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = true; // Needed in core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); glfwTerminate(); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); GLuint VertexArrayID; glGenVertexArrays(1, &amp;VertexArrayID); glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders GLuint programID = loadShaders("simple-vertex.glsl", "simple-fragment.glsl"); const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; GLuint vertexbuffer; glGenBuffers(1, &amp;vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); puts("Initialized."); do { // Clear the screen glClear(GL_COLOR_BUFFER_BIT); // Use our shader glUseProgram(programID); // 1st attribute buffer: vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride NULL // array buffer offset ); // Draw the triangle! glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -&gt; 1 triangle glDisableVertexAttribArray(0); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); // Check if the ESC key was pressed or the window was closed } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &amp;&amp; !glfwWindowShouldClose(window)); // Cleanup VBO glDeleteBuffers(1, &amp;vertexbuffer); glDeleteVertexArrays(1, &amp;VertexArrayID); glDeleteProgram(programID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; } </code></pre>
[]
[ { "body": "<p>A few minor things after a quick look.</p>\n\n<p><em>Inconsistent use of spacing</em>. The placement of the opening <code>{</code> is sometimes on the same line as the statement it belongs with, other times it is on a line by itself (which makes an almost blank-line gap in the code). Pick one style and stick with it.</p>\n\n<p>What is <code>glfwCB</code>? That just seems like a bunch of random characters thrown together for a function name. Pick something more meaningful, even if it came directly from the tutorial.</p>\n\n<p><em>Inconsistent passing arrays to <code>glShaderSource</code></em>. For the 'length' array you pass in a one element array, while for the array of strings you pass in the address of a variable as a one element array. Both ways are valid, but the inconsistency makes it harder to understand what exactly is going on there. Think about what you'll have to do when you alter this later to use two (or more) shaders.</p>\n\n<p><em>Run on variable declarations</em>. With <code>vertexShaderID</code> and <code>fragmentShaderID</code>, using two statements and repeating the type makes the code easier to read. As it is you need to look carefully to see if it is two declarations or one declaration that spans two lines (see, for example, the <code>while</code> near the end of <code>main</code>, which has a very similar appearance but is one statement).</p>\n\n<p><code>g_vertex_buffer_data</code> can be made <code>static</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T17:10:35.570", "Id": "406749", "Score": "0", "body": "`glfwCB` I'll rename to `glfwErrorCallback`. I moved all of the open-braces to the same line. \"Run-on variable declarations\" I disagree with; it's quite clear what it's doing based on indentation. What advantage is there to setting `g_vertex_buffer_data` to be `static`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T01:39:53.940", "Id": "406817", "Score": "1", "body": "@Reinderien You don't change any of the data in `g_vertex_buffer_data`, and to initialize the local array the compiler will have to store that data into it, either with some store instructions or (more likely here) copy the data from an internal static buffer. Making the array static will allow it to be initialized at compile time, saving some code space and execution time. We'll just have to disagree on the variable declaration, as my impression seeing it is different from yours (which should be reason enough to be explicit with what's going on)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T16:29:05.287", "Id": "210432", "ParentId": "210427", "Score": "2" } }, { "body": "<h1>3<sup>rd</sup> Party Libraries</h1>\n<p>I have a hard time with most OpenGL tutorials, and this one is no different. They often have a bunch of non-OpenGL code that mysteriously handles things without explaining how under the guise of &quot;keeping things simple and cross platform.&quot; In my opinion it does more harm than good. In particular, the use of support libraries like GLEW, GLFW, GLU, GLUT, etc. leaves beginners confused about which parts are OpenGL and which parts are not. It ends up impairing their use of the tools and it hides very important details like OpenGL contexts. A better tutorial would simply supply code for creating a context on each platform that the tutorial supports. It's more work to write and to make clean and understandable to someone new to OpenGL, but it would be worth it in my opinion.</p>\n<p>In fact, looking through the code, is GLEW even used? It's initialized, and <code>glewExperimental</code> is set to true, but I don't see any other calls to it. Does it affect GLFW code? If so, that's pretty confusing to a learner. In fact, having the GLEW and GLFW code intermixed, it's really hard to tell which is which at a glance.</p>\n<h1>Error Handling</h1>\n<p>You have some reasonably good error handling for reading in the shaders. You handle a bunch of errors around file handling, allocating memory for shaders and logs, etc. Then you completely ignore every possible OpenGL error in your program. There should be some calls to <code>glGetError()</code> somewhere in the code to help the reader understand that things can go wrong with OpenGL.</p>\n<p>Also message about Intel GPUs not supporting OpenGL 3.3 is out-of-date. It can be removed. It's also probably not the only reason that not having a window can happen, so it's just confusing to a user that doesn't have an Intel GPU.</p>\n<h1>Order of Operations</h1>\n<p>Because OpenGL is a big state machine, it often doesn't matter what order you perform actions in, so long as they are all performed before the next draw call. But for a tutorial, it can be useful to have things grouped together when they affect state that's related. For that reason, I'd put the calls that generate and bind the vertex array near the calls that generate, bind, and fill the vertex buffers. They're all related to getting the geometry up to the GPU, so it would be nice to have them together.</p>\n<p>Also, you don't need to re-bind the vertex buffer in the loop in <code>main()</code> as it's already current. Binding things has a performance impact and is very confusing to new learners of OpenGL in my experience. It's one of those things that leads to a lot of superstition when learning OpenGL. (&quot;Last time I had this problem it was because something wasn't bound properly. I'll just bind everything again and hope that fixes it!&quot;)</p>\n<h1>Use Functions</h1>\n<p>The <code>main()</code> function has way too much going on. I'd break out setting up the window and context into its own function. I'd probably break out setting up all the buffers, too. And then I'd make the main loop its own function as well. This will help someone new to the library understand which bits of code are related to which parts of the functionality of the tutorial. (And that can be a good things with OpenGL which is quite opaque!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:08:49.907", "Id": "406821", "Score": "0", "body": "At first glance it seems as if glew isn't doing a lot. Unfortunately, as soon as it's removed, using OpenGL (especially on bad operating systems - such as OSX - that I have to support) becomes a nightmare. It has a weird and broken way of handling \"frameworks\". glew fixes this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:09:40.857", "Id": "406822", "Score": "0", "body": "Whereas it may be confusing to a learner, the alternative (writing a long, hacky makefile with multiple conditional blocks, and similar precompiler conditional blocks in the source itself) is worse." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:10:35.393", "Id": "406823", "Score": "0", "body": "\"you completely ignore every possible OpenGL error in your program\" - Well no, not really. I have an error callback. All errors go to stderr. If it breaks and it's the fault of glfw, the reason is seen on the console." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:11:46.673", "Id": "406824", "Score": "0", "body": "\"message about Intel GPUs not supporting OpenGL 3.3 is out-of-date. It can be removed\" - will do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:13:05.467", "Id": "406825", "Score": "0", "body": "\"The main() function has way too much going on\" agreed, and I've already pulled a pile of code out into an init function." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T01:13:53.783", "Id": "210458", "ParentId": "210427", "Score": "2" } }, { "body": "<p>The render loop does a bunch of stuff over and over that only has to happen once. The vertex attribute array (VAA) does not need to be declared every loop. That gets stored in the VAO. The same program is being used every loop as well.</p>\n\n<p>The variable names for the VBO and the VAO weren't very good. It's a VAO. It should be called a VAO.</p>\n\n<p>Every time something is called &lt;thing>ID, it isn't useful to include \"ID\". It makes it easier and conceptually equivalent to just say &lt;thing>. This applies to the shaders, the shader program, and a couple other things.</p>\n\n<p>A shader should be named according to what it does. The vertex shader just copies, so I named it \"copy.vert\". The fragment shader turns everything red, so I called it \"red.frag\". (The file extensions are not a standard, but my choice of .vert and .frag is pretty common. See for example the doom3 source code.)</p>\n\n<p>Here's my version:</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#include &lt;GL/glew.h&gt;\n#include &lt;GLFW/glfw3.h&gt;\n\n\nstatic void glfwCB(int error, const char *desc)\n{\n fprintf(stderr, \"GLFW error 0x%08X: %s\\n\", error, desc);\n}\n\nstatic GLuint loadShader(const char *fn, GLenum shaderType)\n{\n printf(\"Compiling shader '%s'...\\n\", fn);\n\n GLuint shader = glCreateShader(shaderType);\n if (!shader) {\n fprintf(stderr, \"Failed to create shader\\n\");\n exit(1);\n }\n\n FILE *f = fopen(fn, \"r\");\n if (!f) {\n perror(\"Failed to load shader file\");\n exit(1);\n }\n if (fseek(f, 0, SEEK_END)) {\n perror(\"Failed to get file size\");\n exit(1);\n }\n GLint size[1] = {ftell(f)};\n if (size[0] == -1) {\n perror(\"Failed to get file size\");\n exit(1);\n }\n rewind(f);\n char *source = malloc(size[0]);\n if (!source) {\n perror(\"Failed to allocate source memory\");\n exit(1);\n }\n if (fread(source, 1, size[0], f) != size[0]) {\n perror(\"Failed to read file\");\n exit(1);\n }\n if (fclose(f))\n perror(\"Warning: failed to close source file\");\n\n const GLchar *rosource = source;\n glShaderSource(shader, 1, &amp;rosource, size);\n free(source);\n\n glCompileShader(shader);\n\n GLint logLength;\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &amp;logLength);\n if (logLength) {\n GLchar *log = malloc(logLength);\n if (!log) {\n perror(\"Couldn't allocate shader compile log\");\n exit(1);\n }\n glGetShaderInfoLog(shader, logLength, NULL, log);\n printf(\"Shader compile message: %s\\n\", log);\n free(log);\n }\n\n GLint status;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &amp;status);\n if (!status)\n exit(1);\n\n return shader;\n}\n\nstatic GLuint loadShaders(const char *vertex_fn, const char *fragment_fn)\n{\n // Compile the shaders\n GLuint vertexShader = loadShader(vertex_fn, GL_VERTEX_SHADER),\n fragmentShader = loadShader(fragment_fn, GL_FRAGMENT_SHADER);\n\n puts(\"Linking shader program...\");\n\n GLuint program = glCreateProgram();\n glAttachShader(program, vertexShader);\n glAttachShader(program, fragmentShader);\n glLinkProgram(program);\n\n // Check the program\n GLint logLength;\n glGetProgramiv(program, GL_INFO_LOG_LENGTH, &amp;logLength);\n if (logLength &gt; 0) {\n char *log = malloc(logLength);\n if (!log) {\n perror(\"Couldn't allocate shader compile log\");\n exit(1);\n }\n glGetProgramInfoLog(program, logLength, NULL, log);\n printf(\"Shader link message: %s\\n\", log);\n free(log);\n }\n\n GLint status;\n glGetProgramiv(program, GL_LINK_STATUS, &amp;status);\n if (!status)\n exit(1);\n\n glDetachShader(program, vertexShader);\n glDetachShader(program, fragmentShader);\n glDeleteShader(vertexShader);\n glDeleteShader(fragmentShader);\n\n return program;\n}\n\nint main()\n{\n // Set error callback to see more detailed failure info\n glfwSetErrorCallback(glfwCB);\n\n if (!glfwInit())\n {\n fprintf(stderr, \"Failed to initialize GLFW\\n\");\n return -1;\n }\n\n glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing\n\n // To ensure compatiblity, check the output of this command:\n // $ glxinfo | grep 'Max core profile version'\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n // We don't want the old OpenGL\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n // Open a window and create its OpenGL context\n GLFWwindow *window = glfwCreateWindow(800, 600,\n \"Tutorial 02 - Red triangle\", NULL, NULL);\n if (!window)\n {\n fprintf(stderr, \"Failed to open GLFW window. If you have an Intel \"\n \"GPU, are not 3.3 compatible. Try the 2.1 version of the \"\n \"tutorials.\\n\");\n glfwTerminate();\n return -1;\n }\n glfwMakeContextCurrent(window);\n\n glewExperimental = true; // Needed in core profile\n if (glewInit() != GLEW_OK) {\n fprintf(stderr, \"Failed to initialize GLEW\\n\");\n glfwTerminate();\n return -1;\n }\n\n // Ensure we can capture the escape key being pressed below\n glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);\n\n // Dark blue background\n glClearColor(0.0f, 0.0f, 0.4f, 0.0f);\n\n // Make the VAO.\n GLuint vao;\n glGenVertexArrays(1, &amp;vao);\n glBindVertexArray(vao);\n\n // Make the VBO and add it to the VAO.\n GLuint vbo;\n glGenBuffers(1, &amp;vbo);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n\n const GLfloat vertex_buffer_data[] = {\n -1.0f, -1.0f, 0.0f,\n 1.0f, -1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n };\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data),\n vertex_buffer_data, GL_STATIC_DRAW);\n\n // vertex attribute array 0: vertices. No particular reason for 0, but must\n // match the layout in the shader.\n GLuint vaa = 0;\n glEnableVertexAttribArray(vaa);\n glVertexAttribPointer(\n vaa,\n 3, // number of numbers per vertex\n GL_FLOAT, // type\n GL_FALSE, // normalized?\n 0, // stride\n 0 // array buffer offset\n );\n // The VAO is ready.\n\n\n // Create and compile our GLSL program from the shaders.\n GLuint program = loadShaders(\"copy.vert\", \"red.frag\");\n // Use our shader.\n glUseProgram(program);\n\n puts(\"Initialized.\");\n\n do\n {\n // Clear the screen\n glClear(GL_COLOR_BUFFER_BIT);\n\n // Draw the triangle! 3 indices starting at 0 -&gt; 1 triangle.\n glDrawArrays(GL_TRIANGLES, 0, 3);\n\n // Swap buffers\n glfwSwapBuffers(window);\n glfwPollEvents();\n\n // Check if the ESC key was pressed or the window was closed\n } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &amp;&amp;\n !glfwWindowShouldClose(window));\n\n // Cleanup VBO\n glDeleteBuffers(1, &amp;vbo);\n glDeleteVertexArrays(1, &amp;vao);\n glDeleteProgram(program);\n\n // Close OpenGL window and terminate GLFW\n glfwTerminate();\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T22:23:40.490", "Id": "406956", "Score": "0", "body": "Pulling out all of that stuff from the main draw loop into the init section is a massive help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:42:37.093", "Id": "210508", "ParentId": "210427", "Score": "2" } } ]
{ "AcceptedAnswerId": "210508", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T14:48:54.590", "Id": "210427", "Score": "3", "Tags": [ "c", "opengl" ], "Title": "Refining an OpenGL tutorial demo" }
210427
<p>My aim is to simulate the following model by means of a Monte Carlo simulation. I wonder if my R code is correct for generating the data. </p> <p>Could somebody check?</p> <p>The model: </p> <p><span class="math-container">$$Y = \sum_{j=1}^{100} (1+(-1)^{j}A_j X_j + B_j \sin(6X_j)) \sum_{j=1}^{50} (1+X_j/50) + \epsilon$$</span></p> <p>where </p> <ul> <li><span class="math-container">\$A_1, \dots, A_{100}\$</span> are i.i.d. <span class="math-container">\$∼ \text{Unif}([0.6,1])\$</span></li> <li><span class="math-container">\$B_1, \dots, B_{100}\$</span> are i.i.d. <span class="math-container">\$∼ \text{Unif}([0.8,1.2])\$</span> and independent of <span class="math-container">\$A_j\$</span></li> <li><span class="math-container">\$X \sim \text{Unif}([0,1])\$</span> where all components are i.i.d. <span class="math-container">\$∼ \text{Unif}([0, 1])\$</span></li> <li><span class="math-container">\$\epsilon \sim N(0,2)\$</span> and <span class="math-container">\$X_j\$</span> represents the <span class="math-container">\$j\$</span>th column of the design matrix</li> </ul> <p>You can find the model <a href="https://www.researchgate.net/profile/B_Yu/publication/243103448_Boosting_With_the_L_2_Loss/links/540c86ce0cf2f2b29a381fd5/Boosting-With-the-L-2-Loss.pdf" rel="nofollow noreferrer">here, p. 14</a></p> <p>This is my code attempt</p> <pre><code>n_sim &lt;- 10 n_sample &lt;- 200 n_reg &lt;- 100 sd_eps &lt;- sqrt(2) X &lt;- replicate(n_reg, runif(n_sample, 0,1)) A &lt;- replicate(n_reg, runif(1, 0.6,1)) B &lt;- replicate(n_reg, runif(1, 0.8,1.2)) f_1 &lt;- vector(mode = 'integer', length = n_sample) f_2 &lt;- vector(mode = 'integer', length = n_sample) for (d in seq(100)){ part1 &lt;- 1 + (-1)^d*A[d]*X[,d]+B[d]*sin(6*X[,d]) f_1 &lt;- f_1 + part1 } for (d in seq(50)){ part2 &lt;- 1 + X[,d]/50 f_2 &lt;- f_2 + part2 } # True DGP Train ---- f_true &lt;- f_1*f_2 y &lt;- replicate(n_sim, f_true) + replicate(n_sim, rnorm(n_sample, 0,sd_eps)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T21:40:37.263", "Id": "406952", "Score": "0", "body": "I find this model difficult to interpret. It seems ambiguous w.r.t. how many Y values are generated. Another question that came to mind w.r.t. interpreting the model is that the `X ~ Unif([0,1])` has an exponent of 100 in the PDF version of the model: `X ~ Unif([0,1]^100)`. I'm not familiar with that notation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:26:18.653", "Id": "408167", "Score": "0", "body": "The `[0,1]^100` notation in `X ~ Unif([0, 1]^100)` is just shorthand for a setwise product. You'll probably have seen `R^3` as shorthand for the set of 3-dimensional real numbers. It means that `X` is a 100-dimensional vector where each component is uniformly distributed on the set `[0, 1]`" } ]
[ { "body": "<p>The first thing that jumps out from the definition is that, if you have X, A, B and epsilon, you can compute y deterministically. This means you can readily test your implementation. You should always strive to find ways to define pure functions in your R code, and try to use vectorisation instead of <code>for</code> loops.</p>\n\n<p>Based on your existing code, I'll assume for a given model that X is a matrix (n_sample, 100), A and B are vectors of length 100 and epsilon is a vector of length n_sample.</p>\n\n<p>Based on your implementation, the function would look something like</p>\n\n<pre><code>compute_y &lt;- function(X, A, B, epsilon) {\n n_sample &lt;- nrow(X)\n # note that your f_[1|2] stored `double`s not `integers`\n f_1 &lt;- numeric(n_sample)\n f_2 &lt;- numeric(n_sample)\n\n for (d in seq(100)){\n part1 &lt;- 1 + (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])\n f_1 &lt;- f_1 + part1\n }\n for (d in seq(50)){\n part2 &lt;- 1 + X[,d]/50\n f_2 &lt;- f_2 + part2\n }\n\n f_1 * f_2 + epsilon\n}\n</code></pre>\n\n<p>But that's a bit scruffy.</p>\n\n<p>The easiest bit to clean up is the bit that defines <code>f_2</code>:</p>\n\n<pre><code>f_2 &lt;- numeric(n_sample)\nfor (d in seq(50)) {\n part2 &lt;- 1 + X[,d]/50\n f_2 &lt;- f_2 + part2\n}\n</code></pre>\n\n<p>Here you're only using the first 50 columns of <code>X</code>. You could rewrite it as:</p>\n\n<pre><code>f_2 &lt;- numeric(n_sample)\nW &lt;- 1 + X[, 1:50]/50\nfor (d in seq(50)) {\n f_2 &lt;- f_2 + W[,d]\n}\n</code></pre>\n\n<p>But in the latter, you're summing along the rows of <code>W</code>. So you could ditch the <code>for</code> loop altogether:</p>\n\n<pre><code>W &lt;- 1 + X[, 1:50] / 50\nf_2 &lt;- rowSums(W)\n</code></pre>\n\n<p>This gives us:</p>\n\n<pre><code>compute_y &lt;- function(X, A, B, epsilon) {\n n_sample &lt;- nrow(X)\n\n f_1 &lt;- numeric(n_sample)\n\n for (d in seq(100)){\n part1 &lt;- 1 + (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])\n f_1 &lt;- f_1 + part1\n }\n\n f_2 &lt;- rowSums(1 + X[, 1:50] / 50)\n\n f_1 * f_2 + epsilon\n}\n</code></pre>\n\n<p>There is a way to replace the for-loop that computes f_1. </p>\n\n<p>First note you're adding 1 to f_1 one hundred times, so you might as well start with f_1 storing the value 100</p>\n\n<pre><code>f_1 &lt;- rep(100, n_sample)\n\nfor (d in seq(100)){\n part1 &lt;- (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])\n f_1 &lt;- f_1 + part1\n}\n</code></pre>\n\n<p>For speed, I'll just show you how to do it:</p>\n\n<pre><code>tX &lt;- t(X)\na &lt;- colSums(c(-1, 1) * A * tX)\nb &lt;- colSums(B * sin(6 * tX))\nf_1 &lt;- 100 + a + b\n</code></pre>\n\n<p>That code would be a bit faster, but I don't think it looks as clean as your definition of f_1.</p>\n\n<p>If you want you can move the code that defines X, A, B, and epsilon into a model-definition function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:10:10.290", "Id": "211130", "ParentId": "210428", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T15:00:03.420", "Id": "210428", "Score": "1", "Tags": [ "statistics", "r", "simulation" ], "Title": "Simulating data generating process correctly" }
210428
<p>I have built a generator that, using the GitHub API, creates a dictionary containing a tree of all the resources in any GitHub repo. It uses the function <code>git_tree</code>, which takes one argument, a repo-string (<code>repo-author/repo-name</code>). For example, <a href="https://github.com/githubtraining/github-move" rel="nofollow noreferrer">this repo</a> only contains one file, a <code>README</code>. If we pass in the repo-string, and format the end result, this is what we get:</p> <pre><code>&gt;&gt; json.dumps(git_tree("githubtraining/github-move"), indent=3) { "github-move": { "files": [ "README.md" ], "dirs": {} } } </code></pre> <p>You can see that it returns a <code>dict</code> with a key/value pair of <code>{repo_name: tree}</code>. So the <code>github_move</code> item contains a list of all files in that directory, and a dict with more nested directories. Obviously, in this repository there aren't any other directories, so that dict is just blank.</p> <p>For sake of purpose, <a href="https://pastebin.com/TjJuYvrq" rel="nofollow noreferrer">here is the tree</a> of <a href="https://github.com/githubtraining/caption-this" rel="nofollow noreferrer">this repo</a> (it was too long to put in the post). You can see each directory and subdirectory has its own <code>files</code> list and <code>dirs</code> dict.</p> <p>Here's the code (<a href="https://repl.it/@xMikee/Github-Tree" rel="nofollow noreferrer">repl.it online program for testing</a>):</p> <pre><code>import requests from pprint import pprint from functools import reduce import operator import json from itertools import chain, repeat, islice class GitError(Exception): pass def intersperse(delimiter, seq): return list(islice(chain.from_iterable(zip(repeat(delimiter), seq)), 1, None)) def _get_from_dict(dataDict, mapList): return reduce(operator.getitem, mapList, dataDict) def _append_in_dict(dataDict, mapList, value): _get_from_dict(dataDict, mapList[:-1]).append(value) def _get_sha(author, repo): try: return requests.get('https://api.github.com/repos/{}/{}/branches/master'.format(author, repo)).json()['commit']['commit']['tree']['sha'] except KeyError as ex: raise GitError("Invalid author or repo name") from ex def _get_git_tree(author, repo): return requests.get("https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1".format(author, repo, _get_sha(author, repo))).json()["tree"] def git_tree(repostring): author, repo = repostring.split("/") tree = {repo: {"files": [], "dirs": {}}} for token in _get_git_tree(author, repo): if token["type"] == "tree" and "/" not in token["path"]: tree[repo]["dirs"].update({token["path"]: {}}) tree[repo]["dirs"][token["path"]].update({"files": [], "dirs": {}}) elif token["type"] == "tree" and "/" in token["path"]: temp_dict = {} a = list(reversed(token["path"].split("/"))) for k in a[:-1]: temp_dict = {k: {"files": [], "dirs": temp_dict}} tree[repo]["dirs"][a[-1]]["dirs"] = temp_dict elif token["type"] == "blob": path = token["path"].split("/") if len(path) == 1: tree[repo]["files"].append(path[0]) else: dict_path = [repo, "dirs"] + intersperse("dirs", path[:-1]) + ["files", path[-1]] _append_in_dict(tree, dict_path, dict_path[-1]) return tree print(json.dumps(git_tree("githubtraining/caption-this"), indent=3)) </code></pre> <p><em>(The <code>json.dumps</code> is just there for easy viewing, it can be ommited)</em>.</p> <p>My questions:</p> <ol> <li><p>Is it too messy? I look back at this function and it looks a bit cluttered and all over the place. Is that the case, or am I just going crazy?</p></li> <li><p>Do I have any unnecessary code in there?</p></li> <li><p>Is there anything else you deem wrong with the program?</p></li> </ol>
[]
[ { "body": "<p>I see nothing wrong with the code itself, but you're in dire need of docstrings. Arcane functional one-liners like the one in <code>intersperse</code> are impenetrable unless they're well-documented. You'd also benefit from splitting that one into multiple lines.</p>\n\n<p>For strings like this:</p>\n\n<pre><code> return requests.get('https://api.github.com/repos/{}/{}/branches/master'.format(author, repo)).json()['commit']['commit']['tree']['sha']\n</code></pre>\n\n<p>consider rewriting your <code>format</code> call as an f-string; i.e.</p>\n\n<pre><code>f'https://api.github.com/repos/{author}/{repo}/branches/master'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:28:35.217", "Id": "406782", "Score": "0", "body": "The only reason I use formats instead of f-strings is for compatibility for Python 3.x, not just > 3.5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:28:58.357", "Id": "406783", "Score": "0", "body": "But great advice otherwise! Yeah, I probably should have some comments in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:34:55.007", "Id": "406787", "Score": "0", "body": "My philosophy is: if you've made it past the 2x hurdle, you're allowed to target modern 3x, consequences be damned. But ¯\\\\_(ツ)_/¯" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:22:39.160", "Id": "210451", "ParentId": "210435", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/210451/140921\">@Reinderien's answer</a> makes a very good point about docstrings and using those to describe your code: it would be much easier to understand if I knew what the various components are generally intended to do. There's a PEP about docstring formatting: <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>. The comments in the REPL.it link are pretty good except normal comments should come the line <em>before</em> the thing they're commenting, not at the right side of the line.</p>\n\n<p>You could use a more descriptive name than <code>temp_dict</code>: at first I was very confused because you iterated over a dict, continually reassigning it for no reason, but then I realized you were recursively building a tree. I would suggest <code>child_dict</code>.</p>\n\n<p>Similarly, <code>a</code> is not a very descriptive variable name. Even though it's only used once, you should still name it something slightly more descriptive, even if it's only 1 word, like <code>path</code>.</p>\n\n<p>This is a relatively minor <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> infraction, but you use the conditional structure:</p>\n\n<pre><code>if token[\"type\"] == \"tree\" and \"/\" not in token[\"path\"]:\n # path 1 ...\nelif token[\"type\"] == \"tree\" and \"/\" in token[\"path\"]:\n # path 2 ...\n</code></pre>\n\n<p>when you should use the structure:</p>\n\n<pre><code>if token[\"type\"] == \"tree\":\n if \"/\" not in token[\"path\"]:\n # path 1\n else:\n # path 2\n</code></pre>\n\n<p>The second form is preferred both because it's (trivially) more efficient, but more importantly, it makes the dichotomy between the two paths clear for future modification and maintenance. If you pay close attention to your control flow in general, you will often find simplifications like this.</p>\n\n<h2>General miscellaneous improvements</h2>\n\n<p>You imported <code>pprint</code> but never used it. You should remove unused imports. Code linters like <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">PyLint</a> help you avoid things like this.</p>\n\n<p>You should add an <code>if __name__ == '__main__'</code> guard to the bottom of your program, so that people can import your program without running the example. This is a general good practice you should almost always follow.</p>\n\n<p>2 spaces is not my preferred indentation, and <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, the widely-used style guide for Python, happens to agree: <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">\"Use 4 spaces per indentation level\"</a>. It doesn't really make that much difference, but it is <em>slightly</em> easier to read if you're used to it, and it's the style I see other Python programmers use. I do recommend checking out PEP 8 and starting to learn its suggestions if you haven't already, because it helps create more standard looking code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:36:26.803", "Id": "406881", "Score": "1", "body": "Yeah, I was using `pprint` in testing but decided to use `json.dumps` instead and forgot about it (oops!). I'm now creating a module for it (so the `__name__/__main__` won't be necessary), but good point about the `if` structure (I typed that up and my mind was all over the place, I'll change that). Thanks for the tips!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:22:29.263", "Id": "210492", "ParentId": "210435", "Score": "3" } } ]
{ "AcceptedAnswerId": "210492", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T17:18:02.027", "Id": "210435", "Score": "4", "Tags": [ "python", "json", "api", "git" ], "Title": "GitHub repo tree generator" }
210435
<p>I have a Repository class which looks like this:</p> <pre><code>public class Repository extends Observable { private List&lt;Event&gt; events; private List&lt;Article&gt; articles; private List&lt;Article&gt; sportArticles; private List&lt;Article&gt; fitnessArticles; private List&lt;Article&gt; governmentArticles; private Article mainArticle; private Configuration config; public Repository() { loadRepository(); } private void loadRepository() { ExecutorService exService = Executors.newSingleThreadExecutor(); exService.submit(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).build(); final Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Calendar.class, new CalendarGson()).create(); final AtomicBoolean error = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(7); Request.Builder requestbuilder = new Request.Builder(); Request articlesRequest = requestbuilder.url("https://apiurlarticles").build(); Request eventsRequest = requestbuilder.url("https://apiurlevents").build(); Request sportArticlesRequest = requestbuilder.url("https://apiurlsports").build(); Request fitnessArticlesRequest = requestbuilder.url("https://apiurlfitness").build(); Request governmentArticlesrequest = requestbuilder.url("https://apiurlgovernment").build(); Request mainArticleRequest = requestbuilder.url("https://apiurlmain").build(); Request configurationRequest = requestbuilder.url("https://apiurlconfig").build(); //Article Request client.newCall(articlesRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { articles = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Events Request client.newCall(eventsrequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { events = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Event&gt;&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Sports Request client.newCall(sportArticlesRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { sportArticles = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Fitness Request client.newCall(fitnessArticlesRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { fitnessArticles = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Government Request client.newCall(governmentArticlesrequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { governmentArticles = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Main Article Request client.newCall(mainArticleRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { mainArticle = gson.fromJson(body.string(), new TypeToken&lt;Article&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); //Configuration request client.newCall(configurationRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { error.set(true); latch.countDown(); } @Override public void onResponse(Call call, Response response) { try { ResponseBody body = response.body(); if (response.code() != 200 || body == null) { error.set(true); } else { config = gson.fromJson(body.string(), new TypeToken&lt;Configuration&gt;() { }.getType()); } } catch (IOException | JsonSyntaxException e) { error.set(true); } latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { error.set(true); } notifyObservers(error.get() ? HTTPRequestStatus.HTTPERROR : HTTPRequestStatus.OK); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { notifyObservers(HTTPRequestStatus.TLSERROR); } } }); exService.shutdown(); } } </code></pre> <p>This code calls several HTTP requests asynchronously and wait for all of them to conclude. If any request fails it notifies with an error, otherwise success. These requests returns JSON and I parse them using <code>Gson</code>.</p> <p>For simplicity I have only showed two requests, however I want to refactor this code for any number of requests. There is a lot of similar code, but I can't figure a way to refactor it. I have already tried to create a custom <code>Callback</code> class however I can't figure a way to pass a <code>Type</code> and return the parsed value.</p> <p>How would you approach this one?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T19:36:36.203", "Id": "406778", "Score": "2", "body": "Simplicity isn't usually the way to go here. I recommend you show the rest of your code. You might get different answers based on the less \"simple\" code than you would with what you currently have. Also please change the title to describe What your code *Does* as apposed to your goal. (Almost everyone wants to refactor their code.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:55:15.697", "Id": "406795", "Score": "0", "body": "@bruglesco The difference between this code and the actual one is that there are like 10 `Request` Objects and 10 `client.newCalls(request)` , should I include them anyway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T21:17:53.627", "Id": "406797", "Score": "0", "body": "Yes. You should." } ]
[ { "body": "<p>Welcome to Code Review!</p>\n\n<p>Thanks for sharing your code.</p>\n\n<p>As you observed the main problem is code duplication.</p>\n\n<p>We have basically two options to solve that problem. Both of them use the basic approach to separate the <em>common code</em> from the <em>different code</em> and \"inject\" the <em>differing code</em> into the <em>common code</em>.</p>\n\n<h1>prepare injecting differing code</h1>\n\n<p>When looking at your code the only difference between the <code>//Article Request</code> and the <code>//Events Request</code> are these lines:</p>\n\n<pre><code>//Article Request\narticles = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() {\n }.getType());\n\n//Events Request \nevents = gson.fromJson(body.string(), new TypeToken&lt;List&lt;Event&gt;&gt;() {\n }.getType());\n</code></pre>\n\n<p>One problem here is that you <em>change</em> the objects pointed to by the member variables <code>articles</code> and <code>events</code>. We could make is easier to change if the objects would be reused:</p>\n\n<pre><code>//Article Request\narticles.clear();\narticles.addAll(gson.fromJson(body.string(), new TypeToken&lt;List&lt;Article&gt;&gt;() {\n }.getType()));\n\n//Events Request \nevents.clear();\nevents.addAll(gson.fromJson(body.string(), new TypeToken&lt;List&lt;Event&gt;&gt;() {\n }.getType()));\n</code></pre>\n\n<p>now we can extract one of that parts to a new Method using the IDEs <em>automated refactoring</em> \"extract method\":</p>\n\n<pre><code>private void deserializeJson(\n List&lt;Event&gt; events,\n Gson gson,\n ResponseBody body\n){\n events.clear();\n events.addAll(gson.fromJson(body.string(), new TypeToken&lt;List&lt;Event&gt;&gt;() {\n }.getType()));\n} \n\n//Events Request \n// ...\n} else {\n deserializeJson((List&lt;Event&gt;)events,\n Gson gson,\n ResponseBody body);\n}\n</code></pre>\n\n<p>Next we have to mat this new private method \"generic\":</p>\n\n<pre><code>private &lt;L extends List&gt; void deserializeJson(\n L events,\n Gson gson,\n ResponseBody body\n){\n events.clear();\n events.addAll(gson.fromJson(body.string(), new TypeToken&lt;L&gt;() {\n }.getType()));\n} \n</code></pre>\n\n<p>Now we can change toe other place too:</p>\n\n<pre><code>//Articles Request\n// ...\n} else {\n deserializeJson((List&lt;Article&gt;)articles);\n}\n</code></pre>\n\n<p>from here we have two options:</p>\n\n<ol>\n<li>consolidating the common code in a single generic typed method.</li>\n<li>puttig the difering code into an \"specialized classes\" providing the differing behavior via an common <em>interface</em>.</li>\n</ol>\n\n<h1>common code in a single generic typed method</h1>\n\n<p>We basically do he same as above: we extract the <code>//Events Request</code> section or the <code>//Articles Request</code> into a new private method and make it \"generic\"</p>\n\n<pre><code>private &lt;L extends List&gt; void deserializeFromJson(\n L theList, \n OkHttpClient client, \n Gson gson \n){\n client.newCall(articlesrequest).enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n error.set(true);\n latch.countDown();\n }\n @Override\n public void onResponse(Call call, Response response) {\n try {\n ResponseBody body = response.body();\n if (response.code() != 200 || body == null) {\n error.set(true);\n } else {\n deserializeJson((L)theList, gson, body);\n }\n } catch (IOException | JsonSyntaxException e) {\n error.set(true);\n }\n latch.countDown();\n }\n });\n}\n\n\n//Article Request\ndeserializeFromJson(\n (List&lt;Articles&gt;)articles,\n client,\n gson\n);\n\n//Events Request\nclient.newCall(eventsrequest).enqueue(new Callback() {\n // ...\n</code></pre>\n\n<p>and then also replace the other part:</p>\n\n<pre><code>//Article Request\ndeserializeFromJson(\n (List&lt;Articles&gt;)articles,\n client,\n gson\n);\n\n//Events Request\ndeserializeFromJson(\n (List&lt;Event&gt;)events,\n client,\n gson\n);\n</code></pre>\n\n<h1>creating specialized classes with interface</h1>\n\n<p>for this we have to move the private method created in the first section into a new <em>inner class</em></p>\n\n<pre><code>class your current class:\n\n private static class JsonDeserializer&lt;T&gt; {\n\n void deserialize(\n List&lt;T&gt; theList,\n Gson gson,\n ResponseBody body\n ){\n theList.clear();\n theList.addAll(gson.fromJson(body.string(), new TypeToken&lt;List&lt;T&gt;&gt;() {\n }.getType()));\n\n }\n }\n // ...\n\n //Articles Request\n // ...\n } else {\n new JsonDeserializer&lt;Article&gt;().deserialize(articles, gson, body);\n }\n //...\n</code></pre>\n\n<p>Since <code>articles</code> and <code>events</code> are <em>member variables</em> I'd rather have them as <em>constructor parameters</em> in the new class: </p>\n\n<pre><code>class your current class:\n\n private static class JsonDeserializer&lt;T&gt; {\n private final List&lt;T&gt; theList;\n JsonDeserializer( List&lt;T&gt; theList){\n this.theList = theList;\n }\n\n void deserialize(\n Gson gson,\n ResponseBody body\n ){\n theList.clear();\n theList.addAll(gson.fromJson(body.string(), new TypeToken&lt;List&lt;T&gt;&gt;() {\n }.getType()));\n\n }\n }\n // ...\n\n //Articles Request\n // ...\n } else {\n new JsonDeserializer&lt;Article&gt;(articles).deserialize(gson, body);\n }\n //...\n //Event Request\n // ...\n } else {\n new JsonDeserializer&lt;Event&gt;(eventss).deserialize(gson, body);\n }\n //...\n</code></pre>\n\n<p>Now we can create the <code>JsonDeserializer</code> instances at the top of the method:</p>\n\n<pre><code>private void loadRepository() {\n JsonDeserializer&lt;Article&gt; articleDeserializer = new JsonDeserializer&lt;&gt;(articles);\n JsonDeserializer&lt;Event&gt; eventDeserializer = new JsonDeserializer&lt;&gt;(event);\n ExecutorService exService = Executors.newSingleThreadExecutor();\n // ...\n //Articles Request\n // ...\n } else {\n articleDeserializer.deserialize(gson, body);\n }\n //...\n //Event Request\n // ...\n } else {\n eventDeserializer.deserialize(gson, body);\n }\n //...\n</code></pre>\n\n<p>Now the only difference left in <code>//Articles Request</code> section and <code>//Event Request</code> section is the <em>name</em> of the variable. So we can put the two <code>JsonDeserializer</code> instances into a <em>collection</em> and apply the *common code * as a loop:</p>\n\n<pre><code>private void loadRepository() {\n JsonDeserializer&lt;?&gt; deserializers = Arrays.asList( \n new JsonDeserializer&lt;Article&gt;(articles),\n new JsonDeserializer&lt;Event&gt;(event)\n );\n ExecutorService exService = Executors.newSingleThreadExecutor();\n// ...\n\n Request eventsrequest = requestbuilder.url(\"https://apiurlevents\").build();\n\n //Article Request changed to loop\n for(JsonDeserializer&lt;?&gt; deserializer: deserializers){\n client.newCall(articlesrequest).enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n error.set(true);\n latch.countDown();\n }\n @Override\n public void onResponse(Call call, Response response) {\n try {\n ResponseBody body = response.body();\n if (response.code() != 200 || body == null) {\n error.set(true);\n } else {\n deserializer.deserialize(gson, body);\n }\n } catch (IOException | JsonSyntaxException e) {\n error.set(true);\n }\n latch.countDown();\n }\n });\n }\n try {\n latch.await();\n } catch (InterruptedException e) {\n error.set(true);\n }\n</code></pre>\n\n<p>New document types are just new instances in the <em>collection</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:12:23.153", "Id": "406808", "Score": "0", "body": "Really appreciate your help. That refactor would work, however not all my class member variables are from type `List`. Added more requests examples. If I replace `List<T>` to `<T>` would that work? Ofc I would declare JsonDeserializer as `<List<Article>>` for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:20:49.950", "Id": "406809", "Score": "0", "body": "@Exprove *however not all my class member variables are from type List* I'd create another `JsonDeserializer` that deserializes the generic type directly. Problem might be to get the de-serialized object out of the `JsonDeserializer` instance. replacing the `List` parameter of the constructor with a *Listener* might work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T22:02:32.773", "Id": "210454", "ParentId": "210437", "Score": "3" } }, { "body": "<p>You could use a <a href=\"https://developer.android.com/reference/java/util/concurrent/CompletableFuture\" rel=\"nofollow noreferrer\">CompletableFuture</a> for this. Make each call return a completed future with the body, or an exceptionally completed future with an error:</p>\n\n<pre><code>private CompletableFuture&lt;String&gt; call(String url) {\n CompletableFuture&lt;String&gt; future = new CompletableFuture&lt;&gt;();\n\n OkHttpClient client = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).build();\n client.newCall(requestbuilder.url(url).build()).enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n future.completeExceptionally(e);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n try {\n ResponseBody body = response.body();\n if (response.code() != 200 || body == null) {\n throw new IOException(\"Http error\");\n } else {\n future.complete(body.string());\n }\n } catch (IOException | JsonSyntaxException e) {\n future.completeExceptionally(e);\n }\n }\n });\n\n return future;\n}\n</code></pre>\n\n<p>Then add a generic method to make the calls and deserialize the results:</p>\n\n<pre><code>private &lt;T&gt; Future&lt;T&gt; callAndDeserialize(String url, Gson gson, TypeToken&lt;T&gt; typeToken) {\n CompletableFuture&lt;String&gt; future = call(url);\n return future.thenApply(new Function&lt;String, T&gt;() {\n public T apply(String body) {\n return gson.fromJson(body, typeToken.getType()));\n }\n });\n}\n</code></pre>\n\n<p>The <code>loadRepository</code> code would then be something like:</p>\n\n<pre><code>final Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Calendar.class, new CalendarGson()).create();\n\nFuture&lt;List&lt;Article&gt;&gt; articlesFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;List&lt;Article&gt;&gt;() {});\nFuture&lt;List&lt;Event&gt;&gt; eventsFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;List&lt;Event&gt;&gt;() {});\nFuture&lt;List&lt;Article&gt;&gt; sportsFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;List&lt;Article&gt;&gt;() {});\nFuture&lt;List&lt;Article&gt;&gt; fitnessFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;List&lt;Article&gt;&gt;() {});\nFuture&lt;List&lt;Article&gt;&gt; governmentFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;List&lt;Article&gt;&gt;() {});\nFuture&lt;Article&gt; mainArticleFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;Article&gt;() {});\nFuture&lt;Configuration&gt; configurationFuture = callAndDeserialize(\"https://apiurlarticles\", gson, new TypeToken&lt;Configuration&gt;() {});\n\ntry {\n articles = articlesFuture.get();\n events = eventsFuture.get();\n sportArticles = sportsFuture.get();\n fitnessArticles = fitnessFuture.get();\n governmentArticles = governmentFuture.get();\n mainArticle = mainArticleFuture.get();\n config = configurationFuture.get();\n\n notifyObservers(HTTPRequestStatus.OK);\n} catch (ExecutionException e) {\n if(e.getCause() instanceof KeyManagementException || e.getCause() instanceof NoSuchAlgorithmException || e.getCause() instanceof KeyStoreException) {\n notifyObservers(HTTPRequestStatus.TLSERROR);\n } else {\n notifyObservers(HTTPRequestStatus.HTTPERROR);\n }\n}\n</code></pre>\n\n<p>The <code>ExecutionException</code> at the end now retains the exception messages, causes and stacktraces. In case there's any unexpected errors you need to debug, you can also <a href=\"https://developer.android.com/reference/android/util/Log\" rel=\"nofollow noreferrer\">log</a> this exception as well notifying the observers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T13:12:47.153", "Id": "210638", "ParentId": "210437", "Score": "2" } } ]
{ "AcceptedAnswerId": "210454", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T17:51:27.400", "Id": "210437", "Score": "2", "Tags": [ "java", "android", "gson" ], "Title": "Call multiple asynchronous HTTP requests and wait for the result" }
210437
<p>I have a computer that roams, but needs to have an FQDN attached to it for certain reasons such as email system integrations or testing email via a testing SMTP server that requires valid FQDNs and HELOs.</p> <p>My domain(s) are all on CloudFlare, so I wrote an adapted version of another script I had to wrap around CloudFlare's API so I can update DNS entries and such.</p> <p>This has a few requirements from PyPI:</p> <ul> <li><code>ipaddress</code></li> <li>CloudFlare Python wrapper (<code>cloudflare</code> on PyPI)</li> </ul> <p>This script also has two other requirements to really function, but I can guarantee you that both of these components work:</p> <ul> <li>WhatIsMyIP.com API key for IP lookup capabilities</li> <li>CloudFlare Account with API key</li> </ul> <p>Note that any sensitive information (such as login credentials or API keys) have been obfuscated in the below code. Additional bits can be provided as needed.</p> <p>(There is a <strong>known limitation</strong> that this does not work for IPv6 addresses - I'm working on adding this, but this current iteration of the script does not have IPv6 in it.)</p> <p>Critiques to improve the script are welcome, but keep in mind that I abide by PEP8 about linelengths &lt;= 120 chars long because this is permissible if users on a team/development group agree on the longer length.</p> <pre><code>#!/usr/bin/python3 import CloudFlare import ipaddress import json import shlex import subprocess as sp import syslog import urllib.error import urllib.request from typing import AnyStr, Optional # Used for `dig` queries because we are using CloudFlare, and we need actual DNS results, not CF results for checking # the existence of an IP address currently. Therefore, we use Google DNS here. DNS_NAMESERVER = "8.8.8.8" # ZONE = root domain # DOMAIN = hostname within root domain. ZONE = "domain.tld" DOMAIN = "subdomain" # These next two are for WHATISMYIP - API Endpoints. WHATISMYIP = "https://api.whatismyip.com/ip.php?key={key}&amp;output=json" API_KEYS = ['WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY', 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'] # Wrapper function around syslog to allow default priority of INFO, but # has the ability to change the priority if wished for a given message. def _syslog(message: AnyStr, priority: int = syslog.LOG_INFO) -&gt; None: syslog.syslog(priority, message) # Horribly unnecessary wrapper function around `exit` which calls the # "Process Ended" log message, and then actually exists with the given # exit code (by default it exits on 0 - the "Success" exit code) def _exit(code=0): # type: (int) -&gt; None _syslog("DDNS Update Process Ended.") exit(code) # Singular Error handler for EmptyDNSResponse (could probably be a bare # LookupError, but EmptyDNSResponse is nicer...) class EmptyDNSResponse(LookupError): pass # No changes from base LookupError # Get current public IP address with WhatIsMyIP.com API def _get_current_ip_address(): # type: () -&gt; Optional[AnyStr] for key in API_KEYS: _syslog("Attempting lookup with API key {key}...".format(key=key)) try: with urllib.request.urlopen(WHATISMYIP.format(key=key)) as req: data = json.loads(req.read().decode("UTF-8")) ipaddr = data['ip_address'][1]['result'] except (urllib.error.URLError, urllib.error.HTTPError): _syslog("Could not look up public IP address, aborting update process.") _exit(1) try: # noinspection PyUnboundLocalVariable ipaddress.ip_address(ipaddr) except ValueError: if data is '0': _syslog("API key was not entered for lookup, this is a programming error.", syslog.LOG_CRIT) _exit(5) if data in ['1', '2']: _syslog("API Key Invalid or Inactive, attempting to try other keys...", syslog.LOG_WARNING) if data is '3': _syslog("API key lookup threshold reached, skipping to next API key...", syslog.LOG_WARNING) if data in ['4', '5']: _syslog("Query is bad, it needs 'input', which we can't do. This is a critical issue.", syslog.LOG_CRIT) _exit(6) if data is '6': _syslog("There was an unknown error with the WhatIsMyIP API, contact their support.", syslog.LOG_CRIT) _exit(7) continue # Try next API key return data # Check if the DNS entry for a given hostname differs from current IP, # and if it has no A record or it differs, return "True". Otherwise, # return False, and assume the IP address doesn't differ. def _dns_ip_address_status(host: AnyStr, curip: Optional[AnyStr] = None) -&gt; AnyStr: if not curip: raise RuntimeError("Empty IP!") dnsip = "" try: dnsip = sp.check_output( shlex.split('dig +short @{nameserver} A {hostname}'.format(nameserver=DNS_NAMESERVER, hostname=host)) ).decode('utf-8').strip() if dnsip == '': _syslog('Current IP record for \'{hostname}\': [NXDOMAIN]'.format(hostname=host), syslog.LOG_INFO) raise EmptyDNSResponse else: _syslog('Current IP record for \'{hostname}\': {record}'.format(hostname=host, record=dnsip)) except sp.CalledProcessError as err: syslog.syslog(syslog.LOG_CRIT, 'Subprocess error when calling `dig`, exiting.') print("Subprocess error when calling dig: {}".format(err)) _exit(2) # Exit on code 10: Can't continue if subprocess isn't working... except EmptyDNSResponse: syslog.syslog(syslog.LOG_INFO, "Empty DNS response, assuming that entry doesn't exist.") # Assume that the IP address differs or doesn't exist. return "NXDOMAIN" if dnsip == curip: return "UPTODATE" else: return "NEEDSUPDATED" # CloudFlare has different functions for Add and Change. Determine if we exist first. def _update_cloudflare(cf: CloudFlare.CloudFlare, domain: AnyStr = ZONE, hostname: AnyStr = DOMAIN): # Validate that zone exists first. zone_id = None try: zone = cf.zones.get(params={'name': domain}) if len(zone) &lt; 1: raise LookupError else: zone_id = zone[0]['id'] except LookupError: syslog.syslog(syslog.LOG_ERR, "No valid zone data on CloudFlare, root domain zone might not exist.") _exit(3) curip = _get_current_ip_address() if not curip: syslog.syslog(syslog.LOG_ERR, "Could not find valid current IP address, aborting update process.") _exit(2) fqdn = hostname + '.' + domain ip_status = _dns_ip_address_status(host=fqdn, curip=curip) if ip_status == "NXDOMAIN": # Add new record: POST cf.zones.dns_records.post(zone_id, data={'name': hostname, 'type': 'A', 'content': curip, 'proxiable': False, 'proxied': False}) elif ip_status == "NEEDSUPDATED": dns_records = cf.zones.dns_records.get(zone_id, params={'name': fqdn}) if len(dns_records) != 1: syslog.syslog(syslog.LOG_ERR, "Invalid number of records returned, this might be a CF DNS records issue, check it.") _exit(4) dns_record_id = dns_records[0]['id'] cf.zones.dns_records.delete(zone_id, dns_record_id) cf.zones.dns_records.post(zone_id, data={'name': hostname, 'type': 'A', 'content': curip, 'proxiable': False, 'proxied': False}) elif ip_status == "UPTODATE": syslog.syslog(syslog.LOG_INFO, "DNS record for {} does not need adjusted.".format(fqdn)) pass def execute(): syslog.openlog(ident='py-ddns-ipupdate', logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON) _syslog("DDNS Update Process Started.") # Test if Internet is up by reaching to Google. try: req = urllib.request.urlopen('https://google.com', timeout=5) req.close() except urllib.error.URLError: _syslog("No Internet connection available, aborting update process.") _exit(1) # Get current public IP ip = _get_current_ip_address() if '.' not in ip and ':' not in ip: _syslog("Unexpected response from WhatIsMyIP.com API: {response}".format(response=ip)) _exit(1) else: _syslog("Current Public IP: {ip}".format(ip=ip)) _update_cloudflare(CloudFlare.CloudFlare(email='valid@email.address', token='CloudFlareAPITokenKey', debug=False)) _exit(0) if __name__ == "__main__": execute() </code></pre>
[]
[ { "body": "<blockquote>\n <p><code># Horribly unnecessary wrapper</code></p>\n</blockquote>\n\n<p>You're right. Don't write your own <code>exit</code>. Since <code>exit</code> itself generates an exception to terminate the program, simply put your <code>_syslog</code> call in a <code>finally</code> at the top level.</p>\n\n<pre><code>with urllib.request.urlopen\n</code></pre>\n\n<p>Unless you have a really good (and obscure) reason, never use <code>urllib</code>. Use <code>requests</code>. It's saner in every way.</p>\n\n<pre><code>if data in ['1', '2']:\n</code></pre>\n\n<p>Technically, since you're testing membership, make this a set:</p>\n\n<pre><code>if data in {'1', '2'}:\n</code></pre>\n\n<p>As for this function documentation:</p>\n\n<pre><code># Check if the DNS entry for a given hostname differs from current IP,\n# and if it has no A record or it differs, return \"True\". Otherwise,\n# return False, and assume the IP address doesn't differ.\n</code></pre>\n\n<p>Fine... but this doesn't do what you say it does. It returns strings, not booleans. I'd offer that neither is appropriate, and that you should be returning an enum instead.</p>\n\n<pre><code> if len(zone) &lt; 1:\n raise LookupError\n else:\n zone_id = zone[0]['id']\n</code></pre>\n\n<p>Get rid of the <code>else</code>; you've previously raised.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:50:38.843", "Id": "406814", "Score": "0", "body": "Agreed with these suggestions, and I'll work on improving. The headache I ran into with requests was this was originally written on an *OLD* Python3 which didn't have `requests` available. I haven't updated it to 3.7 standards yet... or at least, the `urllib` bits yet." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:12:53.957", "Id": "210448", "ParentId": "210442", "Score": "3" } }, { "body": "<h1>Docstrings</h1>\n\n<p>You should really consider switching to <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">Docstrings</a> instead of using your current documentation method. (Note that using Docstrings will give the function a <code>.__doc__</code> property which can be used for a variety including documentation generation). So for instance:</p>\n\n<pre><code># Wrapper function around syslog to allow default priority of INFO, but\n# has the ability to change the priority if wished for a given message.\ndef _syslog(message: AnyStr, priority: int = syslog.LOG_INFO) -&gt; None:\n syslog.syslog(priority, message)\n</code></pre>\n\n<p>Would (well, almost) become:</p>\n\n<pre><code>def _syslog(message: AnyStr, priority: int = syslog.LOG_INFO) -&gt; None:\n \"\"\"\n Wrapper function around syslog to allow default priority of INFO, but\n has the ability to change the priority if wished for a given message.\n \"\"\"\n syslog.syslog(priority, message)\n</code></pre>\n\n<p>However, there are couple remarks to make:</p>\n\n<ol>\n<li>The Docstring comment I have linked tends to have the summary on the same line as the <code>\"\"\"</code>, but <a href=\"https://stackoverflow.com/a/24385103/667648\">many conventions disregard this</a>.</li>\n<li>You should probably mention the arguments and return values (when applicable of course.)</li>\n</ol>\n\n<h1>Wrap it in a class?</h1>\n\n<p>Admittedly, I don't know too much about the domain you are working with, and similarly, I don't really like promoting OOP since I find often too overused, but here is my rational:</p>\n\n<ol>\n<li>You have a lot of globals like <code>DNS_NAMESERVER</code>, <code>ZONE</code>, <code>DOMAIN</code> etc, these could be given default values in your class and made private variables. (On the other hand, you might actually want these constant, in which case ignore this.)</li>\n<li>A lot of your functions have default values which could be instead omitted and placed as class variables.</li>\n</ol>\n\n<p>On the other hand, I may not know enough about what you're doing. If you disagree with this assessment, just look at the first critique.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:49:44.983", "Id": "406812", "Score": "0", "body": "Class Wrap > 1: These are constants, not a class. This is just a script which I utilize for my dynamic DNS updates to CLoudFlare on a cronjob. Eventually there will be more than one hostname being updated, at which case #2 will have non-default inputs and I'll revise the script. I do agree with the docstring notes though, I'll work on that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:13:48.180", "Id": "210449", "ParentId": "210442", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T18:43:57.410", "Id": "210442", "Score": "5", "Tags": [ "python", "python-3.x", "networking", "client" ], "Title": "CloudFlare Dynamic DNS Update Script in Python 3" }
210442
<p>I have created a python program that prints a vertical bar graph made from fields and values inputted by the user. It works by first creating a horizontal bar graph and then going through each layer and determining whether to print a letter, a <code>"|"</code>, a <code>"_"</code>, or a space. I would appreciate any feedback on the program and things I could do to improve it. </p> <pre><code>import re feilds = input("Input| ex: dogs,10 cats,23 birds,67\n").strip() while not re.match("^(\w+,\d+ ?)+$", feilds): feilds = input("invalid input, use this format:\nfeild,value feild,value feild,value...\n").strip() width = int(input("How wide is your output window in characters? ")) scale = float(input("Scale: ")) vals = dict([feild.split(",") for feild in feilds.split(" ")]) for k, v in vals.items(): vals[k] = int(v) spacing = int(width / len(vals.keys())) horizontal = ["-" * int(v * scale) + "|" + k[::-1] for k, v in vals.items()] vertical = [] for x in reversed(range(len(max(horizontal, key=len)))): layer = [] for val in horizontal: try: if val[x] == "-": layer.append("|") elif val[x] == "|": layer.append("_") else: layer.append(val[x]) except IndexError: layer.append(" ") vertical.append(layer) print("\n") print("\n".join((" " * (spacing - 1)).join(layer) for layer in vertical)) </code></pre> <p>ex:</p> <p>input:</p> <pre><code>dogs,20 cats,18 fish,25 birds,10 80 .5 </code></pre> <p>output:</p> <pre><code> f i d s o c h g a _ s t | _ s | b | _ | i | | | r | | | d | | | s | | | _ | | | | | | | | | | | | | | | | | | | | </code></pre> <p><strong>NOTE</strong>: output might be messed up if the width is off by a lot. Make sure to input a width close to what it is.</p>
[]
[ { "body": "<p><code>feilds</code> is spelled <code>fields</code>. IDEs like PyCharm will identify spelling mistakes in variables.</p>\n\n<p>Why is there a <code>?</code> after the space in your regex? Currently I believe it will pass input looking like</p>\n\n<pre><code>key,1key,2key,3\n</code></pre>\n\n<p>So you have to fix that edge case, probably by adding a final key-value pair with no space, and making the space in the first group mandatory.</p>\n\n<p>This:</p>\n\n<pre><code>vals = dict([feild.split(\",\") for feild in feilds.split(\" \")])\nfor k, v in vals.items():\n vals[k] = int(v)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>vals = {k: int(v)\n for field in fields.split(' ')\n for k, v in field.split(',')}\n</code></pre>\n\n<p>i.e. don't construct a list in memory only to throw it away.</p>\n\n<p>This:</p>\n\n<pre><code>spacing = int(width / len(vals.keys()))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>spacing = width // len(vals)\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>for x in reversed(range(len(max(horizontal, key=len)))):\n</code></pre>\n\n<p>doesn't actually need an index at all, since you don't use it. Also, lumping everything into one line is confusing. Instead:</p>\n\n<pre><code>longest_horz = max(len(h) for h in horz)\nfor v in val[longest_horz-1::-1]:\n</code></pre>\n\n<p>Then use <code>v</code> instead of <code>val[x]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T19:58:32.797", "Id": "210446", "ParentId": "210443", "Score": "3" } } ]
{ "AcceptedAnswerId": "210446", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T18:52:40.353", "Id": "210443", "Score": "1", "Tags": [ "python", "graph" ], "Title": "Vertical Bar Graph Generator" }
210443
<p>I have a log file which is constantly updated with new lines of data. I need to get new added data in java as soon as it's written. For now my solution is:</p> <pre><code>public static void readNonStop(String filename, boolean goToEnd, FileReadCallback readCallback) { if(readCallback == null) { return; } try { BufferedReader br = new BufferedReader(new FileReader(filename)); try { String line = br.readLine(); int lineNumber = 0; if(goToEnd) { while(br.readLine() != null) {} } while (true) { if(line != null) { readCallback.onRead(lineNumber++, line); } else { Thread.sleep(1); } line = br.readLine(); } } finally { br.close(); } } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>But I have a feeling that there should be a better way. I don't like the idea of a constant running loop with a "sleep" inside and would prefer some sort of an event driven approach.</p> <p>If I rely on FileSystem events to reopen the file each time it is modified, it introduces a delay.</p> <p>What is the correct way of doing it for this situation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:30:03.907", "Id": "406785", "Score": "1", "body": "Consider [Tailer](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/Tailer.html) class from Apache Commons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:33:03.790", "Id": "406786", "Score": "0", "body": "Welcome to Code Review. I hope you get some good reviews, and I hope to see more of your contributions here in future!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:43:07.937", "Id": "406789", "Score": "0", "body": "@vnp, wow, looks like what I need. While a bit more robust, `Tailer` uses the same logic as my code, it reads in a loop with a `Thread.sleep` delay. But it feels good to confirm that I had the right idea, thanks! @Zeta, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:45:21.530", "Id": "406790", "Score": "1", "body": "Maybe there is a \"native\" solution too: https://dzone.com/articles/how-watch-file-system-changes or https://docs.oracle.com/javase/tutorial/essential/io/notification.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:48:15.553", "Id": "406792", "Score": "1", "body": "`WatcherService` introduces a delay up to 6 seconds in my tests, so unfortunately it is not an option. Looks like I will go with a looped read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T21:40:16.810", "Id": "406802", "Score": "0", "body": "Aren’t you missing `lineNumber++;` in your `goToEnd` while loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:55:10.503", "Id": "406841", "Score": "0", "body": "@AJNeufeld, sorry, the line number is not relevant anymore. I've updated my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T19:21:21.130", "Id": "406940", "Score": "0", "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": "<h3><code>try</code>-with-resources</h3>\n\n<p><code>BufferedReader</code> implements <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html\" rel=\"nofollow noreferrer\"><code>AutoCloseable</code></a>, so instead of </p>\n\n<blockquote>\n<pre><code> try {\n BufferedReader br = new BufferedReader(new FileReader(filename));\n try {\n</code></pre>\n</blockquote>\n\n<p>You can say </p>\n\n<pre><code> try (BufferedReader br = new BufferedReader(new FileReader(filename))) {\n</code></pre>\n\n<p>and then get rid of your <code>finally</code> block. </p>\n\n<blockquote>\n<pre><code> } finally {\n br.close();\n }\n</code></pre>\n</blockquote>\n\n<p>Also, this should allow you to merge the two <code>try</code> statements into one, as the resource declaration is inside the scope of the <code>try</code> if it throws an exception. </p>\n\n<h3>Odd behavior</h3>\n\n<blockquote>\n<pre><code> String line = br.readLine();\n int lineNumber = 0;\n</code></pre>\n</blockquote>\n\n<p>So you read the first line of the file. Then, if a Boolean is true, you skip all the other lines of the file without counting them (even though you just declared a variable to count them). Then you process the first line of the file. Why not </p>\n\n<pre><code> if (goToEnd) {\n while (br.readLine() != null) {}\n }\n\n // we only want to count lines past the current end of file\n int lineNumber = 0;\n while (true) {\n String line = br.readline();\n while (line == null) {\n Thread.sleep(1);\n line = br.readLine();\n }\n\n readCallback.onRead(lineNumber++, line);\n }\n</code></pre>\n\n<p>Now it's clearer that <code>lineNumber</code> has nothing to do with the part before the end of the current file. And we don't process the first line of the file and then a much later line. Each <code>line</code> lasts only one iteration of the loop. </p>\n\n<p>If the condition is false, a <code>while</code> acts just like an <code>if</code>. But if the condition is true, we can stay in the loop. </p>\n\n<p>If this is not the behavior that you want, please add comments to your code explaining why. E.g. \"We always need to read the first line of the file as line number 0, even if we skip the rest of the existing lines. This is because the first line has the column headers.\" </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:55:47.317", "Id": "406842", "Score": "0", "body": "Thanks for your answer, though lineNumber is not relevant anymore." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T02:10:02.673", "Id": "210459", "ParentId": "210444", "Score": "1" } }, { "body": "<p>You can use the Java <code>WatchService</code> as described <a href=\"https://docs.oracle.com/javase/tutorial/essential/io/notification.html\" rel=\"nofollow noreferrer\">here</a>. You said that <code>WatchService</code> is too slow for you. There are other people who have had that problem and resolved it <a href=\"https://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else\">https://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else</a><a href=\"https://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else\">in this thread</a>.</p>\n\n<p>On a side note, consider using <code>ScheduledThreadPoolExecutor</code> rather than <code>Thread.sleep</code>. The former will recreate threads if they are killed by an exception, has the potential to reuse threads in a pool, and has other potential advantages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:49:20.720", "Id": "210502", "ParentId": "210444", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T18:56:42.283", "Id": "210444", "Score": "1", "Tags": [ "java", "file", "io", "stream" ], "Title": "Reading new data from a constantly updating file in Java" }
210444
<p>Given a matrix, clockwise rotate elements in it. Examples:</p> <pre><code>Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12 </code></pre> <p>Scala Implementation is below. I do feel that I do not need to have a rotatedMatrix predefined (which I am filling with -1) and I can build it up during my recursive calls, but I am not able to do it. Thanks in advance for helping me on this.</p> <pre><code>import scala.util.Random object MatrixRotate extends App { def getCol(c: Int, m: Array[Array[Int]]): Seq[Int] = (0 to (m(0).length - 1)) map ( r =&gt; m(r)(c)) def getRow(r: Int, m: Array[Array[Int]]): Seq[Int] = m(r).toSeq def innerMatrix(m: Array[Array[Int]]): Array[Array[Int]] = { if (m.length == 0) Array.empty else { val rows = m.length - 1 val cols = m(0).length - 1 (1 until rows).map { r =&gt; (1 until cols).map { c =&gt; m(r)(c) }.toArray }.toArray } } val rotatedMatrix = Array.fill(6)(Array.fill(6)(-1)) def rotateByOne(m: Array[Array[Int]], startRow: Int, startCol: Int, endRow: Int, endCol: Int): Unit = { m.size match { case 0 =&gt; case _ =&gt; getRow(0, m) match { case Nil =&gt; case x =&gt; x.init.zipWithIndex foreach { case (e, index) =&gt; rotatedMatrix(startRow)(startCol+index+1) = e } } getCol(m(0).length - 1, m) match { case Nil =&gt; case x =&gt; x.init.zipWithIndex foreach { case (e, index) =&gt; rotatedMatrix(startRow+index+1)(endCol) = e } } getRow(m.length - 1, m) match { case x :: Nil =&gt; case x =&gt; x.tail.zipWithIndex foreach { case (e, index) =&gt; rotatedMatrix(endRow)(startCol+index) = e } } getCol(0, m) match { case x :: Nil =&gt; case x =&gt; x.tail.zipWithIndex foreach { case (e, index) =&gt; rotatedMatrix(startRow+index)(startCol) = e } } rotateByOne(innerMatrix(m), startRow + 1, startCol + 1, endRow - 1, endCol - 1) } } val matrix = Array.fill(6)(Array.fill(6)(Random.nextInt(100))) matrix foreach(row =&gt; println(row.mkString(","))) println("----------") rotateByOne(matrix, 0, 0, 5, 5) rotatedMatrix foreach (row =&gt; println(row.mkString(","))) } </code></pre> <p><strong>Update</strong></p> <p>I realize that this code seems to be failing for rectangular matrix. I still need to solve it for that case.</p>
[]
[ { "body": "<p><strong>Functional programming</strong></p>\n\n<p>Since you've tagged this post with <code>functional-programming</code> I guess that the goal of this exercise may have been to practice functional programming or to present you skills in functional programming. This way or another, I'll stick to the assumption that it was supposed to be written in the functional programming paradigm.</p>\n\n<p>When working with functional code, a function returning a <code>Unit</code> is a huge warning sign. In functional programming we compose programs of functions which are (<a href=\"https://twitter.com/jdegoes/status/936301872066977792\" rel=\"nofollow noreferrer\">quoting John De Goes</a>):</p>\n\n<blockquote>\n <ol>\n <li>Total: They return an output for every input. </li>\n <li>Deterministic: They return the same output for the same input. </li>\n <li>Pure: Their only effect is computing the output.</li>\n </ol>\n</blockquote>\n\n<p>In FP, if a function returns a Unit, it basically means that the function does nothing, as the only thing a function can do is to return a result.</p>\n\n<p><strong>rotatedMatrix</strong></p>\n\n<p>In FP preallocating the <code>rotatedMatrix</code> doesn't make sens, because in order to stay Pure <code>rotateByOne</code> is disallowed to mutate the <code>rotatedMatrix</code>. And the solution is simple, the <code>rotateByOne</code> should allocate and <strong>return</strong> a rotated matrix.</p>\n\n<p><strong>rotateByOne</strong></p>\n\n<p>While moving the allocation of <code>rotatedMatrix</code> into the <code>rotateByOne</code> would make <code>rotateByOne</code> a pure function, the implementation of the function would still be clattered with state mutations, and generally much more complex than it needs to be.</p>\n\n<p>So let's have a look at how it can be improved. </p>\n\n<p>Edge-case/error handling aside, I would expect the problem to be solved with a <code>def rotateByOne(in: Array[Array[Int]]): Array[Array[Int]]</code>. That function would have to create a new matrix of the same dimensions, finding a new value of each cell in the matrix. It's implementation could look like</p>\n\n<pre><code> def rotateByOne(in: Array[Array[Int]]): Array[Array[Int]] = {\n val size = in.length\n (0 until size).map { i =&gt;\n (0 until size).map { j =&gt;\n newValueAt(in, i, j)\n }.toArray\n }.toArray\n }\n</code></pre>\n\n<p>Now all that's left is to implement the <code>def newValueAt(in: Array[Array[Int]], i: Int, j: Int): Int</code> which is again - <em>a pure function</em> - doing nothing but returning an <code>Int</code>. There are 5 cases to be considered, in <code>newValueAt</code>. Using the value of the cell:\nbelow, above, on the right, on the left, and the same cell. </p>\n\n<p>For 3 x 3 matrix it's:</p>\n\n<pre><code>b l l\nb s a\nr r a\n</code></pre>\n\n<p>For 4 x 4 matrix it's:</p>\n\n<pre><code>b l l l\nb b l a\nb r a a\nr r r a\n</code></pre>\n\n<p>After a few minutes of trial and error, I've ended up with the following implementation:</p>\n\n<pre><code> def newValueAt(in: Array[Array[Int]], i: Int, j: Int): Int = {\n val s = in.size - 1\n if (i &gt;= j &amp;&amp; s - i &gt; j) in(i + 1)(j) // 'b'\n else if (i &lt; j &amp;&amp; s - i &gt;= j) in(i)(j - 1) // 'l'\n else if (i &lt;= j &amp;&amp; s - i &lt; j) in(i - 1)(j) // 'a'\n else if (i &gt; j &amp;&amp; s - i &lt;= j) in(i)(j + 1) // 'r'\n else in(i)(j) // 's'\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T20:03:29.787", "Id": "406942", "Score": "0", "body": "Thanks for explaining it so well.\n\nrotateByOne not returning new matrix was troubling me as well (as I observed in my question), but I was not for the right reasons. Your guidelines will help me in thinking it right way.\n\nI do think that identifying new value for each position is a difficult approach for this problem and the current solution handles it in a different way (with recursion). Approach is inspired by this answer https://codereview.stackexchange.com/a/210390/37522 ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:59:35.523", "Id": "210490", "ParentId": "210450", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:19:38.607", "Id": "210450", "Score": "0", "Tags": [ "interview-questions", "functional-programming", "matrix", "scala" ], "Title": "Clockwise rotate a matrix in Scala" }
210450
<p>I have created a quiz function in my rails application. Since I want to track responses and make it a server-side application I created a table to record the responses of the questions people answer.</p> <pre><code>create_table "responses", force: :cascade do |t| t.bigint "question_id" t.bigint "answer_id" t.bigint "user_id" t.uuid "uuid", default: -&gt; { "uuid_generate_v4()" } t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["answer_id"], name: "index_responses_on_answer_id" t.index ["question_id"], name: "index_responses_on_question_id" t.index ["user_id"], name: "index_responses_on_user_id" end </code></pre> <p>Each question can have 4 possible answers association with them. I want to create and check the response directly after the user clicks on it. To do this I created this bit of logic here.</p> <pre><code>&lt;h1&gt;&lt;%= @question.prompt %&gt;&lt;/h1&gt; &lt;% @question.answers.each do |a| %&gt; &lt;%= form_for @response, url: send_wager_response_path, remote: true do |f| %&gt; &lt;%= f.hidden_field :user_id, value: current_user.id %&gt; &lt;%= f.hidden_field :question_id, value: @question.id %&gt; &lt;%= f.hidden_field :answer_id, value: a.id %&gt; &lt;%= f.submit "#{a.answer.titleize}", class: 'btn btn-block btn-lg btn-primary' %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>The problem I have with this is that I am creating 4 different forms on the question page and passing the current user id, the answer id they select, and the question id. This seems a bit not-so DRY. Is there a way to improve on this concept? </p> <p>I am currently looking into a action-cable based approach since this is a head-to-head application but this is a good place to start. </p>
[]
[ { "body": "<p>Why do you submit the current user id in the form? I assume the user is logged in by the statement <code>current_user.id</code> in the form. If you're placing the current user id into the form, you allow the user to change the value (assuming you use the submitted user id in your handler). I know the field is hidden, but everything that an client submits can be manipulated. The only thing to do is open up the developer tools and alter the HTML source. Instead of submitting the id through the form I recommend simply using <code>current_user</code> in the handler and don't submit the user id at all.</p>\n\n<p>You mention you're looking into Action Cable at the moment. However Action Cable is based on the web-socket technology. This could be used, but the main reason they where invented is to keep the connection between the server and client open so the server can send data to the client without the client making a request first. This is mostly done when something changed on the server that has impact on the current view of the client. The term for this would be push notifications or messages.</p>\n\n<p>Since the view doesn't have to change when something changed on the server there is no need to make things more complicated. Instead you want to update the responses when user selects an answer (user initiated). The solution is to update the user response on change (using JavaScript). Rails has a build in system that does this documented in the <a href=\"https://guides.rubyonrails.org/working_with_javascript_in_rails.html#customize-remote-elements\" rel=\"nofollow noreferrer\">Ruby on Rails Guides - Working with JavaScript in Rails: 3.2 Customize remote elements</a>.</p>\n\n<p>Let me provide you with an (untested) example:</p>\n\n<p>First we ensure that the correct routes are present so we can update the response in a reasonable fashion.</p>\n\n<pre><code># config/routes.rb\n# ...\nresources :questions, only: [] do\n member do\n post 'answer', to: 'responses#answer'\n end\nend\n# ...\n</code></pre>\n\n<p>This should create the route <code>/questions/:id/answer</code> that will be handled in <em>ResponsesController#answer</em>. This route should create a helper named <code>answer_question</code> that accepts an question or question id as its first argument.</p>\n\n<p>The controller might look something like this:</p>\n\n<pre><code># app/controllers/responses_controller.rb\n# ...\ndef answer\n question = Question.find(params[:id])\n answer = question.answers.find(params[:answer_id])\n response = question.responses.find_or_initialize_by(user: current_user)\n\n if response.update(answer: answer)\n head :ok\n else\n render 'answer_error'\n # renders /app/views/responses/answer_error.js.erb\n # Here you can write some JS to update the DOM and sets an error\n # message somewhere.\n end\nend\n# ...\n</code></pre>\n\n<p>And now for the final part of the puzzle we need the view.</p>\n\n<pre><code>&lt;% # I don't know which view this is, but it replaces the one that OP provided. %&gt;\n&lt;h1&gt;&lt;%= @question.prompt %&gt;&lt;/h1&gt;\n&lt;% @question.answers.each do |question| %&gt;\n &lt;%= form_for @response, url: answer_question_path(@question), method: :post, remote: true do |f| %&gt;\n &lt;%= f.hidden_field :answer_id, value: answer.id %&gt;\n &lt;%= f.submit a.answer.titleize, class: 'btn btn-block btn-lg btn-primary' %&gt;\n &lt;% end %&gt;\n&lt;% end %&gt;\n</code></pre>\n\n<p>By having an nested route you eliminate the need to submit the question id. And the user id can be left out for reasons mentioned before.</p>\n\n<p>From the tone in your post I assume you also want to drop those forms. This is possible by using the \"Customize remote elements\" that I linked above. This would leave you with a view that might look something like this.</p>\n\n<pre><code>&lt;h1&gt;&lt;%= @question.prompt %&gt;&lt;/h1&gt;\n&lt;% @question.answers.each do |answer| %&gt;\n &lt;%= radio_button_tag \"question_#{question.id}_answer\", answer.id, false, data: {\n remote: true,\n method: :post,\n url: answer_question_path(@question),\n params: { answer_id: answer.id }\n } %&gt;\n&lt;% end %&gt;\n</code></pre>\n\n<p>The above would simply generate radio buttons (using <a href=\"https://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-radio_button_tag\" rel=\"nofollow noreferrer\"><code>radio_button_tag</code></a>) that are linked to each other (per question). On change a request will be send to the specified URL. This eliminates the need for a form altogether. Keep in mind that no labels are currently present for the radio buttons, you'll have to add them yourself.</p>\n\n<p>Of course you could also use other input HTML input elements to achieve the same result. If you want to stick to the button approach I recommend taking a look at <a href=\"https://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-button_tag\" rel=\"nofollow noreferrer\"><code>button_tag</code></a> in combination with the technique shown above. Or <a href=\"https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to\" rel=\"nofollow noreferrer\"><code>button_to</code></a> which is an helper that generates the wrapping form for you.</p>\n\n<p>As I said, this is an untested example. Might any errors come up let me know in the comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:50:32.727", "Id": "407036", "Score": "0", "body": "`button_tag` was causing issues with params. If you are building a similar function, I recommend using `button_to` so you don't run into issues with data params." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:00:03.850", "Id": "210486", "ParentId": "210452", "Score": "0" } } ]
{ "AcceptedAnswerId": "210486", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T20:36:44.813", "Id": "210452", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Ruby on Rails quiz function" }
210452
<p>I have recently finished a course on Python 3 and I really learned a lot, but every time I write a script, it is messy and I often feel like there must be shorter, more efficient ways to write and structure my scripts.</p> <p>So my question is: How could I rewrite the below script to be shorter and more efficient, and what advice would you guys give me to improve my coding skills in general (maybe a way of thinking about the program that will make it easier to define the structure of what my script should look like...)</p> <p>I am really enthused about the possibilities that coding bring and I would really like to improve, so don't hesitate to be harsh with your comments ;)</p> <p>Here below is one of the scripts I wrote. This one is a hangman game: (The word list for the game are being picked from a .txt file that lives in the same directory as my script)</p> <pre><code>import string import random class Main: def __init__(self): self.place_holder = [] self.wrong_guesses = 10 self.guesses = [] with open('./words.txt', mode='r') as f: self.word = random.choice(f.readlines()) self.word = self.word.strip() print(self.word, end='') return self.place_holders() def place_holders(self): # creates the placeholders for the word for char in self.word: if char != " ": self.place_holder.append(' _ ') elif char == " ": self.place_holder.append(' ') print("".join(self.place_holder)) # prints initial placeholder return self.is_letter() @staticmethod def guess(): # Prompts the user for a guess while True: guessed_letter = input(str('Give a guess: ')).lower() if guessed_letter not in string.ascii_lowercase or len(guessed_letter) &gt; 1: print( 'You have inputted more than one character or the character entered was not recognized.\nPlease try again.') else: break return guessed_letter def is_letter(self): # finds out if the letter belongs to the word, and if so, places it on the right placeholder guessed_letter = self.guess() if guessed_letter in self.word and guessed_letter not in self.guesses: for i in range(len(self.word)): if guessed_letter == self.word[i]: self.place_holder[i] = f' {self.word[i]} ' elif guessed_letter in self.guesses: print('You already said that..\n') else: self.wrong_guesses -= 1 print(f'Sorry, missed.\nYou have {self.wrong_guesses} guesses left.\n') self.guesses.append(guessed_letter) print("".join(self.place_holder)) # prints the updated placeholder return self.is_over() def is_over(self): # Checks if the players has guessed the full word or if the player ran out of guesses if ' _ ' in self.place_holder and self.wrong_guesses &gt; 0: self.is_letter() elif ' _ ' in self.place_holder and self.wrong_guesses == 0: print(f'Sorry, Game Over!\nThe word to guess was: {self.word}') self.play_again() else: self.play_again() @staticmethod def play_again(): # Prompts the player if he wants to play again or not if input('Do you want to play again? (y/n): ').lower().startswith('y'): Main() else: print('Fair enough.. Thanks for playing!') quit() Main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T23:52:38.140", "Id": "406807", "Score": "1", "body": "Why do you print the word immediately after choosing it? That takes all the challenge out of the game." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:41:24.147", "Id": "406810", "Score": "1", "body": "oh yeah sorry about that, that was just for testing purposes, I guess I forgot to take it out lol" } ]
[ { "body": "<p>Your code structure is one of infinite recursion. <code>Main()</code> calls <code>placeholder()</code>, which calls <code>is_letter()</code> which calls <code>is_over()</code> which calls <code>is_letter()</code> (recursive), or <code>play_again()</code> which calls <code>Main()</code> (recursive)! Eventually, you will end up with a Stack Overflow if you play long enough!</p>\n\n<p>What you want is a loop. Two loops, actually. Your program should be structured to operate something like:</p>\n\n<pre><code>play_again = True\nwhile play_again:\n # initialize game state\n while not solved and guesses_left:\n # get guess\n # update game state\n play_again = ask_play_again()\n</code></pre>\n\n<p>No recursive calls are necessary.</p>\n\n<hr>\n\n<p>You read all lines of the file to choose a random puzzle. When you play again, you again read all lines in the file. Perhaps you could read and store all the puzzles, and each time a game is played, you just select one randomly from the list.</p>\n\n<hr>\n\n<p>Your placeholders are complicated, 3 character entities. They could just be single characters, and spaces could be added during printing.</p>\n\n<pre><code>self.placeholder = [ \"_\" if ch != \" \" else \" \" for ch in self.word ]\n</code></pre>\n\n<p>To print:</p>\n\n<pre><code>print(\"\".join(f\" {ch} \" for ch in self.placeholder))\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>print(\"\", \" \".join(self.placeholder))\n</code></pre>\n\n<hr>\n\n<p>You should allow for punctuation in the puzzles. Like spaces, these should be directly shown, not converted to underscores.</p>\n\n<pre><code> _ _ _ _ _ ’ _ _ _ _ _\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:44:02.833", "Id": "406811", "Score": "0", "body": "Thanks! that helps a lot! \nThese are things I didn't even think about, very thoughtful!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:57:51.020", "Id": "406816", "Score": "0", "body": "The list comprehension for `self.placeholder` in this answer is an especially valuable Pythonic technique when you are looking to trim your code. Also, be cautious with `quit()` as this resets the kernel in some IDEs, such as Spyder ([reference here](https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T00:10:06.767", "Id": "210457", "ParentId": "210455", "Score": "7" } }, { "body": "<p>Don't unconditionally call <code>Main()</code> from global scope - if someone else imports your file, you want to leave it up to them what should be executed. This is why you should use the <code>if __name__ == '__main__'</code> pattern that we see so often elsewhere.</p>\n\n<p><code>self.guesses</code> shouldn't be a list. Since you need fast lookup, even though it won't make a noticeable difference, you should be using a set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:19:39.970", "Id": "210460", "ParentId": "210455", "Score": "5" } } ]
{ "AcceptedAnswerId": "210457", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T22:24:40.547", "Id": "210455", "Score": "7", "Tags": [ "python", "python-3.x", "hangman" ], "Title": "Hangman game, written after taking a Python course" }
210455
<p>Given an array of integers, update the index with multiplication of previous and next integers,</p> <pre><code> Input: 2 , 3, 4, 5, 6 Output: 2*3, 2*4, 3*5, 4*6, 5*6 </code></pre> <p>Following is a scala implementation for the same. Kindly review.</p> <pre><code>import scala.util.Random object NeighborMultiplication extends App { val numbers = List.fill(10)(Random.nextInt(10)) println(numbers mkString ",") def multiplication(l: List[Int], carryOver: Int = 1, useCarryOver: Boolean = false ): List[Int] = l match { case Nil =&gt; List() case x::Nil =&gt; List(carryOver * x) case x::y::Nil =&gt; List(carryOver * x * y, y * x) case x::y::z::Nil =&gt; List(carryOver * x * y, x * z, y * z) case x::y::z::tail =&gt; if (useCarryOver) List(carryOver * y, x * z, y * tail.head) ++ multiplication(tail, z, true) else List(x * y, x * z, y * tail.head) ++ multiplication(tail, z, true) } println(multiplication(numbers).mkString(",")) } </code></pre>
[]
[ { "body": "<p>The tricky part of this problem is how to handle the special cases for the start and end of the list, as well as how to handle short lists with fewer than three elements.</p>\n\n<p>The fact that you need to consider up to three elements at a time means that you need a lot of base cases for recursion, though. It's also undesirable to expose the special cases in the form of the <code>carryOver</code> and <code>useCarryOver</code> parameters.</p>\n\n<p>A better approach would be to take advantage of the <a href=\"https://www.scala-lang.org/api/current/scala/collection/immutable/List.html#sliding(size:Int):Iterator[Repr]\" rel=\"noreferrer\"><code>List.sliding</code></a> function. (Note that <code>.sliding</code> may produce a <code>group</code> with just two elements instead of three, if the input <code>lst</code> has length two.)</p>\n\n<pre><code>def multiplication(lst: List[Int]): List[Int] = lst match {\n case _::_::_ =&gt;\n (lst.head :: lst ++ List(lst.last))\n .sliding(3)\n .map(group =&gt; group.head * group.last)\n .toList\n case _ =&gt; lst\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T20:20:04.870", "Id": "406943", "Score": "0", "body": "thanks for your answer, sliding fits here beautifully." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T03:33:53.063", "Id": "210461", "ParentId": "210456", "Score": "5" } }, { "body": "<p>This can be done using tail recursion as well.</p>\n\n<pre><code>def mulSeq(numbers: Seq[Int]): Seq[Long] = {\n @tailrec\n def recurMul(numbersPart: Seq[Int], mul: Int, acc: List[Long]): Seq[Long] = {\n numbersPart match {\n case num1::num2::Nil =&gt;\n (num1*num2) :: ((mul*num2).toLong :: acc)\n case num1::num2::tail =&gt;\n recurMul(num2::tail, num1, (mul*num2)::acc)\n case _ =&gt;\n acc\n }\n }\n\n numbers.headOption match {\n case Some(first) =&gt;\n recurMul(numbers, first, Nil).reverse\n case None =&gt;\n Nil\n }\n}\n</code></pre>\n\n<p>Although the solution above with <code>List.sliding</code> is a little bit shorter, tail recursion is a beloved thing in Scala ^_^.\nAlso, I think in the proposed solution edge cases are more clear. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:50:54.943", "Id": "211294", "ParentId": "210456", "Score": "1" } } ]
{ "AcceptedAnswerId": "210461", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-27T23:18:35.050", "Id": "210456", "Score": "4", "Tags": [ "array", "recursion", "interview-questions", "functional-programming", "scala" ], "Title": "Replace array element with multiplication of neighbors in Scala" }
210456
<p>I wrote this simple command line interface tic tac toe game with unbeatable AI with unittests. Looking for any suggestions how to improve it.</p> <p><strong>Game:</strong></p> <pre><code>#views.py class GameView: @property def intro(self): return '\nTic Tac Toe\n' def newlines(self, amount=1): return '\n' * amount @property def number_of_players(self): return 'Enter number of players (1-2): ' @property def number_of_players_error(self): return '\nPlease enter 1 or 2' def board(self, board): return ''' ╔═══╦═══╦═══╗ ║ {0} ║ {1} ║ {2} ║ ╠═══╬═══╬═══╣ ║ {3} ║ {4} ║ {5} ║ ╠═══╬═══╬═══╣ ║ {6} ║ {7} ║ {8} ║ ╚═══╩═══╩═══╝ '''.format(*board) def win_player(self, player): return 'Player {} won!'.format(player) @property def draw(self): return '\nGame ended in draw.' @property def play_again(self): return '\nPlay again? (Y/n): ' def next_move(self, player, move=''): return 'Player {}: {}'.format(player, move) @property def move_not_valid(self): return 'Not a valid move' # controllers.py from models import Game from views import GameView class GameController: def __init__(self): self.game = Game() self.view = GameView() def run(self): print(self.view.intro) while(True): players = input(self.view.number_of_players) if players == "1": self.play( HumanController(player=1), ComputerController(player=2) ) elif players == "2": self.play( HumanController(player=1), HumanController(player=2) ) else: print(self.view.number_of_players_error) continue break self.play_again() def play_again(self): resp = input(self.view.play_again) if resp != 'n': self.game = Game() print(self.view.newlines()) self.run() def play(self, player1, player2): self.display_board for i in range(9): if i % 2 == 0: player1.move(self.game) else: player2.move(self.game) self.display_board if self.game.is_won(): return self.game_results(player1, player2) def game_results(self, player1, player2): if self.game.winner: if player1.marker == self.game.winner: print(self.view.win_player(player=1)) elif player2.marker == self.game.winner: print(self.view.win_player(player=2)) else: print(self.view.draw) @property def display_board(self): print(self.view.board(self.game.board_positions)) class PlayerController: player = None def __init__(self, player): self.player = player self.view = GameView() if player == 1: self.marker = 'X' self.opponent = 'O' else: self.marker = 'O' self.opponent = 'X' def move(self, game): raise NotImplementedError class HumanController(PlayerController): def move(self, game): while True: move = input(self.view.next_move(self.player)) try: move = int(move) - 1 except: move = -1 if move not in game.available_positions: print(self.view.move_not_valid) else: break game.mark(self.marker, move) class ComputerController(PlayerController): def move(self, game): move, _ = game.maximized(self.marker, self.opponent) game.mark(self.marker, move) print(self.view.next_move(self.player, move + 1)) # models.py class Game: winnable_positions = [ (0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6) ] def __init__(self): self.board = [None for _ in range(9)] self.moves = [] self.winner = None @property def board_positions(self): return [i + 1 if not x else x for i, x in enumerate(self.board)] @property def available_positions(self): return [i for i, v in enumerate(self.board) if not v] def mark(self, marker, pos): self.moves.append(pos) self.board[pos] = marker @property def undo_move(self): self.winner = None self.board[self.moves.pop()] = None def is_won(self): board = self.board if None not in self.board: self.winner = None return True for a, b, c in self.winnable_positions: if board[a] and board[a] == board[b] == board[c]: self.winner = board[a] return True return False def maximized(self, marker, opponent): best_score, best_move = None, None for move in self.available_positions: self.mark(marker, move) if self.is_won(): score = self.score(marker, opponent) else: _, score = self.minimized(marker, opponent) self.undo_move if best_score == None or score &gt; best_score: best_score, best_move = score, move return best_move, best_score def minimized(self, marker, opponent): best_score, best_move = None, None for move in self.available_positions: self.mark(opponent, move) if self.is_won(): score = self.score(marker, opponent) else: _, score = self.maximized(marker, opponent) self.undo_move if best_score == None or score &lt; best_score: best_score, best_move = score, move return best_move, best_score def score(self, marker, opponent): if self.is_won(): if self.winner == marker: return 1 elif self.winner == opponent: return -1 return 0 </code></pre> <p><strong>Unittests:</strong></p> <pre><code># test_views.py import unittest from views import GameView class TestGameView(unittest.TestCase): def setUp(self): self.view = GameView() def test_board(self): board = [1, 'O', 'O', 'X', 5, 'X', 7, 8, 9] self.assertEqual(self.view.board(board), ''' ╔═══╦═══╦═══╗ ║ 1 ║ O ║ O ║ ╠═══╬═══╬═══╣ ║ X ║ 5 ║ X ║ ╠═══╬═══╬═══╣ ║ 7 ║ 8 ║ 9 ║ ╚═══╩═══╩═══╝ ''') def test_new_lines(self): self.assertEqual(self.view.newlines(), '\n') self.assertEqual(self.view.newlines(3), '\n\n\n') def test_win_player(self): self.assertEqual(self.view.win_player(1), 'Player 1 won!') self.assertEqual(self.view.win_player(2), 'Player 2 won!') def test_next_move(self): self.assertEqual(self.view.next_move(1, 1), 'Player 1: 1') self.assertEqual(self.view.next_move(1, 5), 'Player 1: 5') self.assertEqual(self.view.next_move(2, 6), 'Player 2: 6') # test_controllers.py import unittest from unittest.mock import patch from models import Game from controllers import * import io class TestGameControllerPlayAgain(unittest.TestCase): """ GameController.play_again """ @patch('sys.stdout', new_callable=io.StringIO) def assert_stdout(self, expected_output, stdout): game = GameController() try: game.play_again() except StopIteration: pass self.assertIn(expected_output, stdout.getvalue()) @patch('builtins.input', side_effect=['Y']) def test_play_again__yes(self, input): self.assert_stdout('Tic Tac Toe') self.assertTrue(input.called) @patch('builtins.input', side_effect=['n']) def test_play_again__no(self, input): self.assert_stdout('') self.assertTrue(input.called) @patch('builtins.input', side_effect=['']) def test_play_again__default(self, input): self.assert_stdout('Tic Tac Toe') self.assertTrue(input.called) class TestGameControllerPlay(unittest.TestCase): """ GameController.play """ @patch('sys.stdout', new_callable=io.StringIO) def assert_stdout(self, player1, player2, expected_output, stdout): game = GameController() try: game.play(player1, player2) except StopIteration: pass self.assertIn(expected_output, stdout.getvalue()) @patch('builtins.input', side_effect=[1, 4, 2, 5, 3]) def test_play__human(self, input): player1 = HumanController(player=1) player2 = HumanController(player=2) self.assert_stdout(player1, player2, 'Player 1 won!') self.assertTrue(input.called) @patch('builtins.input', side_effect=[5, 6, 7, 2, 9]) def test_play__computer_draw(self, input): player1 = HumanController(player=1) player2 = ComputerController(player=2) self.assert_stdout(player1, player2, 'Game ended in draw') self.assertTrue(input.called) @patch('builtins.input', side_effect=[1, 2, 4]) def test_play__computer_win(self, input): player1 = HumanController(player=1) player2 = ComputerController(player=2) self.assert_stdout(player1, player2, 'Player 2 won!') self.assertTrue(input.called) @patch('sys.stdout', new_callable=io.StringIO) class TestGameControllerGameResults(unittest.TestCase): """ GameController.game_results """ def setUp(self): self.game = Game() self.controller = GameController() self.player1 = HumanController(player=1) self.player2 = HumanController(player=2) def test_draw(self, stdout): self.controller.game_results(self.player1, self.player2) self.assertIn('Game ended in draw', stdout.getvalue()) def test_win_player1(self, stdout): self.controller.game.winner = 'X' self.player1.marker = 'X' self.controller.game_results(self.player1, self.player2) self.assertIn('Player 1 won', stdout.getvalue()) def test_win_player2(self, stdout): self.controller.game.winner = 'O' self.player2.marker = 'O' self.controller.game_results(self.player1, self.player2) self.assertIn('Player 2 won', stdout.getvalue()) class TestPlayerController(unittest.TestCase): """ PlayerController """ def test_player1(self): controller = PlayerController(player=1) self.assertEqual(controller.player, 1) self.assertEqual(controller.marker, 'X') self.assertEqual(controller.opponent, 'O') def test_player2(self): controller = PlayerController(player=2) self.assertEqual(controller.player, 2) self.assertEqual(controller.marker, 'O') self.assertEqual(controller.opponent, 'X') def test_move(self): game = Game() controller = PlayerController(player=1) with self.assertRaises(NotImplementedError): controller.move(game) # test_models.py import unittest from unittest.mock import patch from models import Game import sys class TestGame(unittest.TestCase): def setUp(self): self.game = Game() def test_board_positions(self): self.game.board = [None, 'X', 'O', None] self.assertEqual(self.game.board_positions, [1, 'X', 'O', 4]) self.game.board = ['X', 'O', None, None] self.assertEqual(self.game.board_positions, ['X', 'O', 3, 4]) def test_available_positions(self): self.game.board = [None, 'X', 'O', None] self.assertEqual(self.game.available_positions, [0, 3]) self.game.board = ['X', 'O', None, None] self.assertEqual(self.game.available_positions, [2, 3]) def test_mark(self): game = self.game game.mark('O', 2) self.assertEqual(game.moves, [2]) self.assertEqual(game.board.count('O'), 1) self.assertEqual(game.board.count('X'), 0) self.game.mark('X', 5) self.assertEqual(game.moves, [2, 5]) self.assertEqual(game.board.count('O'), 1) self.assertEqual(game.board.count('X'), 1) def test_undo_move(self): game = self.game game.board = [None, 'O', None, 'X'] game.moves = [1, 3] game.winner = 'O' game.undo_move self.assertIsNone(game.winner) self.assertEqual(game.moves, [1]) self.assertEqual(game.board, [None, 'O', None, None]) game.undo_move self.assertIsNone(game.winner) self.assertEqual(game.moves, []) self.assertEqual(game.board, [None, None, None, None]) def test_is_won__false(self): self.game.board = ['X', 'X', None, 'X', None, None, None, None, None] self.assertFalse(self.game.is_won()) def test_is_won__true(self): self.game.board = ['X', 'X', 'X', None, None, None, None, None, None] self.assertTrue(self.game.is_won()) def test_is_won__full_board(self): self.game.board = ['X'] * 9 self.assertTrue(self.game.is_won()) def test_maximized(self): self.game.board = ['X', 'X', 'X', None, None, None, None, None, None] self.assertEqual(self.game.maximized('X', 'O'), (3, 1)) def test_minimized(self): self.game.board = ['X', 'X', 'X', 'O', 'O', None, None, None, None] self.assertEqual(self.game.minimized('X', 'O'), (5, 1)) def test_score(self): self.game.board = ['X', 'X', 'X', None, None, None, None, None, None] self.assertEqual(self.game.score(marker='X', opponent='O'), 1) self.game.board = ['O', 'O', 'O', None, None, None, None, None, None] self.assertEqual(self.game.score(marker='X', opponent='O'), -1) self.game.board = ['X', 'X', None, None, None, None, None, None, None] self.assertEqual(self.game.score(marker='X', opponent='O'), 0) </code></pre>
[]
[ { "body": "<p>I'm unclear on why <code>GameView</code> has a list of <code>@property</code> functions that are just static strings. This might in theory be useful if you have to support i18n, but I doubt that's the intent here. As such, <code>intro</code>, <code>number_of_players</code>, <code>number_of_players_error</code>, <code>draw</code>, etc. don't need to be properties; that's just clutter.</p>\n\n<p>Another quirk of <code>GameView</code> is that <code>self</code> is never used, so it doesn't deserve to be a class. At most, if you needed to keep those functions but wanted them in a namespace, you would move them into the global scope and use <code>views</code> as the namespace.</p>\n\n<p>To make your board initialization literal easier to read, you can write</p>\n\n<pre><code>board = [1, 'O', 'O', 'X', 5, 'X', 7, 8, 9]\n</code></pre>\n\n<p>as</p>\n\n<pre><code>board = ( 1 ,'O', 'O',\n 'X', 5 , 'X',\n 7 , 8 , 9 )\n</code></pre>\n\n<p>That particular set of data is problematic. You're mixing up \"display\" data (i.e. 'X') with \"logical\" data (i.e. 7). The format of your board should be such that it isn't translated to display characters until it hits the view.</p>\n\n<p>You have tests! Awesome!</p>\n\n<p>Your player number input loop is awkward. I'd suggest rewriting it as:</p>\n\n<pre><code>while True:\n try:\n players = int(input(self.view.number_of_players))\n if not (1 &lt;= players &lt;= 2):\n raise ValueError()\n break\n except ValueError:\n print(self.view.number_of_players_error)\n\nif players == 1:\n type_2 = ComputerController\nelse:\n type_2 = HumanController\nself.play(HumanController(player=1),\n type_2(player=2))\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if resp != 'n':\n</code></pre>\n\n<p>should lower-case <code>resp</code> before the check.</p>\n\n<p>This:</p>\n\n<pre><code>self.display_board\n</code></pre>\n\n<p>is nasty. You're accessing a property, relying on its side-effect to do a <code>print</code>. Properties should be simple value-returning functions. Make that a normal function.</p>\n\n<p>Given this:</p>\n\n<pre><code>class PlayerController:\n player = None\n</code></pre>\n\n<p>I'm unclear on why you declared <code>player</code> at the class level. That can probably go away.</p>\n\n<p>This:</p>\n\n<pre><code>raise NotImplementedError\n</code></pre>\n\n<p>doesn't do what you think it does. You need to add <code>()</code> for that error type to be instantiated.</p>\n\n<p>This:</p>\n\n<pre><code> try:\n move = int(move) - 1\n except:\n move = -1\n</code></pre>\n\n<p>should catch <code>ValueError</code>; the exception clause is too broad.</p>\n\n<p>This:</p>\n\n<pre><code>self.board = [None for _ in range(9)]\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>self.board = [None]*9\n</code></pre>\n\n<p>This</p>\n\n<pre><code>i + 1 if not x else x\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>x or (i + 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:23:21.177", "Id": "407091", "Score": "0", "body": "`raise Exception` works also without the `()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T14:57:39.667", "Id": "407100", "Score": "1", "body": "@Graphier Apparently it works but it's discouraged. Have a read through PEP317 - https://www.python.org/dev/peps/pep-0317 - even though it was rejected, it captures the common sentiment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:14:27.403", "Id": "407104", "Score": "1", "body": "Thanks, interesting read! It seems like I'm in the camp thinking it looks a bit ugly with the empty parentheses, but YMMV. It would be nice if the \"correct\" way was mentioned in PEP8..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:31:01.477", "Id": "210504", "ParentId": "210466", "Score": "3" } } ]
{ "AcceptedAnswerId": "210504", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T07:10:08.913", "Id": "210466", "Score": "4", "Tags": [ "python", "python-3.x", "unit-testing", "tic-tac-toe", "ai" ], "Title": "Tic tac toe with unbeatable AI" }
210466
<p>I have managed to achieve this action through this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function togglePasswordVisibility($pw, on, id) { $pw.attr('type', on ? 'password' : 'text'); $('[data-id=' + id + '] &gt; i').toggleClass('fa-eye-slash fa-eye'); } // $("#pass-on").after('&lt;div class="input-group-append"&gt;&lt;span class="password-button password-button-main"&gt;&lt;i class="fas fa-eye-slash"&gt;&lt;/i&gt;&lt;/span&gt;&lt;/div&gt;'); $('[data-id]').on('click', function() { var id = $(this).data('id'), $pw = $('#' + id); togglePasswordVisibility($pw, false, id); setTimeout(function() { togglePasswordVisibility($pw, true, id); }, 800); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" rel="stylesheet"/&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="input-group"&gt; &lt;input type="password" id="pass-on" title="&lt;?php echo $user-&gt;valid_password_error; ?&gt;" class="form-control" name="txt_upass" placeholder="Enter Password" autocomplete="off" value="" oninvalid="setCustomValidity('&lt;?php echo $user-&gt;password_error; ?&gt;')" oninput="setCustomValidity('')" required /&gt; &lt;label&gt;Password&lt;/label&gt; &lt;div class="input-group-append"&gt; &lt;span class="password-button password-button-main" data-id="pass-on"&gt;&lt;i class="fas fa-eye-slash"&gt;&lt;/i&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group progress jquery-result-1" style="height: 10px;"&gt; &lt;div class="form-group input-group"&gt; &lt;input type="password" id="pass-verify-on" title="&lt;?php echo $user-&gt;valid_password_error; ?&gt;" class="form-control" name="txt_upass_ok" placeholder="Retype Password" autocomplete="off" value="" oninvalid="setCustomValidity('&lt;?php echo $user-&gt;password_error; ?&gt;')" oninput="setCustomValidity('')" required /&gt; &lt;label&gt;Retype Password&lt;/label&gt; &lt;div class="input-group-append"&gt; &lt;span class="password-button password-button-verify" data-id="pass-verify-on"&gt;&lt;i class="fas fa-eye-slash"&gt;&lt;/i&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>But I would like to place the password button from within the function using the commented line with the <code>after</code> callback and making it apply the same effect. Right now the button correlates with the input through the association of data-id and id. If I would to place it inside the function I would have to get rid of the data-id and still make it act individually on each input, I just can't figure how. Thank you for your time.</p>
[]
[ { "body": "<p>You can first create the <code>i</code> element and add a click event handler to it dynamically while you wrap it inside the <code>div</code> and <code>span</code> and add it to the document.</p>\n\n<p>As you use jQuery, I would suggest using it for creating each individual element, providing it with attributes using jQuery methods. </p>\n\n<p>Here is how you could do it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function togglePasswordVisibility($pw, on, $eye) {\n $pw.attr('type', on ? 'password' : 'text');\n $eye.toggleClass('fa-eye-slash fa-eye');\n}\n\n$(\"[type=password]\").each(function () {\n var $pw = $(this);\n var $eye = $(\"&lt;i&gt;\").addClass(\"fas fa-eye-slash\").click(function () {\n togglePasswordVisibility($pw, false, $eye);\n setTimeout(function() {\n togglePasswordVisibility($pw, true, $eye);\n }, 800);\n });\n $pw.parent().append(\n $(\"&lt;div&gt;\").addClass(\"input-group-append\").append(\n $(\"&lt;span&gt;\").addClass(\"password-button password-button-main\").append($eye)\n )\n );\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" rel=\"stylesheet\"/&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n\n&lt;link href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" rel=\"stylesheet\"/&gt;\n\n&lt;div class=\"input-group\"&gt;\n &lt;input type=\"password\" id=\"pass-on\" title=\"&lt;?php echo $user-&gt;valid_password_error; ?&gt;\" class=\"form-control\" name=\"txt_upass\" placeholder=\"Enter Password\" autocomplete=\"off\" value=\"\" oninvalid=\"setCustomValidity('&lt;?php echo $user-&gt;password_error; ?&gt;')\" oninput=\"setCustomValidity('')\" required /&gt;\n &lt;label for=\"pass-on\"&gt;Password&lt;/label&gt;\n&lt;/div&gt;\n \n&lt;div class=\"form-group input-group\"&gt;\n &lt;input type=\"password\" id=\"pass-verify-on\" title=\"&lt;?php echo $user-&gt;valid_password_error; ?&gt;\" class=\"form-control\" name=\"txt_upass_ok\" placeholder=\"Retype Password\" autocomplete=\"off\" value=\"\" oninvalid=\"setCustomValidity('&lt;?php echo $user-&gt;password_error; ?&gt;')\" oninput=\"setCustomValidity('')\" required /&gt;\n &lt;label for=\"pass-verify-on\"&gt;Retype Password&lt;/label&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:55:47.747", "Id": "406936", "Score": "0", "body": "You are freaking genius. Thanks a lot, you are awesome! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T19:04:47.527", "Id": "406937", "Score": "1", "body": "You're welcome ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:48:48.307", "Id": "210501", "ParentId": "210467", "Score": "1" } } ]
{ "AcceptedAnswerId": "210501", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T07:11:45.263", "Id": "210467", "Score": "0", "Tags": [ "javascript" ], "Title": "Place a button after an input and show it's password in plain text" }
210467
<p>In an effort to stretch my programming muscles, I'm doing the <a href="https://adventofcode.com/2018" rel="nofollow noreferrer">Advent of Code 2018</a> in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!</p> <p>The full challenge is <a href="https://adventofcode.com/2018/day/3" rel="nofollow noreferrer">here</a> and a bit involved, I'll try to keep it a bit shorter here.</p> <blockquote> <p><strong>The challenge</strong></p> <p>The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.</p> <p>Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:</p> <ul> <li>The number of inches between the left edge of the fabric and the left edge of the rectangle.</li> <li>The number of inches between the top edge of the fabric and the top edge of the rectangle.</li> <li>The width of the rectangle in inches.</li> <li>The height of the rectangle in inches.</li> </ul> <p>A claim like <code>#123 @ 3,2: 5x4</code> means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:</p> <pre><code>- #1 @ 1,3: 4x4 - #2 @ 3,1: 4x4 - #3 @ 5,5: 2x2 </code></pre> <p>Visually, these claim the following areas:</p> <pre><code>........ ...2222. ...2222. .11XX22. .11XX22. .111133. .111133. ........ </code></pre> <p>The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. <strong>How many square inches of fabric are within two or more claims?</strong></p> </blockquote> <p>This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.</p> <p><strong>Day3.py</strong></p> <pre><code>class Claim(object): id = None x = None y = None width = None height = None def __init__(self, claim_id, x, y, width, height): self.id = claim_id self.x = x self.y = y self.width = width self.height = height def __repr__(self): return "&lt;Claim #%s - %s, %s - %sx%s&gt;" % (self.id, self.x, self.y, self.width, self.height) def read_file_lines(file_path, strip_lines=True): """ Reads the specified file and returns it's lines an array file_path: the path to the file strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line Returns: An array of the lines in the file as string """ with open(file_path, "r") as f: if strip_lines: return [l.strip() for l in f.readlines()] return [l for l in f.readlines()] def parse_input(lines): claims = [] for line in lines: parts = line.split(" ") id = int(parts[0][1:]) x = int(parts[2].split(",")[0]) y = int(parts[2].split(",")[1][:-1]) width = int(parts[3].split("x")[0]) height = int(parts[3].split("x")[1]) claims.append(Claim(id, x, y, width, height)) return claims def generate_matrix(size): return [[0]*size for _ in range(size)] def print_matrix(matrix): line = "" for y in range(0, len(matrix[0])): line = line + str(y) + ": " for x in range(0, len(matrix[0])): line = line + str(matrix[x][y]) print(line) line = "" if __name__ == '__main__': content = read_file_lines("input.txt") claims = parse_input(content) matrix = generate_matrix(1000) print_matrix(matrix) for claim in claims: x_indexes = range(claim.x, claim.x + claim.width) y_indexes = range(claim.y, claim.y + claim.height) for x in x_indexes: for y in y_indexes: matrix[x][y] = matrix[x][y] + 1 print_matrix(matrix) inches_double_claimed = 0 for x in range(0, len(matrix[0])): for y in range(0, len(matrix[0])): if matrix[x][y] &gt;= 2: inches_double_claimed += 1 print("Inches claimed by two or more claims:", inches_double_claimed) </code></pre>
[]
[ { "body": "<p>This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def __repr__(self):\n return \"&lt;Claim #%s - %s, %s - %sx%s&gt;\" % (self.id, self.x, self.y, self.width, self.height)\n</code></pre>\n</blockquote>\n\n<p>This should be <code>__str__</code>, as it is meant for \"fancy\" formatting like this. Ideally, <code>__repr__</code> should be build such as <code>eval(repr(x))</code> will reconstruct <code>x</code>.</p>\n\n<blockquote>\n<pre><code>class Claim(object):\n id = None\n x = None\n y = None\n width = None\n height = None\n\n def __init__(self, claim_id, x, y, width, height):\n self.id = claim_id\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def __repr__(self):\n return \"&lt;Claim #%s - %s, %s - %sx%s&gt;\" % (self.id, self.x, self.y, self.width, self.height)\n</code></pre>\n</blockquote>\n\n<p>This whole class could be replaced by a <code>namedtuple</code>. Considering the previous remark, I’d write:</p>\n\n<pre><code>from collections import namedtuple\n\n\nclass Claim(namedtuple('Claim', 'id x y width height')):\n def __str__(self):\n return \"&lt;Claim #{} - {}, {} - {}x{}&gt;\".format(self.id, self.x, self.y, self.width, self.height)\n</code></pre>\n\n<p>Note that I replaced old-school <code>%</code> formating with the prefered <code>str.format</code> method. Note that there is also f-strings available if you are using Python 3.6+.</p>\n\n<p>Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def read_file_lines(file_path, strip_lines=True):\n \"\"\" Reads the specified file and returns it's lines an array\n file_path: the path to the file\n strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line\n\n Returns: An array of the lines in the file as string\n \"\"\"\n with open(file_path, \"r\") as f:\n if strip_lines:\n return [l.strip() for l in f.readlines()]\n\n return [l for l in f.readlines()]\n</code></pre>\n</blockquote>\n\n<p>You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:</p>\n\n<pre><code>def read_file_lines(file_path, strip_lines=True):\n \"\"\" Reads the specified file and returns it's lines\n file_path: the path to the file\n strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line\n\n Generates the lines in the file as string\n \"\"\"\n with open(file_path, \"r\") as f:\n for line in f:\n if strip_lines:\n yield line.strip()\n else:\n yield line\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def parse_input(lines):\n claims = []\n for line in lines:\n parts = line.split(\" \")\n\n id = int(parts[0][1:])\n x = int(parts[2].split(\",\")[0])\n y = int(parts[2].split(\",\")[1][:-1])\n width = int(parts[3].split(\"x\")[0])\n height = int(parts[3].split(\"x\")[1])\n\n claims.append(Claim(id, x, y, width, height))\n\n return claims\n</code></pre>\n</blockquote>\n\n<p>You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:</p>\n\n<pre><code>def parse_input(lines):\n return [Claim.from_input(line) for line in lines]\n</code></pre>\n\n<p>and rework the <code>Claim</code> class into:</p>\n\n<pre><code>class Claim(namedtuple('Claim', 'id x y width height')):\n def __str__(self):\n return \"&lt;Claim #{} - {}, {} - {}x{}&gt;\".format(self.id, self.x, self.y, self.width, self.height)\n\n @classmethod\n def from_input(cls, line):\n parts = line.split(\" \")\n\n id = int(parts[0][1:])\n x = int(parts[2].split(\",\")[0])\n y = int(parts[2].split(\",\")[1][:-1])\n width = int(parts[3].split(\"x\")[0])\n height = int(parts[3].split(\"x\")[1])\n\n return cls(id, x, y, width, height)\n</code></pre>\n\n<p>In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:</p>\n\n<pre><code>def parse_input(filename):\n with open(filename) as f:\n return [Claim.from_input(line.strip()) for line in f]\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def generate_matrix(size):\n return [[0]*size for _ in range(size)]\n</code></pre>\n</blockquote>\n\n<p>Nothing to say here, you didn't fall in the trap of writting <code>[[0] * size] * size</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def print_matrix(matrix):\n line = \"\"\n for y in range(0, len(matrix[0])):\n line = line + str(y) + \": \"\n for x in range(0, len(matrix[0])):\n line = line + str(matrix[x][y])\n print(line)\n line = \"\"\n</code></pre>\n</blockquote>\n\n<p>Time to learn to use <code>str.join</code>:</p>\n\n<pre><code>def print_matrix(matrix):\n string = '\\n'.join(\n 'line {}: {}'.format(i, ''.join(map(str, line)))\n for i, line in enumerate(matrix))\n print(string)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>if __name__ == '__main__':\n content = read_file_lines(\"input.txt\")\n claims = parse_input(content)\n\n matrix = generate_matrix(1000)\n print_matrix(matrix)\n\n for claim in claims:\n x_indexes = range(claim.x, claim.x + claim.width)\n y_indexes = range(claim.y, claim.y + claim.height)\n\n for x in x_indexes:\n for y in y_indexes:\n matrix[x][y] = matrix[x][y] + 1\n\n print_matrix(matrix)\n\n inches_double_claimed = 0\n for x in range(0, len(matrix[0])):\n for y in range(0, len(matrix[0])):\n if matrix[x][y] &gt;= 2:\n inches_double_claimed += 1\n\n print(\"Inches claimed by two or more claims:\", inches_double_claimed)\n</code></pre>\n</blockquote>\n\n<p>As you made in the <code>print_matrix</code> function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:</p>\n\n<pre><code>for line in matrix:\n for claims in line:\n if claims &gt; 1:\n inches_double_claimed += 1\n</code></pre>\n\n<p>And, in fact, these loops could be written in a single generator expression fed to <code>sum</code>:</p>\n\n<pre><code>inches_double_claimed = sum(claims &gt; 1 for line in matrix for claims in line)\n</code></pre>\n\n<p>I would also advice you to wrap this code in a <code>main</code> function parametrized by the file name to read.</p>\n\n<hr>\n\n<p>There is still room for improvement: maybe defining a <code>Matrix</code> class to abstract your functions manipulating it, using <code>re</code> to simplify input parsing, using a <code>defaultdict(defaultdict(int))</code> to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T08:01:13.510", "Id": "407183", "Score": "0", "body": "Thanks so much! Very comprehensable and a lot of things to absorb!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:42:43.883", "Id": "210474", "ParentId": "210470", "Score": "4" } }, { "body": "<p>I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to <code>Claim</code> objects is wasting resources and you should focus on your intermediate <code>matrix</code> representation instead. Or maybe as intermediate representation for documentation purposes, but you don't need to store them all at once in memory.</p>\n\n<p>As such, I would only use the <code>re</code> module to parse a line and immediately store it into the matrix.</p>\n\n<p>Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the <code>collections</code> module features two helpful classes: <code>defaultdict</code> and <code>Counter</code>.</p>\n\n<p>Lastly, the <code>fileinput</code> module make it easy to use a/several file names on the command line or standard input.</p>\n\n<p>My take on this would be:</p>\n\n<pre><code>import re\nimport fileinput\nfrom collections import namedtuple, defaultdict, Counter\n\n\nINPUT_PATTERN = re.compile(r'#\\d+ @ (\\d+),(\\d+): (\\d+)x(\\d+)')\n\n\nclass Claim(namedtuple('Claim', ['x', 'y', 'width', 'height'])):\n @property\n def horizontal(self):\n return range(self.x, self.x + self.width)\n\n @property\n def vertical(self):\n return range(self.y, self.y + self.height)\n\n\ndef parse_input(stream):\n for line in stream:\n match = INPUT_PATTERN.match(line)\n if match:\n yield Claim(*map(int, match.groups()))\n\n\ndef claim_fabric(claims):\n fabric = defaultdict(Counter)\n for claim in claims:\n for line in claim.horizontal:\n fabric[line].update(claim.vertical)\n return fabric\n\n\ndef count_overlaping_claims(fabric):\n return sum(\n claims &gt; 1\n for line in fabric.values()\n for claims in line.values())\n\n\nif __name__ == '__main__':\n fabric = claim_fabric(parse_input(fileinput.input()))\n print(count_overlaping_claims(fabric))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T08:00:13.383", "Id": "407182", "Score": "0", "body": "Thanks! I'm used to C# so Objects are my knee-jerk reaction to anything. I see a lot of cool new stuff in here for me to research. I'll approve the other answer because of the completeness, but at the very least: Have an upvote!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:35:06.960", "Id": "210479", "ParentId": "210470", "Score": "2" } }, { "body": "<p>Another python feature crying to be used is scatter/gather assignments. You can replace:</p>\n\n<pre><code> parts = line.split(\" \")\n\n id = int(parts[0][1:])\n x = int(parts[2].split(\",\")[0])\n y = int(parts[2].split(\",\")[1][:-1])\n width = int(parts[3].split(\"x\")[0])\n height = int(parts[3].split(\"x\")[1])\n</code></pre>\n\n<p>with the at least slightly more readable:</p>\n\n<pre><code> line = line[1:].replace(':','') # nuke extra punctuation\n id, _, xy, size = line.split(\" \")\n id = int(id)\n x, y = [int(i) for i in xy.split(',')]\n width, height = [int(i) for i in size.split('x')]\n</code></pre>\n\n<p>The first and second lines can of course be combined if you're going for more brevity, but I thought breaking the cleanup away from the breakup clarified it a little.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T05:13:08.233", "Id": "210855", "ParentId": "210470", "Score": "0" } } ]
{ "AcceptedAnswerId": "210474", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T08:35:58.027", "Id": "210470", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Python solution to Advent of Code, day 3" }
210470
<p>I have a simple quiz game where user can give simple answers to simple questions and program will give a result. Please, guys, make a code review and if it is possible answer to my questions placed at the bottom.</p> <p><strong>Model classes looks like that:</strong></p> <pre><code>public class Answer { public Answer(int id, int questionId, string content) { Id = id; Content = content; QuestionId = questionId; } public int Id { get; private set; } public int QuestionId { get; private set; } public string Content { get; private set; } } public class Question { public Question(int id, string content, char answer) { Id = id; Content = content; Answer = answer; } public int Id { get; private set; } public string Content { get; private set; } public char Answer { get; private set; } } </code></pre> <p><strong>Abstractions:</strong></p> <pre><code>interface IAnswerService { List&lt;IList&lt;Answer&gt;&gt; GetAnswers(); } interface IQuestionService { IList&lt;Question&gt; GetQuestions(); } public interface ICalculationService { int CalculatePoints(Dictionary&lt;Question, char&gt; userAnswers); } </code></pre> <p><strong>Constants:</strong></p> <pre><code>public static class Constants { public static class Answers { public const char A = 'a'; public const char B = 'b'; public const char C = 'c'; public const char D = 'd'; } } </code></pre> <p><strong>Core services:</strong></p> <pre><code>static class Factory { public static T CreateInstance&lt;T&gt;() where T : new() { return new T(); } } </code></pre> <p><strong>Services:</strong></p> <pre><code>public class AnswerService : IAnswerService { public List&lt;IList&lt;Answer&gt;&gt; GetAnswers() { return new List&lt;IList&lt;Answer&gt;&gt;() { new List&lt;Answer&gt;() { new Answer(11, 3, "Sequoia"), new Answer(12, 3, "Berch"), new Answer(13, 3, "Lindens"), new Answer(14, 3, "Alder") }, new List&lt;Answer&gt;() { new Answer(1, 1, "1"), new Answer(2, 1, "2"), new Answer(3, 1, "5"), new Answer(4, 1, "6") }, new List&lt;Answer&gt;() { new Answer(7, 2, "More than 1"), new Answer( 8, 2, "More than 2"), new Answer(9, 2, "More than 5"), new Answer(10, 2, "More than 6") }, new List&lt;Answer&gt;() { new Answer(15, 4, "yes, I do!"), new Answer(16, 4, "Sure!"), new Answer(17, 4, "Exactly"), new Answer(18, 4, "Yeap!") } }; } } </code></pre> <p><code>CalculationAnswerByAdding</code> class of Services:</p> <pre><code>class CalculationAnswerByAdding : ICalculationService { public int CalculatePoints(Dictionary&lt;Question, char&gt; userAnswers) { var sum = 0; foreach (var question in userAnswers) { if (question.Key.Answer == question.Value) sum += 1; } return sum; } } </code></pre> <p><code>CalculationAnswerBySubtracting</code> of Services:</p> <pre><code>class CalculationAnswerBySubtracting : ICalculationService { public int CalculatePoints(Dictionary&lt;Question, char&gt; userAnswers) { var sum = 10; foreach (var question in userAnswers) { if (question.Key.Answer == question.Value) sum -= 1; } return sum; } } public class QuestionService : IQuestionService { public IList&lt;Question&gt; GetQuestions() { return new List&lt;Question&gt;() { new Question(1, "How many are there contintents?", Constants.Constants.Answers.A), new Question(2, "How many are there colours?", Constants.Constants.Answers.B), new Question(3, "What is the tallest tree?", Constants.Constants.Answers.C), new Question(4, "Do you like dolphins?", Constants.Constants.Answers.D), }; } } </code></pre> <p><strong>And Program.cs:</strong></p> <p><code>Main()</code> method of <code>Program.cs</code>:</p> <pre><code>static void Main(string[] args) { IQuestionService questionService = Factory.CreateInstance&lt;QuestionService&gt;(); var questions = questionService.GetQuestions(); IAnswerService answerService = Factory.CreateInstance&lt;AnswerService&gt;(); var answers = answerService.GetAnswers(); var questionAnswers = questions.ToDictionary(q =&gt; q, q =&gt; answers .SelectMany(a =&gt; a) .Where(b =&gt; b.QuestionId == q.Id) .ToList()); var userAnswers = new Dictionary&lt;Question, char&gt;(); GetAsnwers(questionAnswers, userAnswers); ICalculationService calculationService = Factory .CreateInstance&lt;CalculationAnswerByAdding&gt;(); var userSum = calculationService.CalculatePoints(userAnswers); Console.WriteLine(userSum &gt; 3 ? $"Yeah, it is great. Your points are {userSum}." : $"Hey, it is great. Your points are {userSum}"); } </code></pre> <p><code>GetAsnwers()</code> method of <code>Program.cs</code>:</p> <pre><code> private static void GetAsnwers(Dictionary&lt;Question, List&lt;Answer&gt;&gt; questionAnswers, Dictionary&lt;Question, char&gt; userAnswers ) { foreach (var questionAnsw in questionAnswers) { AskQuestion(questionAnsw); List&lt;char&gt; allowedAnswers = new List&lt;char&gt;() { Constants.Constants.Answers.A, Constants.Constants.Answers.B, Constants.Constants.Answers.C, Constants.Constants.Answers.D, }; while (true) { var userKey = Console.ReadKey().KeyChar; Console.WriteLine(); if (!allowedAnswers.Contains(userKey)) { AskQuestion(questionAnsw, true); } else { userAnswers.Add(questionAnsw.Key, userKey); break; } } } } </code></pre> <p><code>AskQuestion()</code> method of <code>Program.cs</code>:</p> <pre><code>private static void AskQuestion(KeyValuePair&lt;Question, List&lt;Answer&gt;&gt; questionAnswer, bool showPossibleKeys = false) { if (showPossibleKeys) { Console.WriteLine(); Console.WriteLine("Possible keys are A, B, C or D"); } Console.WriteLine(questionAnswer.Key.Content); questionAnswer.Value .ForEach(a =&gt; Console.WriteLine(a.Content)); } </code></pre> <p>Guys, please, see my code. Is my code solid? Do I correctly use strategy and factory patterns? Any improvements and comments are greatly appreciated.</p> <p>In addition, do my classes organized well? Especially, is it okay that I moved <code>Factory</code> into folder <code>CoreServices</code>? Or is there a better way to organize classes? <a href="https://i.stack.imgur.com/HfLVR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HfLVR.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>Instead of asking <em>'did I use pattern X correctly?'</em>, I would ask <em>'does pattern X provide a good solution to my problem?'</em>. And to answer that question, you need to consider the requirements of your program. <em>Why</em> do you think this program needs strategies, services and factories?</p>\n\n<h3>Model classes</h3>\n\n<ul>\n<li>Regarding your model classes, why do answers reference questions by their id? Note how this makes things more cumbersome for the caller: <code>Main</code> has to do extra work to match answers to questions.</li>\n<li>Why do questions refer to their correct answer with a char? Not only is that inconsistent with the use of ids, it's also error-prone because it depends on the order in which answers are returned. Such labeling is probably best left to the UI layer, anyway.</li>\n<li>Read-only properties don't need a private setter anymore: <code>{ get; }</code> is sufficient nowadays.</li>\n</ul>\n\n<p>I would go for the following (I've left out constructors for brevity's sake, and ids because they don't seem to be necessary):</p>\n\n<pre><code>public class Question\n{\n public string Content { get; }\n public IReadOnlyCollection&lt;Answer&gt; AvailableAnswers { get; }\n public Answer CorrectAnswer { get; }\n}\n\npublic class Answer\n{\n public string Content { get; }\n}\n</code></pre>\n\n<p>Note that the <code>Answer</code> class now only contains a string, so you could remove it and store a collection of answer strings in <code>Question</code> directly, together with the index of the correct answer.</p>\n\n<h3>Services</h3>\n\n<ul>\n<li>Why split questions and answers into two 'services'? Questions and answers are often, if not always, used together, so this split is making things more difficult than they need to be. It's also more error-prone, because now you need to keep two separate services in sync. I would merge these into a single question repository.</li>\n<li>Both calculation 'service' implementations do the same work, more or less. I'd probably create some kind of <code>Result</code> class, that can be used to keep track of how many questions a user answered correctly and incorrectly. That'll give these calculation algorithms a higher-level overview, and reduces code duplication.</li>\n<li>I'm not really sure whether abstracting the scoring mechanism is really useful, but I don't know what your plans are with this program, so I can't say much about that. That hard-coded <code>10</code> in <code>CalculationAnswerBySubtracting</code> does look problematic though - certainly that should be configurable?</li>\n</ul>\n\n<h3>Factories and constants</h3>\n\n<ul>\n<li>That factory class doesn't add any value over using <code>new</code> directly. If it's intended to simulate a DI container: normally you ask a container for a concrete implementation of an 'abstract' interface, not the other way around.</li>\n<li>Those constants are verbose but don't really clarify anything. <code>Answers.A</code> and <code>'A'</code> are both equally vague ways to reference an answer. Labeling questions like this is a UI detail that shouldn't leak into the rest of the program. Besides, with these constants you pretty much hard-coded a limit of 4 answers per question, which seems like an unnecessary restriction.</li>\n<li><code>AskQuestion</code> doesn't use those constants, and because their values are lower-case, not upper-case, this can result in seemingly valid inputs being rejected (try pressing shift + A instead of just hitting the A key).</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Personally I don't like those <code>Service</code> and <code>Factory</code> suffixes. I would use names like <code>IQuestionRepository</code> and <code>IScoreCalculator</code> - more descriptive, less cluttered.</li>\n<li>In <code>foreach (var question in userAnswers)</code>, <code>question</code> isn't actually a <code>Question</code> but a key-value pair, so that name is a bit misleading. A dictionary is probably not the best way to pass this information around anyway - it doesn't preserve order, and you don't need its lookup functionality, you just need a collection of question-answer pairs.</li>\n<li><code>GetAsnwers</code> 'returns' results by modifying one of its arguments... why doesn't it just return its results, which is how most programmers would expect it to work?</li>\n<li>Using <code>Question</code> as a key in a dictionary, without overriding <code>Equals</code> and <code>GetHashCode</code>, can cause problems. Because right now you're not doing any key lookups with different (but equal) <code>Question</code> instances (no key lookups at all, in fact) the current code works fine, but this could easily cause problems in the future.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T19:16:54.963", "Id": "406939", "Score": "0", "body": "Thanks for so thorough and great answer! I really like your answer. I agree with you. However, I have a question. My intention to use `Id` properties in model classes such as `Answer` and `Question` is to map them accordingly their id's from database. How to create a better classes for mapping them from database?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T20:46:01.487", "Id": "406947", "Score": "0", "body": "Your `Question` and `Answer` classes are used throughout the program, and since nothing there needs those ids I (currently) see no need for those properties. If you're loading them from a database then they'll likely have row ids, yes, but that's an implementation detail that only the question repository needs to know about. How to load or map them... that's a different question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:41:03.723", "Id": "210515", "ParentId": "210472", "Score": "4" } } ]
{ "AcceptedAnswerId": "210515", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:07:05.843", "Id": "210472", "Score": "2", "Tags": [ "c#" ], "Title": "Simple Quiz game with Strategy and Factory pattern" }
210472
<p>I'm a beginner in OOP and PHP frameworks. I used slim skeleton to create a project and designed the project in this way. </p> <p>Project structure is given by the slim skeleton. Object Mappers are added by my self. I want to know whether this is a good practice. What I'm doing wrong here. Is there any better way to do this?</p> <pre><code>src Controllers PostController.php CommentController.php Models Post.php Comment.php ObjectMappers PostMapper.php CommentMapper.php Dependencies.php Middleware.php Routes.php Settings.php </code></pre> <p>Model files are used to include queries for relevant class. Mappers are the real classes that used to map query results to necessary class. Controllers are for necessary operations before sending it to the user.</p> <p>Post.php</p> <pre><code>namespace App\Models; class Post { public function getPostById($id){ $sql = "SELECT `post_id`, `post` FROM `posts` WHERE `post_id` = :id"; try { $stmt = $this-&gt;db-&gt;prepare($sql); $stmt-&gt;execute(['id' =&gt; $id]); $post = $stmt-&gt;fetchObject('\App\ObjectMappers\PostMapper'); if($post){ return $post; } return false; } catch (\PDOException $e){ return false; } } // Other queries } </code></pre> <p>PostMapper.php</p> <pre><code>namespace App\ObjectMappers; class PostObject { public $post_id; public $post; public function __construct(){} public function getPost_id() { return $this-&gt;post_id; } public function setPost_id($post_id) { $this-&gt;post_id= $post_id; return $this; } public function getPost() { return $this-&gt;post; } public function setPost($post) { $this-&gt;post= $post; return $this; } } </code></pre> <p>PostController.php</p> <pre><code>namespace App\Controllers; class PostController { public function ($request, $response, $args){ $postId = $request-&gt;getAttribute("post_id"); if(!$postId){ return $response-&gt;withJSON("post id not found"); } $post = $this-&gt;Post-&gt;getPostById($postId); if(!$post ){ return $response-&gt;withJSON("post not found"); } return $response-&gt;withJSON($post); } } </code></pre> <p>I'll be glad if you can help me. I'm trying to avoid using existing ORMs here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:14:08.717", "Id": "406844", "Score": "0", "body": "Welcome to Code Review. From your post, it's not clear what you wwant to get reviewed. Just the general structure? Or the code? Note that example code is **off-topic** on Code Review. I mention this since your code snippets are prefaced with \"For example\". If that's actual code that you really want to get reviewed, I suggest you to remove that phrase. Also keep in mind that questions should provide some context, and at the moment, your structure looks **very** generic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:18:15.993", "Id": "406849", "Score": "0", "body": "I edited the question." } ]
[ { "body": "<p>This is good in general. The main point is that you confused a model and a mapper. Your mapper must be a model (or, to avoid a confusion, better to call it an <em>entity</em>) whereas your model is actually a mapper. </p>\n\n<p>People often mistake the term \"model\", so I had to write an <a href=\"https://phpdelusions.net/articles/mvc\" rel=\"nofollow noreferrer\">article to explain it</a>.</p>\n\n<p>So</p>\n\n<pre><code>src\n Controllers\n PostController.php\n CommentController.php\n Entities\n Post.php\n Comment.php\n Mappers\n PostMapper.php\n CommentMapper.php\n Dependencies.php\n Middleware.php\n Routes.php\n Settings.php\n</code></pre>\n\n<p>where Post.php would be</p>\n\n<pre><code>namespace App\\Entities;\n\nclass Post {\n\n protected $postId;\n protected $post;\n\n public function __construct(){}\n\n public function getPostId()\n {\n return $this-&gt;postId;\n }\n\n public function setPostId($postId)\n {\n $this-&gt;postId= $postId;\n return $this;\n }\n\n public function getPost()\n {\n return $this-&gt;post;\n }\n\n public function setPost($post)\n {\n $this-&gt;post= $post;\n return $this;\n }\n}\n</code></pre>\n\n<p>and PostMapper would be</p>\n\n<pre><code>namespace App\\Mappers;\n\nclass PostMapper {\n\n public function getPostById($id){\n\n $sql = \"SELECT `post_id`, `post` FROM `posts` WHERE `post_id` = :id\";\n $stmt = $this-&gt;db-&gt;prepare($sql);\n $stmt-&gt;execute(['id' =&gt; $id]);\n return $stmt-&gt;fetchObject('\\App\\Entity\\Post');\n }\n}\n</code></pre>\n\n<p>Please note that a lot of code has been removed from PostMapper class. First, a harmful try .. catch has been removed. A try .. catch that silently returns false is as bad as any other error suppression operator, and shouldn't be used such casually. As a programmer, you crave to know what the error was, so you'll be able to fix it. So always let errors go, unless you have a certain handling scenario. See more in my article, <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting basics</a>.</p>\n\n<p>Also, rather useless condition is removed too, as <code>fetchObject()</code> already returns false if a row not found, so we can return its result right away. </p>\n\n<p>Also, consider making your PHP code style to conform with the <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">standard</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:14:13.533", "Id": "406848", "Score": "0", "body": "Thank you very much for the answer. I would like to know how the controller is going to be relevant to your edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:20:47.400", "Id": "406850", "Score": "0", "body": "At the moment the controller is a regular controller, does exactly what a controller should. So I have nothing to review in it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:27:49.120", "Id": "406851", "Score": "0", "body": "in the post mapper, the return should be like this\n **return $stmt->fetchObject('\\App\\Entities\\Post');**\nam I correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:34:28.357", "Id": "406853", "Score": "0", "body": "Can you tell me some resources on learning PHP OOP and MVC further. I'm still new. Your website looks cool. bookmarked it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T12:03:17.850", "Id": "406858", "Score": "0", "body": "I would suggest https://phptherightway.com/ as a theory and then https://symfonycasts.com/screencast/symfony for the best practice you can get" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T10:14:07.067", "Id": "210475", "ParentId": "210473", "Score": "0" } } ]
{ "AcceptedAnswerId": "210475", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T09:35:11.507", "Id": "210473", "Score": "0", "Tags": [ "php", "object-oriented", "mvc", "slim" ], "Title": "PHP OOP MVC Project Structure" }
210473
<p>Let's say I have this folder tree:</p> <pre class="lang-none prettyprint-override"><code>├──FolderParent ├── FolderA ├── FolderAA_IMG -- should be renamed ├── file_IMG_AA1.txt -- should NOT be renamed ├── file_VID_AA1.txt -- should NOT be renamed ├── file_IMG_A1.txt -- should be renamed ├── file_PANO_A1.txt -- should be renamed ├── FolderB ├── file_IMG_B1.txt -- should be renamed ├── file_PANO_B1.txt -- should be renamed </code></pre> <p>As you can see, only the files/folders in the first children folder should be renamed, not the other ones. I follow this <a href="https://stackoverflow.com/a/52156458/3154274">base code</a> and then I added a second loop above but I wonder if the double <code>for</code> loop is the right way to go.</p> <pre class="lang-py prettyprint-override"><code>import os # custom var path= r"C:\Users\user\FolderParent" # other cvar number_modified_files= 0 # get all path of subfolder all_subfolders = [f.path for f in os.scandir(path) if f.is_dir() ] print(all_subfolders) for folder in all_subfolders: # set the path to the folder: otherwise the rename file won't work os.chdir(folder) #won't rename files in subfolder but will rename folder in the path for filename in os.listdir(folder): print("new file:", filename) if "IMG_" in filename: os.rename(filename, filename.replace('IMG_', '')) number_modified_files +=1 elif "PANO_" in filename: os.rename(filename, filename.replace('PANO_', '')) number_modified_files +=1 elif "VID_" in filename: os.rename(filename, filename.replace('VID_', '')) number_modified_files +=1 print(f"End : {number_modified_file} files renamed") </code></pre>
[]
[ { "body": "<h2>Use regex to replace pattern in filename</h2>\n\n<p>The structure of these <code>if else</code> all similar, you can use <code>re</code> to simplify it.</p>\n\n<pre><code>if \"IMG_\" in filename:\n os.rename(filename, filename.replace('IMG_', ''))\n number_modified_files +=1\nelif \"PANO_\" in filename:\n os.rename(filename, filename.replace('PANO_', ''))\n number_modified_files +=1\nelif \"VID_\" in filename:\n os.rename(filename, filename.replace('VID_', '')) \n number_modified_files +=1\n</code></pre>\n\n<p>So you are looking for <code>IMG_</code>, <code>PANO_</code> and <code>VID_</code> in filename and try to replace it delete this part. </p>\n\n<p>Instead of using <code>os.rename</code> multiply times, we can use <code>re.sub(pattern, repl, string, count=0, flags=0)</code> to do this.</p>\n\n<p>It will Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.</p>\n\n<pre><code>pattern = 'IMG_|PANO_|VID_'\nrenamed_filename = re.sub(pattern, '', filename)\n</code></pre>\n\n<p>The <code>pattern</code> meaning match one in three. I am not sure if your are familiar with regex, here is the <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">doc</a>.</p>\n\n<p>And if the renamed_filename not equal filename it is modified, so whole part will be</p>\n\n<pre><code>pattern = 'IMG_|PANO_|VID_'\nrenamed_filename = re.sub(pattern, '', filename)\nif renamed_filename != filename:\n number_modified_files +=1\n os.rename(filename, renamed_filename)\n</code></pre>\n\n<blockquote>\n <p>Edit: Incorrect to use re.sub with os.rename</p>\n</blockquote>\n\n<p>To fix this just remove the <code>os.chdir(folder)</code>, there is no point doing this</p>\n\n<pre><code># os.chdir(folder)\n...\npattern = 'IMG_|PANO_|VID_'\nrenamed_filename = re.sub(pattern, '', filename)\nfile_path = os.path.join(folder, filename)\nif renamed_filename != filename:\n number_modified_files +=1\n renamed_file_path = os.path.join(folder, renamed_filename)\n os.rename(file_path, renamed_file_path)\n</code></pre>\n\n<h2>Regex side effect</h2>\n\n<p>But the regex code will work differ from your original code, as in your code, the replace end if it match in one pattern, but regex solution will try to replace all patterns in <code>IMG_</code> <code>PANO_</code> and <code>VID_</code>.</p>\n\n<h2>Store replace pattern in list</h2>\n\n<p>I suggest you use a list to store the patterns(<code>IMG_</code> <code>PANO_</code> and <code>VID_</code>) </p>\n\n<p>if you wanna stop replace in the first match, use a loop to check one by one, </p>\n\n<pre><code>patterns = [\"IMG_\", \"PANO_\", \"VID_\"]\n...\nfor pattern in patterns:\n if pattern in filename:\n os.rename(filename, filename.replace(pattern, ''))\n number_modified_files +=1\n</code></pre>\n\n<p>Or if you wanna replace all patterns, use regex</p>\n\n<pre><code>re.compile(\"|\".join(patterns))\n</code></pre>\n\n<p>It is easy for only 3 patterns now, but will drive you crazy if there are 30.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:19:40.837", "Id": "406894", "Score": "0", "body": "There's no point to passing the `count` and `flags` kwargs to `re.sub` in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:20:14.350", "Id": "406895", "Score": "0", "body": "Also, don't use the `re.sub` form at all. Use `re.compile` and call `sub` on the compiled regex object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:21:29.793", "Id": "406896", "Score": "0", "body": "Finally: you're applying `rename` and `sub` on the same filename, which is incorrect. `sub` must only be applied on the filename without path, and `rename` must have the path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:31:15.043", "Id": "406898", "Score": "0", "body": "you are correct for \"sub must only be applied on the filename without path\", I took a mistake on it, and \"There's no point to passing the count and flags kwargs to re.sub in this case. \" I just showing the function, and thanks for \" Use re.compile and call sub on the compiled regex object.\", updating my comment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T22:17:52.583", "Id": "406955", "Score": "0", "body": "Looks OK now :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:13:29.417", "Id": "210498", "ParentId": "210481", "Score": "2" } }, { "body": "<p>You should rethink your solution in terms of regexes:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport re\nfrom os import scandir, rename, path\n\n\ndef rename_children(parent):\n n_renamed = 0\n re_fname = re.compile('(IMG|PANO|VID)_')\n\n for child_dir in scandir(parent):\n if child_dir.is_dir():\n for child in scandir(child_dir):\n renamed = re_fname.sub('', child.name)\n if renamed != child.name:\n new_path = path.join(child_dir.path, renamed)\n print(f'Renaming {child.path} to {new_path}')\n rename(child.path, new_path)\n n_renamed += 1\n print(f'{n_renamed} files renamed')\n</code></pre>\n\n<p>Note the following changes:</p>\n\n<ul>\n<li>Only one <code>if</code> to check whether the regex matches</li>\n<li>Use <code>scandir</code> instead of <code>listdir</code></li>\n<li>Do not call <code>chdir</code>; there's no point</li>\n<li>Don't call <code>replace</code>; the pattern check and the replacement operation can be combined by using <code>sub</code></li>\n<li>Don't store a list of <code>all_subfolders</code>; simply iterate over the results</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:15:20.360", "Id": "210499", "ParentId": "210481", "Score": "3" } } ]
{ "AcceptedAnswerId": "210499", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T11:38:38.793", "Id": "210481", "Score": "2", "Tags": [ "python", "file-system" ], "Title": "Renaming all files/folders in first children folders but not sub-children" }
210481
<p>I have put together this small application that displays a "Users" JSON in an HTML5 table.</p> <p>I use Bootstrap 3, Axios and Vue.js 2 for this purpose.</p> <p>Here is the code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = new Vue({ el: '#app', data: { users: [], loading: true, errored: false, url: "https://randomuser.me/api/?&amp;results=500&amp;inc=name,location,email,cell,picture", search: '', page: 1, perPage: 25, pages: [], }, methods: { getUsers() { axios .get(this.url) .then(response =&gt; { this.users = response.data.results }) .catch(error =&gt; { console.log(error) this.errored = true }) .finally(() =&gt; this.loading = false) }, setPages(users) { this.pages.length = 0; var numberOfPages = Math.ceil(users.length / this.perPage); for (var index = 1; index &lt;= numberOfPages; index++) { this.pages.push(index); } }, paginate(users) { var page = this.page; var perPage = this.perPage; var from = (page * perPage) - perPage; var to = (page * perPage); return users.slice(from, to); }, scrollToTop() { $("html, body").animate({ scrollTop: 0 }, 500); return false; }, }, created() { this.getUsers(); }, watch: { displayedUsers() { this.setPages(this.searchResults); } }, computed: { displayedUsers() { return this.paginate(this.searchResults); }, searchResults() { this.page = 1; return this.users.filter((user) =&gt; { const { first, last } = user.name; const { email } = user; const { city } = user.location; const lowerCaseSearch = this.search.toLowerCase() return `${first} ${last}`.toLowerCase().match(lowerCaseSearch) || email.toLowerCase().match(lowerCaseSearch) || city.toLowerCase().match(lowerCaseSearch); }); } }, filters: { lowercase(value) { return value.toLowerCase(); }, capitalize(value) { return value.charAt(0).toUpperCase() + value.slice(1); }, titlecase(value) { return value.toLowerCase().replace(/(?:^|[\s-/])\w/g, function(match) { return match.toUpperCase(); }) } } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.table-container { margin: 10px; } .table-container .panel-heading { font-weight: bold; } .table-container .panel-heading { display: flex; align-items: center; } .table-container .panel-heading h2 { margin: 0 auto 0 0; font-size: 18px; font-weight: bold; } .table-container .panel-heading .searchbox { margin-left: 10px; } .table-container .panel-body { padding: 0; } .table-container table { margin-bottom: 0; border: none; } .table-container table tr:last-child td { border-bottom: none; } .table-container table tr th { font-weight: bold; } .table-container table tr th:first-child, .table-container table tr td:first-child { border-left: none; } .table-container table tr th:last-child, .table-container table tr td:last-child { border-right: none; } .table-container table tr td { padding: 2px 8px !important; vertical-align: middle; } .table-container table tr td .picture { padding-right: 10px; } .table-container table tr td img { max-height: 30px; width: auto; border: 1px solid #c7c7c7; } .pagination { margin-top: 5px; } .pagination li a:focus, .pagination li a:hover { background: inherit; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div id="app" class="container"&gt; &lt;div class="panel panel-default table-container"&gt; &lt;div class="panel-heading clearfix"&gt; &lt;h2 class="pull-left"&gt;Users&lt;/h2&gt; &lt;div class="searchbox"&gt; &lt;input type="text" v-model="search" class="form-control" placeholder="Search..."&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="table-responsive"&gt; &lt;table class="table table-striped table-bordered" id="dataTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="text-right"&gt;#&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;City&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr v-for="(user, index) in displayedUsers"&gt; &lt;td class="text-right"&gt;{{perPage * (page - 1) + index + 1}}&lt;/td&gt; &lt;td&gt; &lt;span class="picture"&gt; &lt;img :src="user.picture.thumbnail" :alt="user.name.first + ' ' + user.name.last" class="img-circle"&gt; &lt;/span&gt; &lt;span&gt;{{user.name.first | capitalize}} {{user.name.last | capitalize}}&lt;/span&gt; &lt;/td&gt; &lt;td&gt;&lt;a :href="'mailto:' + user.email | lowercase"&gt;{{user.email | lowercase}}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{user.location.city | titlecase}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;nav class="text-center" aria-label="Page navigation"&gt; &lt;ul class="pagination pagination-sm"&gt; &lt;li @click="scrollToTop"&gt; &lt;a href="#" @click="page = 1;" aria-label="First"&gt; &lt;span aria-hidden="true"&gt;&amp;laquo;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li @click="scrollToTop"&gt; &lt;a href="#" v-if="page != 1" @click="page--;" aria-label="Previous"&gt; &lt;span aria-hidden="true"&gt;&amp;lsaquo;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li v-for="pageNumber in pages.slice(page-1, page+4)" :class="{'active': page === pageNumber}" @click="scrollToTop"&gt;&lt;a href="#" @click="page = pageNumber;"&gt;{{pageNumber}}&lt;/a&gt;&lt;/li&gt; &lt;li @click="scrollToTop"&gt; &lt;a href="#" @click="page++" v-if="page &lt; pages.length" aria-label="Next"&gt; &lt;span aria-hidden="true"&gt;&amp;rsaquo;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li @click="scrollToTop"&gt; &lt;a href="#" @click="page = pages.length;" aria-label="Last"&gt; &lt;span aria-hidden="true"&gt;&amp;raquo;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>It works, but I am certain there is room for improvement. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T15:43:51.503", "Id": "409060", "Score": "2", "body": "Please do not edit the code after people have started posting answers." } ]
[ { "body": "<p>Overall the code looks fine. There aren't any drastic changes I would advise - just mostly a few simplifications. As far as the design goes it looks good, though it may be wise to add a spinner icon or some other indication while the data is loading, lest the user think nothing is happening. And it doesn't appear that anything happens when <code>errored</code> is set to true. Perhaps the UI should notify the user that there was a problem fetching the data.</p>\n\n<p>The URL doesn't really change so it doesn't need to be in the <code>data</code> object. I would move it out to a constant.</p>\n\n<pre><code>const API_URL = \"https://randomuser.me/api/?&amp;results=500&amp;inc=name,location,email,cell,picture\";\n</code></pre>\n\n<hr>\n\n<p>I understand what the following block in the filter function of <code>searchResults()</code> is doing:</p>\n\n<blockquote>\n<pre><code> const {\n first,\n last\n } = user.name;\n const {\n email\n } = user;\n const {\n city\n } = user.location;\n</code></pre>\n</blockquote>\n\n<p>But is it really necessary to define all of those things instead of just using the properties, as in below? I could maybe see a point for the nested properties but not so much for <code>user.email</code>...</p>\n\n<pre><code>return `${user.name.first} ${user.name.last}`.toLowerCase().match(lowerCaseSearch) ||\n user.email.toLowerCase().match(lowerCaseSearch) ||\n user.location.city.toLowerCase().match(lowerCaseSearch);\n</code></pre>\n\n<hr>\n\n<p>The following CSS rulesets could be combined:</p>\n\n<blockquote>\n<pre><code>.table-container .panel-heading {\n font-weight: bold;\n}\n.table-container .panel-heading {\n display: flex;\n align-items: center;\n}\n</code></pre>\n</blockquote>\n\n<p>The font-weight specification could be moved into the lower declaration block, unless you wanted to pull the bold specification out of the heading ruleset (i.e. <code>.table-container .panel-heading h2</code>) and combine it with the lone bold rule.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T18:42:32.800", "Id": "211340", "ParentId": "210483", "Score": "4" } } ]
{ "AcceptedAnswerId": "211340", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T12:11:48.960", "Id": "210483", "Score": "3", "Tags": [ "css", "ecmascript-6", "twitter-bootstrap", "vue.js", "axios" ], "Title": "Display and search through a JSON's items in Vue.js" }
210483
<p>I am using below virtual method to read the data from SQL Data Reader like:</p> <pre><code>public IList&lt;District&gt; GetList() { IList&lt;District&gt; _list = new List&lt;District&gt;(); SqlConnection con = new SqlConnection(ConStr); try { string StoreProcedure = ConfigurationManager.AppSettings["SP"].ToString(); SqlCommand cmd = new SqlCommand(StoreProcedure, con); cmd.CommandType = CommandType.StoredProcedure; con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); _list = new GenericReader&lt;District&gt;().CreateList(rdr); rdr.Close(); con.Close(); } finally { IsConnectionOpenThenClose(con); } return _list; } </code></pre> <p>District Class:</p> <pre><code>public class District { public int id { get; set; } public string name { get; set; } } </code></pre> <p>And GenericReader Class as:</p> <pre><code>public class GenericReader&lt;T&gt; { public virtual List&lt;T&gt; CreateList(SqlDataReader reader) { var results = new List&lt;T&gt;(); while (reader.Read()) { var item = Activator.CreateInstance&lt;T&gt;(); foreach (var property in typeof(T).GetProperties()) { if (!reader.IsDBNull(reader.GetOrdinal(property.Name))) { Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; property.SetValue(item, Convert.ChangeType(reader[property.Name], convertTo), null); } } results.Add(item); } return results; } } </code></pre> <p>Is this approach is better or still, we can refactor?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:06:06.610", "Id": "406874", "Score": "0", "body": "Welcome to Code Review. If you're still open for suggestions, why did you already accept an answer? It's a feature of StackExchange that now question every \"closes\" completely (unless it's on hold), you don't need to point that out to other users." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:07:26.890", "Id": "406876", "Score": "0", "body": "Understood! will remove the line" } ]
[ { "body": "<p><code>GetList()</code> </p>\n\n<ul>\n<li><p><code>SqlConnection</code>, <code>SqlCommand</code> and <code>SqlDataReader</code> are all implementing the <code>IDisposable</code> interface hence you should either call <code>Dispose()</code> on that objects or enclosing them in a <code>using</code> block. </p></li>\n<li><p>You should use <code>var</code> instead of the concrete type if the right-hand-side of an assignment makes the concrete type obvious.<br>\nE.g the line <code>SqlConnection con = new SqlConnection(ConStr);</code> we can see at first glance that the concrete type is <code>SqlConnection</code> and therfor we should use <code>var con = new SqlConnection(ConStr);</code> instead.</p></li>\n<li><p>Using abbreviations for naming things shouldn't be done because it makes reading and maintaining the code so much harder. </p></li>\n<li>Underscore-prefixed variablenames are usually used for class-level variables. Method-scoped variables should be named using <code>camelCase</code> casing hence <code>list</code> would be better than <code>_list</code> because Sam the maintainer wouldn't wonder about it. </li>\n<li>You return an <code>IList&lt;&gt;</code> which is good because coding against interfaces is the way to go.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:30:15.900", "Id": "406862", "Score": "0", "body": "Would like to read more! Mostly about `CreateList()`!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:31:44.357", "Id": "406863", "Score": "0", "body": "Do I need to call `con.Close()` and `con.Dispose()` both methods? or `Dispose()` will do the work of `.Close()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:35:36.193", "Id": "406864", "Score": "1", "body": "Dispose is doing the Close for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:36:30.707", "Id": "406865", "Score": "0", "body": "Can you please explain Point no2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:38:53.600", "Id": "406866", "Score": "0", "body": "Edited answer for No2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:40:33.443", "Id": "406867", "Score": "0", "body": "yes got it! any benefit of doing this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:48:29.857", "Id": "406869", "Score": "0", "body": "Its less typing and easier to refactor." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:25:23.873", "Id": "210489", "ParentId": "210488", "Score": "2" } } ]
{ "AcceptedAnswerId": "210489", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T13:11:50.467", "Id": "210488", "Score": "1", "Tags": [ "c#", "generics" ], "Title": "Implementation of Generic SQL Data Reader" }
210488
<p>The code creates a very simple/easy RPG game, with 2 classes <code>Jedi</code> and <code>Orc</code>. The data is visualized using <code>turtle</code>. Each class has a method of <code>attack</code> (<code>lightsaber_attack</code> for <code>Jedi</code>), which has an argument that must be either a <code>Jedi</code> or <code>Orc</code> instance. The <code>.health</code> attribute of the attacked one will be reduced by <code>.power</code> of the attacker. If <code>.health</code> is not positive, then the image of the character will disappear. By design, each character can attack itself.</p> <h2>Simulation</h2> <pre><code>luke.lightsaber_attack( orc_1 ) luke.lightsaber_attack( orc_2 ) orc_1.attack( luke ) orc_2.attack( orc_2 ) </code></pre> <h2>Questions</h2> <ul> <li>How can I make the code to be easily understood by teenagers? (in a tutorial)</li> <li>How can I make it more compact?</li> <li>Are there any missing important features of Python's OOP that are important to be explained to students? (other than <code>super</code> and inheritance)</li> </ul> <h2>Image Links</h2> <ul> <li><a href="https://www.google.com/url?sa=i&amp;rct=j&amp;q=&amp;esrc=s&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwit1aug3sLfAhVLqI8KHXkhDVQQjRx6BAgBEAU&amp;url=http%3A%2F%2Fphotobucket.com%2Fgifs%2Fluke%2520skywalker%2520gif&amp;psig=AOvVaw0FAdw5ahuUpluC-GQ9eF2D&amp;ust=1546093763401668" rel="nofollow noreferrer">jedi.gif</a></li> <li><a href="https://thumbs.gfycat.com/DependableIllArmyworm-max-1mb.gif" rel="nofollow noreferrer">orc.gif</a></li> <li><a href="https://opengameart.org/sites/default/files/attack_3.gif" rel="nofollow noreferrer">darkorc.gif</a></li> <li><a href="https://www.google.com/url?sa=i&amp;rct=j&amp;q=&amp;esrc=s&amp;source=images&amp;cd=&amp;ved=2ahUKEwjD8IOF4MLfAhVINo8KHbO7DaUQjRx6BAgBEAU&amp;url=https%3A%2F%2Fgifer.com%2Fen%2F3IsK&amp;psig=AOvVaw1Jlevg6MxHqG_Xv4XBkeTg&amp;ust=1546094231810744" rel="nofollow noreferrer">damaged.gif</a> </li> </ul> <h2>Full code</h2> <pre><code>import turtle import time jedi_gif = "/home/asus/Arief_tempo/images/random/jedi.gif" orc_gif = "orc.gif" darkorc_gif = "darkorc.gif" damaged_gif = "damaged.gif" turtle.register_shape( jedi_gif ) turtle.register_shape( orc_gif ) turtle.register_shape( darkorc_gif ) turtle.register_shape( damaged_gif ) class JediLuke: def __init__(self): self.power = 300 self.health = 300 self.img = turtle.Turtle( shape = jedi_gif ) self.damaged_img = turtle.Turtle( shape = damaged_gif, visible = False ) self.img.penup() self.damaged_img.penup() def lightsaber_attack(self, enemy): self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1]) enemy.damaged_img.showturtle() enemy.health += - self.power time.sleep(1) enemy.damaged_img.hideturtle() if enemy.health &lt; 0: enemy.img.hideturtle() self.img.setpos(200, 0) def change_pos(self, pos): self.img.setpos(pos[0], pos[1]) self.damaged_img.setpos(pos[0], pos[1] + 150) class Orc: def __init__(self, health, gif_image): self.power = 100 self.health = health self.img = turtle.Turtle( shape = gif_image ) self.damaged_img = turtle.Turtle( shape = damaged_gif, visible = False ) self.img.penup() self.damaged_img.penup() def attack(self, enemy): current_pos = self.img.pos() self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1]) enemy.damaged_img.showturtle() enemy.health += - self.power time.sleep(1) enemy.damaged_img.hideturtle() if enemy.health &lt; 0: enemy.img.hideturtle() self.img.setpos(current_pos[0], current_pos[1]) def change_pos(self, pos): self.img.setpos(pos[0], pos[1]) self.damaged_img.setpos(pos[0], pos[1] + 150) luke = JediLuke() luke.change_pos( [200, 0] ) orc_1 = Orc( health = 400 , gif_image = orc_gif) orc_1.change_pos( [-200, 100] ) orc_2 = Orc( health = 200, gif_image = darkorc_gif ) orc_2.change_pos( [-200, -100] ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:45:58.663", "Id": "406903", "Score": "5", "body": "As an aside: Luke Skywalker attacking orcs is a jarring mix-up of universes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:10:48.607", "Id": "406910", "Score": "3", "body": "I upvoted @Reinderien 's comment, but I also +1 this question because Luke Skywalker. Fighting Orcs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:22:41.400", "Id": "406916", "Score": "5", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:37:22.970", "Id": "407382", "Score": "0", "body": "@Mast noted...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T09:48:41.877", "Id": "407488", "Score": "0", "body": "why name the attacks differently?" } ]
[ { "body": "<pre><code>jedi_gif = \"/home/asus/Arief_tempo/images/random/jedi.gif\"\n</code></pre>\n\n<p>It's unclear why this image has an absolute path but no others do. They should probably all be relative, as the other three are.</p>\n\n<p>Especially if this is for a tutorial, you need to add docstrings to all of your functions.</p>\n\n<p>This:</p>\n\n<pre><code>self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1])\n</code></pre>\n\n<p>can use argument expansion, i.e.:</p>\n\n<pre><code>self.img.setpos(*enemy.img.pos())\n</code></pre>\n\n<p>That pattern can be used elsewhere you're indexing into the position.</p>\n\n<p>This:</p>\n\n<pre><code>enemy.health += - self.power\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>enemy.health -= self.power\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T13:01:49.537", "Id": "407008", "Score": "0", "body": "Thanks. Why need docstrings? the functions will be explained in class. If I use `f(*pos)` then I need to explain further about function to the kids (which makes the subject a bit more tedious to them), but using `f(pos[0], pos[1])` would be more obvious." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:59:58.770", "Id": "407027", "Score": "0", "body": "\"Explaining it [presumably verbally] in class\" is not good enough. The code should document itself. You should be able to hand a copy to a programmer who has not attended your class and have some reasonable expectation that they'll understand what's going on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T15:59:56.987", "Id": "210503", "ParentId": "210494", "Score": "10" } }, { "body": "<p>Just a note of something that was particularly jarring when viewing your code; for stylistic reasons, you shouldn't have spaces on either side of the arguments:</p>\n\n<pre><code>turtle.register_shape( jedi_gif )\n</code></pre>\n\n<p>Instead you want:</p>\n\n<pre><code>turtle.register_shape(jedi_gif)\n</code></pre>\n\n<p>This is covered in <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"noreferrer\">PEP 8</a> in the section <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"noreferrer\">Whitespace in Expressions and Statements</a>. It's good to follow PEP 8 because it makes it easier for others (and in the long run, yourself) to read your code:</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:39:50.397", "Id": "210513", "ParentId": "210494", "Score": "6" } }, { "body": "<p>One guiding principle in programming is to write DRY code, <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>. Your <code>JediLuke</code> class and your <code>Orc</code> class are almost the same. Since you are already teaching about classes, you should also teach about inheritance (maybe later, but eventually).</p>\n\n<pre><code>import turtle\nimport time\n\nclass Entity:\n def __init__(self, power, health, img, damaged_img, *position):\n self.power = power\n self.health = health\n self.img = turtle.Turtle(shape=img)\n self.damaged_img = turtle.Turtle(shape=damaged_img, visible=False)\n\n self.img.penup()\n self.damaged_img.penup()\n self.set_position(*position)\n\n def attack(self, enemy):\n \"\"\"Attack an enemy\"\"\"\n current_pos = self.img.pos()\n self.img.setpos(*enemy.img.pos())\n enemy.damaged(self.power)\n self.img.setpos(*current_pos)\n\n def damaged(self, power):\n \"\"\"Take damage from `power`\"\"\"\n self.damaged_img.showturtle()\n self.health -= power\n time.sleep(1)\n self.damaged_img.hideturtle()\n if self.health &lt;= 0:\n self.img.hideturtle()\n\n def set_position(self, pos):\n self.img.setpos(*pos)\n self.damaged_img.setpos(pos[0], pos[1] + 150)\n\n\nclass Jedi(Entity):\n def lightsaber_attack(self, enemy):\n super().attack(enemy)\n\n attack = None # to ensure it cannot be called...\n\n\nclass Orc(Entity):\n pass\n\n\nif __name__ == \"__main__\":\n\n jedi_gif = \"jedi.gif\"\n orc_gif = \"orc.gif\"\n darkorc_gif = \"darkorc.gif\"\n damaged_gif = \"damaged.gif\" \n\n turtle.register_shape(jedi_gif)\n turtle.register_shape(orc_gif)\n turtle.register_shape(darkorc_gif)\n turtle.register_shape(damaged_gif)\n\n luke = Jedi(200, 0)\n orc_1 = Orc(400, orc_gif, -200, 100) \n orc_2 = Orc(200, darkorc_gif, -200, -100)\n</code></pre>\n\n<p>This also has the calling code under an <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\"</code> guard</a> to allow importing from this script and the whitespace fixed according to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:16:52.657", "Id": "210598", "ParentId": "210494", "Score": "2" } }, { "body": "<p>I just wanted to add use os path for cross compatibility with other os's. Since mac uses a \"/\", and windows \"\\\"</p>\n\n<p>otherwise if you copy your code to windows and run the script you will get an error saying it's not a valid directory</p>\n\n<p>use</p>\n\n<pre><code>from os import path\n\npath.join(\"Directory1\", \"Directory2\", \"filename.gif\") \n# Equal to \"Directory1/Directory2/filename.gif\n# or \"Directory1\\Directory2\\filename.gif\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T09:48:44.433", "Id": "210802", "ParentId": "210494", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:50:10.750", "Id": "210494", "Score": "9", "Tags": [ "python", "object-oriented", "game", "role-playing-game", "turtle-graphics" ], "Title": "Simple (Very Easy to Make) RPG Game Simulation in Python and Turtle" }
210494
<p>Well I have 3 methods that are overloads, but in it's scope has the same scope except one method call.</p> <pre><code> public static Texture2D DrawAnnulus(this Texture2D texture, Func&lt;int, int, Color?&gt; predicate, AnnulusConfig annulusConfig) { InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2); Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, predicate); if (annulusConfig.apply) texture.Apply(); return texture; } public static Texture2D DrawAnnulus(this Texture2D texture, SectorList list, AnnulusConfig annulusConfig) { InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2); Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, (xx, yy) =&gt; Annulus(annulusConfig.offset.x, annulusConfig.offset.y, xx, yy, annulusConfig.radius2, list)); if (annulusConfig.apply) texture.Apply(); return texture; } public static Texture2D DrawAnnulus(this Texture2D texture, Color? color, AnnulusConfig annulusConfig) { InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2); Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, (xx, yy) =&gt; Annulus(annulusConfig.offset.x, annulusConfig.offset.y, xx, yy, annulusConfig.radius2, color)); if (annulusConfig.apply) texture.Apply(); return texture; } </code></pre> <p>As you can see the only changing part is the <code>Polar</code> method call. The other part is only checks.</p> <p>How could I simplify this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:40:31.317", "Id": "406929", "Score": "1", "body": "You need to tell us the purpose of the code and explain what it does. It' currently just code without any explanation which makes it off-topic." } ]
[ { "body": "<p>You could create a single private method and decide there what overload to call based on the presence of the arguments</p>\n\n<pre><code>public static Texture2D DrawAnnulus(this Texture2D texture, \n Func&lt;int, int, Color?&gt; predicate, \n AnnulusConfig annulusConfig)\n =&gt; texture.DoDrawAnnulus(predicate, anulusConfig, null, null);\n\n public static Texture2D DrawAnnulus(this Texture2D texture\n ,SectorList list\n ,AnnulusConfig annulusConfig)\n =&gt; texture.DoDrawAnnulus(null, anulusConfig, list, null); \n\n public static Texture2D DrawAnnulus(this Texture2D texture, \n Color? color, \n AnnulusConfig annulusConfig)\n =&gt; texture.DoDrawAnnulus(null, anulusConfig, null, color);\n\nprivate static Texture2D DoDrawAnnulus(this Texture2D texture, \n Func&lt;int, int, Color?&gt; predicate, \n AnnulusConfig annulusConfig, \n SectorList list, \n Color? color)\n {\n InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2);\n\n if (list != null)\n {\n Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, (xx, yy) =&gt; Annulus(annulusConfig.offset.x, annulusConfig.offset.y, xx, yy, annulusConfig.radius2, list));\n }\n else if (predicate != null)\n {\n Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, predicate);\n }\n else\n {\n Polar(texture, annulusConfig.offset.x, annulusConfig.offset.y, annulusConfig.radius, (xx, yy) =&gt; Annulus(annulusConfig.offset.x, annulusConfig.offset.y, xx, yy, annulusConfig.radius2, color));\n }\n\n if (annulusConfig.apply)\n texture.Apply();\n\n return texture;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:38:44.533", "Id": "406926", "Score": "0", "body": "Reflection? Dynamics? Ahhhhhh!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:39:46.433", "Id": "406928", "Score": "0", "body": "Yep, I might delete that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:42:50.610", "Id": "406932", "Score": "0", "body": "Do you think a polymorphic approach would solve the problem, or is it too much this too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:43:48.550", "Id": "406933", "Score": "0", "body": "Not sure, I'm not going to take any deeper look at OP's code until they fix the question and make it on topic." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:41:50.687", "Id": "210506", "ParentId": "210495", "Score": "1" } }, { "body": "<p>You could create a single private method and pass the Polar call as an action from each of the overloads</p>\n\n<pre><code>public static Texture2D DrawAnnulus(this Texture2D texture, Func&lt;int, int, Color?&gt; predicate, AnnulusConfig annulusConfig)\n =&gt; DrawAnnulus(\n texture,\n annulusConfig,\n () =&gt; Polar(\n texture,\n annulusConfig.offset.x,\n annulusConfig.offset.y,\n annulusConfig.radius,\n predicate));\n\npublic static Texture2D DrawAnnulus(this Texture2D texture, SectorList list, AnnulusConfig annulusConfig)\n =&gt; DrawAnnulus(\n texture,\n annulusConfig,\n () =&gt; Polar(\n texture,\n annulusConfig.offset.x,\n annulusConfig.offset.y,\n annulusConfig.radius,\n (xx, yy) =&gt; Annulus(\n annulusConfig.offset.x,\n annulusConfig.offset.y,\n xx,\n yy,\n annulusConfig.radius2, list)));\n\npublic static Texture2D DrawAnnulus(this Texture2D texture, Color? color, AnnulusConfig annulusConfig)\n =&gt; DrawAnnulus(\n texture,\n annulusConfig,\n () =&gt; Polar(\n texture,\n annulusConfig.offset.x,\n annulusConfig.offset.y,\n annulusConfig.radius,\n (xx, yy) =&gt; Annulus(\n annulusConfig.offset.x,\n annulusConfig.offset.y,\n xx,\n yy,\n annulusConfig.radius2,\n color)));\n\nprivate static Texture2D DrawAnnulus(Texture2D texture, AnnulusConfig annulusConfig, Action polarAction)\n{\n InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2);\n\n polarAction();\n\n if (annulusConfig.apply)\n texture.Apply();\n\n return texture;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:37:10.197", "Id": "406923", "Score": "1", "body": "I have to say that I find your calls pretty scarry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:42:42.090", "Id": "406931", "Score": "0", "body": "I totally agree. To be perfectly honest, I don't think I'd go this route myself. Of all the approaches I've seen so far, I believe I like OP's the best - although possibly some refactoring could be done upstream so that these extension methods aren't required to do such gymnastics." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:07:12.363", "Id": "210509", "ParentId": "210495", "Score": "2" } }, { "body": "<p>You could create helper methods for the repeated parts of the three overloads.</p>\n\n<pre><code>private static void InitTexture(ref Texture2D texture, AnnulusConfig annulusConfig)\n =&gt; InitTexture(ref texture, annulusConfig.offset.x + annulusConfig.radius * 2, annulusConfig.offset.y + annulusConfig.radius * 2);\n\nprivate static void ApplyIfNecessary(Texture2D texture, AnnulusConfig annulusConfig)\n{\n if (annulusConfig.apply)\n texture.Apply();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:37:31.800", "Id": "406924", "Score": "0", "body": "This should be part of the previous answer and not another one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:39:22.723", "Id": "406927", "Score": "0", "body": "I don't see why. It's a very different approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:41:57.417", "Id": "406930", "Score": "0", "body": "This isn't a different approach because `InitTexture` isn't even defined in your other answer. It's a method that is missing there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:44:01.333", "Id": "406934", "Score": "0", "body": "`InitTexture` (with all the arguments) isn't defined in any answer; I assume it exists because it's called by OP." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:10:59.077", "Id": "210510", "ParentId": "210495", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T14:53:57.113", "Id": "210495", "Score": "-2", "Tags": [ "c#", "extension-methods", "overloading" ], "Title": "Refactorizing overloads with the same scope but different calls" }
210495
<p>The default <a href="https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/" rel="noreferrer">.net core dependency injection</a> doesn't support building Func&lt;> for injection automatically, see <a href="https://stackoverflow.com/q/35736070">question</a>. I wrote an extension method to go find all the Func in register types constructors and build the Func automatically, needs to be called at end of registrations.</p> <pre><code>public static class ServiceCollectionExtensions { private static MethodInfo GetServiceMethod; static ServiceCollectionExtensions() { Func&lt;IServiceProvider, object&gt; getServiceMethod = ServiceProviderServiceExtensions.GetService&lt;object&gt;; GetServiceMethod = getServiceMethod.Method.GetGenericMethodDefinition(); } /// &lt;summary&gt; /// Registers all Funcs in constructors to the ServiceCollection - important to call after all registrations /// &lt;/summary&gt; /// &lt;param name="collection"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static IServiceCollection AddFactories(this IServiceCollection collection) { // Get a list of all Funcs used in constructors of regigstered types var funcTypes = new HashSet&lt;Type&gt;(collection.Where(x =&gt; x.ImplementationType != null) .Select(x =&gt; x.ImplementationType) .SelectMany(x =&gt; x.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) .SelectMany(x =&gt; x.GetParameters()) .Select(x =&gt; x.ParameterType) .Where(x =&gt; x.IsGenericType &amp;&amp; x.GetGenericTypeDefinition() == typeof(Func&lt;&gt;))); // Each func build the factory for it foreach (var funcType in funcTypes) { var type = funcType.GetGenericArguments().First(); collection.AddTransient(funcType, FuncBuilder(type)); } return collection; } /// &lt;summary&gt; /// This build expression tree for a func that is equivalent to /// Func&lt;IServiceProvider, Func&lt;TType&gt;&gt; factory = serviceProvider =&gt; new Func&lt;TType&gt;(serviceProvider.GetService&lt;TType&gt;); /// &lt;/summary&gt; /// &lt;param name="type"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static Func&lt;IServiceProvider, object&gt; FuncBuilder(Type type) { var serviceProvider = Expression.Parameter(typeof(IServiceProvider), "serviceProvider"); var method = GetServiceMethod.MakeGenericMethod(type); var call = Expression.Call(method, serviceProvider); var returnType = typeof(Func&lt;&gt;).MakeGenericType(type); var returnFunc = Expression.Lambda(returnType, call); var func = Expression.Lambda(typeof(Func&lt;,&gt;).MakeGenericType(typeof(IServiceProvider), returnType), returnFunc, serviceProvider); var factory = func.Compile() as Func&lt;IServiceProvider, object&gt;; return factory; } } </code></pre> <p>I register the Funcs as Transient but I think it would have been safe to register them as singleton. Not sure which has more overhead.</p> <p>For a simple test</p> <pre><code>public interface ITransient { Guid Id { get; } } public class Transient : ITransient { public Transient() { Id = Guid.NewGuid(); } public Guid Id { get; } } public class SingleTon { private readonly Func&lt;ITransient&gt; _transientFunc; public SingleTon(Func&lt;ITransient&gt; transientFunc) { _transientFunc = transientFunc; } public ITransient GetTransient() { return _transientFunc(); } } </code></pre> <p>If the func isn't working correctly I would get the same object each time back on the transient class.</p> <pre><code>static void Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton&lt;SingleTon&gt;(); serviceCollection.AddTransient&lt;ITransient, Transient&gt;(); serviceCollection.AddFactories(); var container = serviceCollection.BuildServiceProvider(); var singleton = container.GetService&lt;SingleTon&gt;(); if (object.ReferenceEquals(singleton.GetTransient(), singleton.GetTransient())) { throw new InvalidOperationException(); } Console.WriteLine("Done"); Console.ReadLine(); container.Dispose(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:43:43.253", "Id": "406918", "Score": "1", "body": "Singletons should not depend on transients" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:51:23.417", "Id": "406919", "Score": "0", "body": "I understand that is the guideline. I also agree with that guideline but sometimes you do need to have other classes used and either you can inject a func which you can sub out during testing or you have to use the service locator pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T22:32:55.640", "Id": "406959", "Score": "0", "body": "I added another answer to the question you referenced. I don't understand why the answers say that you can't register a function (although I recommend a delegate) because you can. https://stackoverflow.com/questions/35736070/how-to-use-funct-in-built-in-dependency-injection/53964998#53964998" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:08:45.070", "Id": "429786", "Score": "0", "body": "It's pretty bad that it relies on the parameter name as a hardcoded string. Isn't it possible to avoid somehow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:09:49.977", "Id": "429788", "Score": "0", "body": "It doesn't. It's looking for func sig" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T16:42:10.970", "Id": "210507", "Score": "5", "Tags": [ "c#", "dependency-injection", "asp.net-core" ], "Title": "Auto register Func<T> for .net core dependecy injection" }
210507
<p>The following code implements the Boyer Moore string matching algorithm. The algorithm is used to find a sub-string (called the pattern) in a string (called the text) and return the index of the beginning of the pattern. </p> <p>Looking for comments on correctness, efficiency, clarity and idiomatic C# usages. It passes all tests on <a href="https://leetcode.com/problems/implement-strstr/" rel="nofollow noreferrer">LeetCode</a>.</p> <pre><code>public static class BoyerMoore { private static void Main(string[] args) { string text = "Hello World" string pattern = "World"; Console.WriteLine(string.Join(",", IndexOf(text, pattern))); } public static IEnumerable&lt;int&gt; IndexOf(string text, string pattern) { if (pattern.Equals("")) { yield return 0; yield break; } // For an initial read of the algorithm, it is advisable to read this later, just assume you have a magic shift table computed int[] goodSuffixShifts = BuildGoodSuffixShifts(pattern); Dictionary&lt;char, int[]&gt; badCharacterShifts = BuildBadCharacterShifts(pattern); int i = 0; int goodSuffixCheck = -1; int goodSuffixSkip = 0; while (i + pattern.Length &lt;= text.Length) { // Consider the pattern is placed so that its first character it under the ith character of the text // We started the matching from the right of the pattern int patternIndex = pattern.Length - 1; int textIndex = i + patternIndex; while (patternIndex &gt;= 0 &amp;&amp; text[textIndex] == pattern[patternIndex]) { textIndex--; patternIndex--; // Here is an optimization for the good suffix case // If the shift is caused by a good suffix, we first count down the // number of characters shifted, as we knew nothing about the text for // those shifts if (goodSuffixCheck &gt; 0) { goodSuffixCheck--; } // Once we reach the point where we hit the known match if (goodSuffixCheck == 0) { // Then we just skip all the known matches goodSuffixCheck = -1; textIndex -= goodSuffixSkip; patternIndex -= goodSuffixSkip; } } // If the loop ended with patternIndex == -1 if (patternIndex == -1) { // The whole pattern matched yield return i; } // Figure out how many characters we can shift the pattern int matched = pattern.Length - patternIndex - 1; Debug.Assert(matched &lt;= pattern.Length); int badCharacterShift = 0; if (patternIndex != -1) { // In case we have a mismatching character char badCharacter = text[textIndex]; if (badCharacterShifts.ContainsKey(badCharacter)) { // In case the bad character does exist in the pattern // We find the right most occurence of it and align them badCharacterShift = badCharacterShifts[badCharacter][patternIndex]; } else { // Otherwise, the bad character is not seen, we can shift the pattern // so that it is after the bad character badCharacterShift = patternIndex + 1; } } int goodSuffixShift = 0; if (goodSuffixShifts[matched] == 0) { // Ideally we would like to start compare the with the pattern shifted by the pattern length, for example, we can have: // // text : abceabcd // pattern before shift : abcd // pattern after shift : abcd // goodSuffixShift = pattern.Length; } else { // But it isn't always possible, in case a suffix of the pattern repeats within itself, for example, we can have: // // text : aaaaaaapqbbbbbbbbbbbb // pattern before shift : pqaxpqxpq // pattern after shift : pqaxpqxpq // // In the case above, we have determined that we have 2 matching characters, how do we determine that we should shift by 7 characters? // The key idea is that we know not just we have 2 matching character, we also know the third character doesn't match, // this leads us to the notion of maximal suffix. // // A substring of the pattern is a maximal suffix if it matches a proper suffix of the pattern and either it can't extend the the left or // if it extended to the left, it is no longer matches a suffix pattern. // // In the example above, we have two maximal suffixes: // ** // *** // pqaxpqxpq // // After the first match, we know 2 characters matches, therefore we would shift the pattern trying to align the length 2 maximal suffix // to the matched characters, we get the 7 characters shift as expected. // // The key question would be, why is it correct? // If we had a length 1 maximal suffix, aligning that one is not going to work, as we will fail at the second character. // If we had a length 3 maximal suffix, aligning that one is not going to work either, as we will fail at the third character, // as we knew the third character of the text doesn't match with the pattern, but the length 3 maximal suffix does // // There is just one last twist, if we had more than one length 2 maximal suffix, we need to align it to the rightmost one to make sure // we don't skip potential hits // // Now go read the ComputeShiftTable() to see how the maximal suffixes are found and the shift table constructed // goodSuffixShift = goodSuffixShifts[matched]; } if (badCharacterShift &gt; goodSuffixShift) { // In case we have a bad character shift, we know nothing about what will match // after the shift (except, of course, the only character we are aligning to) // so we switch the goodSuffixCheck off goodSuffixCheck = -1; goodSuffixSkip = 0; i += badCharacterShift; } else { // In case we have a good suffix shift, we know the shifted characters are unknown // so they must be checked goodSuffixCheck = goodSuffixShift; // After going through the shifted characters, we know we reach a point where the string // aligns if (matched == pattern.Length) { // In case the whole pattern is matched, we know the full prefix matches goodSuffixSkip = matched - goodSuffixShift; } else { // Otherwise, we know the number of matched character in the suffix goodSuffixSkip = matched; } i += goodSuffixShift; } } } private static Dictionary&lt;char, int[]&gt; BuildBadCharacterShifts(string pattern) { Dictionary&lt;char, int[]&gt; badCharacterShifts = new Dictionary&lt;char, int[]&gt;(); for (int i = 0; i &lt; pattern.Length; i++) { char c = pattern[i]; int[] shift; if (!badCharacterShifts.TryGetValue(c, out shift)) { // A new array is by default zero filled shift = new int[pattern.Length]; badCharacterShifts.Add(c, shift); } // Therefore, we have a 1 in the array at the corresponding index if the // character appears, and 0 otherwise shift[i] = 1; } foreach (int[] shift in badCharacterShifts.Values) { // A placeholder value to indicate the array is never shifted int lastShift = -1; for (int i = 0; i &lt; shift.Length; i++) { if (shift[i] == 0) { // At this point we are at a mismatch if (lastShift == -1) { // There is no occurrence of the character before this position // Therefore we can safely shift the pattern past the character shift[i] = i + 1; } else { // Last time we shifted lastShift characters and then it aligns // Therefore we can shift one more character now to align shift[i] = ++lastShift; } } else { // Here we have as hit, the driver should not access this value shift[i] = -1; // And we need to shift no character to achieve alignment now lastShift = 0; } } } return badCharacterShifts; } private static int[] BuildGoodSuffixShifts(string s) { int length = s.Length; int[] maximalSuffixLengths = new int[length - 1]; int left = -1; int right = 0; for (int i = s.Length - 2; i &gt;= 0; i--) { int currentLeft = i; int currentRight = i + 1; int prefixLeft = length - 1; if (left != -1) { // Here we have a maximal suffix, as always, we have: // s[left, right) = s[left + length - right, length) Debug.Assert(IsMaximalSuffix(s, left, right)); if (left &lt;= i &amp;&amp; i &lt; right) { // Now we know s[i] lies inside the leftmost maximal suffix // In particular, s[left, i + 1) = s[left + length - right, i + length - right + 1) // So we are interested to see the maximal suffix starting from i + length - right int knownRight = i + length - right + 1; // knownRight - 1 - i // = i + length - right + 1 - 1 - i // = length - right &gt; 0 // Therefore we know knownRight - 1 &gt; i - we are always accessing the array that must have been already populated Debug.Assert(knownRight - 1 &gt; i); int knownLength = maximalSuffixLengths[knownRight - 1]; int knownLeft = knownRight - knownLength; Debug.Assert(knownLeft &gt;= 0); // In terms of the variables, we have // s[knownLeft, knownRight) = s[knownLeft + length - knownRight, length) Debug.Assert(IsSuffix(s, knownLeft, knownRight)); // We wish to use the relation s[left, i + 1) = s[left + length - right, i + length - right + 1) // So we need to make sure s[knownLeft, knownRight) is substring of s[left + length - right, i + length - right + 1) if (knownLeft &lt; left + length - right) { knownLeft = left + length - right; } Debug.Assert(left + length - right &lt;= knownLeft &amp;&amp; knownLeft &lt; length); Debug.Assert(left + length - right &lt; knownRight &amp;&amp; knownRight &lt;= length); // Now we can shift them back, and this now we have this // s[knownLeft, knownRight = i + 1) = s[knownLeft + length - knownRight, length) knownLeft = knownLeft + right - length; knownRight = knownRight + right - length; Debug.Assert(knownRight == i + 1); Debug.Assert(IsSuffix(s, knownLeft, knownRight)); currentLeft = knownLeft - 1; prefixLeft = knownLeft + length - knownRight - 1; } } // Now, we extend the maximal suffix until we cannot // Note that in this loop, we are either exploring characters already discovered in a known maximal suffix // in which the loop should terminate right away because the maximal suffix terminated inside, or we are // discovering new characters. Therefore the total time spent on this loop should be proportional to the length of s while (currentLeft &gt;= 0 &amp;&amp; s[currentLeft] == s[prefixLeft]) { currentLeft--; prefixLeft--; } // We moved too much, adjust back currentLeft++; prefixLeft++; // Now we have found the maximal suffix Debug.Assert(IsMaximalSuffix(s, currentLeft, currentRight)); // Book keeping for the left most maximal suffix if (left == -1 || currentLeft &lt; left) { left = currentLeft; right = currentRight; } // And save the lengths maximalSuffixLengths[i] = currentRight - currentLeft; } // Make sure we have got it right in debug mode for (int i = 0; i &lt; s.Length - 1; i++) { Debug.Assert(IsMaximalSuffix(s, i + 1 - maximalSuffixLengths[i], i + 1)); } // Now we compute the shift table, the number of character matched could range from 0 to length int[] shifts = new int[length + 1]; // Starting from the back for (int i = length - 2; i &gt;= 0; i--) { int maximalSuffixLength = maximalSuffixLengths[i]; // Note that i + shift = length - 1, this is designed so that the ith character aligns with the last character. int shift = length - 1 - i; if (shifts[maximalSuffixLength] == 0) { shifts[maximalSuffixLength] = shift; } if (shifts[length] == 0 &amp;&amp; maximalSuffixLength == (i + 1)) { // // In case the full pattern is matched, we will never have a maximal suffix with length n (it has to be proper) // Therefore the rule above cannot handle that special case, and must be analyzed differently // // Suppose a full pattern is matched: // text : abcabcxxxxxxx // pattern : abcabc // // In this case we know we should shift by 3, because the prefix matches a suffix. We can see that for any // shift less than the pattern length, that has to be the case. // // We can detect the prefix matches a suffix case by checking the maximal suffix starts at 0. Note that // when a maximal suffix starts at 0 and ends at i, it has length (i + 1), that is what the condition is checking // // Again, if we have multiple ways such that prefix matches suffix, we pick the one with least shift to make sure // we capture all occurences, this could happen in this case: // // text : aaxaaxaa // pattern : aaxaa // // In this case we can only shift by 3, not 4. // shifts[length] = shift; } } return shifts; } private static string SubstringLeftRight(this string s, int left, int right) { if (left == s.Length) { Debug.Assert(right == s.Length); return ""; } else { Debug.Assert(left &gt;= 0); Debug.Assert(right &gt;= 0); Debug.Assert(right &lt;= s.Length); Debug.Assert(right &gt;= left); return s.Substring(left, right - left); } } private static bool IsSuffix(string s, int left, int right) { return s.SubstringLeftRight(left, right) == s.SubstringLeftRight(left + s.Length - right, s.Length); } private static bool IsMaximalSuffix(string s, int left, int right) { if (IsSuffix(s, left, right)) { if (left &gt; 0) { return !IsSuffix(s, left - 1, right); } else { return true; } } return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T18:46:15.103", "Id": "406935", "Score": "1", "body": "Please add the description of the task to your question." } ]
[ { "body": "<h3>Bugs</h3>\n\n<ul>\n<li><code>IndexOf(\"BC.xABC..ABC\", \"BC..ABC\")</code> does not find a match, because your good-suffix table logic does not calculate shifts for situations where a suffix of the match is a prefix of pattern.</li>\n<li><code>IndexOf(\"x.ABC..ABC\", \"..ABC\")</code> fails with an <code>IndexOutOfRangeException</code>. This is because you always apply the good-suffix skip logic (the Galil rule) after a good-suffix shift, even when the suffix did not occur elsewhere in the pattern.</li>\n</ul>\n\n<h3><code>IndexOf</code></h3>\n\n<ul>\n<li>Returning 0 if pattern is an empty string leads to inconsistent results: <code>IndexOf(text.Substring(1), \"\")</code> returns 0, so you'd expect the result of <code>IndexOf(text, \"\")</code> to include 1, but that's not the case. I would throw an exception instead.</li>\n<li><code>IndexOf</code> is public, but it doesn't check whether it's arguments are valid. I'd expect an <code>ArgumentNullException</code> if either <code>text</code> or <code>pattern</code> is null.</li>\n<li>I would rename this method to <code>IndexesOf</code>. It's more accurate, and it allows you to make it an extension method without name-clashes.</li>\n<li>The <code>if (goodSuffixCheck == 0)</code> check is only useful if the previous check succeeded, so this should be moved into the above <code>if</code> body. This happens inside a loop after all.</li>\n<li>The name <code>matched</code> sounds like a boolean - <code>matchLength</code> is a more descriptive name.</li>\n<li>In the bad-character shift lookup, use <code>TryGetValue</code> instead of <code>ContainsKey</code>, so you only need a single lookup.</li>\n<li>The comment <code>// In case the bad character does exist in the pattern // We find the right most occurence of it and align them</code> is not correct - you don't want the right-most occurrence, but the first occurrence to the left of the current position.</li>\n<li><code>if (goodSuffixShifts[matchLength] == 0) { goodSuffixShift = pattern.Length; }</code> - why not store the pattern length in this shift table during pre-processing?</li>\n<li>While it's useful to see a description of a complicated algorithm, inserting such large comments in-between the code makes it more difficult to get an overview of the code itself, because it's so fragmented. I would prefer fewer and much more succinct in-line comments, and - if necessary - a more extensive explanation elsewhere (such as at the top of the file).</li>\n</ul>\n\n<h3><code>BuildBadCharacterShifts</code></h3>\n\n<ul>\n<li>You can shorten <code>Dictionary&lt;char, int[]&gt; badCharacterShifts = new Dictionary&lt;char, int[]&gt;();</code> to <code>var badCharacterShifts = new Dictionary&lt;char, int[]&gt;();</code>.</li>\n<li><code>out</code> parameters can be declared in-line: <code>if (!badCharacterShifts.TryGetValue(c, out int[] shift))</code>.</li>\n<li>Comments like <code>// A new array is by default zero filled</code> are clutter, in my opinion. There are plenty of places to read up on C# if someone is not sufficiently familiar with the language. I guess it depends on the target audience though.</li>\n<li>Why not mark occurrences with <code>-1</code>? That saves a tiny bit of work further down. You may want to add an assertion in <code>IndexOf</code> to make sure that a <code>-1</code> shift is never used, just in case.</li>\n<li>The <code>foreach</code> loop can be simplified - the <code>lastShift == -1</code> edge-case can be taken care of by the general <code>shift[i] = ++lastShift</code> case, if you initialize <code>lastShift</code> to 0.</li>\n</ul>\n\n<h3><code>BuildGoodSuffixShifts</code></h3>\n\n<ul>\n<li>I'd rename <code>s</code> to <code>pattern</code>, for consistency's sake.</li>\n<li>Using both <code>length</code> and <code>s.Length</code> is inconsistent. Personally I'd stick to <code>s.Length</code>, so it's more obvious what length you're working with.</li>\n<li>This method is fairly long. A helper method for finding a maximal suffix for a certain end position would be useful - not only to make this method shorter, but properly named helper methods can also make the intention of the code more clear. This is actually a good place for a local function.</li>\n<li>Many comments here look very similar to the code, with a lot of <code>left + length - right</code> and similar expressions. That's like saying that <code>Frob(widget)</code> frobs the widget, without explaining what frobbing is or why the widget needs to be frobbed. It doesn't really make the code easier to understand.</li>\n<li>The <code>if (left != -1)</code> part is actually an optimization, but that's not clearly explained. When inside an already known maximal suffix, it's sometimes possible to skip a few comparisons, but neither the code nor the comments make that very clear (expressions like <code>i + length - right + 1</code> aren't as easy to understand as I'd like).</li>\n<li>Picking better initial values sometimes lets you simplify code. For example, initializing <code>left</code> to <code>s.Length</code> removes the need for that <code>left != -1</code> check.</li>\n</ul>\n\n<h3>Other methods</h3>\n\n<ul>\n<li>There's no need for that <code>if/else</code> check in <code>SubstringLeftRight</code> - the <code>else</code> body already takes care of the empty-string edge-case.</li>\n<li>I'd rename <code>left</code> and <code>right</code> to <code>startIndex</code> and <code>endIndex</code>, to be more consistent with <code>string.Substring</code>'s parameter names.</li>\n<li>The <code>right &gt;= 0</code> assert in <code>SubstringLeftRight</code>'s <code>else</code> body is superfluous.</li>\n<li><code>IsSuffix</code> can be simplified by using <code>string.EndsWith</code>. And with that, there's very little need left for <code>SubstringLeftRight</code>.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>I would add messages to those <code>Debug.Assert</code> calls, so you can immediately see which assertion failed.</li>\n<li>If you plan to use this code, then you may want to create a <code>SearchPattern</code> class that can store the shift tables for a pattern, so searching multiple texts with the same pattern will be faster because you don't need to repeat the pre-processing each time.</li>\n<li>Using LeetCode as a 'unit test repository' is a smart idea, but note that you're returning the index of all matches, while their tests are geared towards finding only the first match. That might explain why those tests didn't catch the above two bugs. What I did was a basic form of fuzz-testing: generate a few random patterns, randomly join them together (a few hundred times for the text, a few times for the pattern) and feed that into the algorithm, then repeat that a few thousand times. The next step would've been writing a simple verification method (using repeated <code>string.IndexOf</code> calls), but at that point I had already found 2 bugs so I decided that was enough.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T02:17:44.287", "Id": "210850", "ParentId": "210514", "Score": "3" } } ]
{ "AcceptedAnswerId": "210850", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T17:52:57.400", "Id": "210514", "Score": "2", "Tags": [ "c#", "strings", "programming-challenge" ], "Title": "LeetCode #28 - Boyer Moore string matching algorithm" }
210514
<p>This is a game for two users who roll 2 dice 5 times. If the total of dice is even the player gains 10 points; if it is odd, they lose 5.</p> <p>If there is a draw after five rounds then both users will have to roll one die to determine the winner.</p> <p>Some updates that I have done to this code include adding functions to it so that it reduces the size of the code, removing repeated code, acting upon the suggestions that were given to me on my old code, and trying to improve my DRY (don't repeat yourself) skills.</p> <p>I just want suggestions on how I could improve this updated code.</p> <pre><code>import time import sys import random import operator total_score2 = 0 total_score1 = 0 rounds = 0 playerOnePoints = 0 playerTwoPoints = 0 counter = 0 print("*****************Welcome To The DICE Game*******************") print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores") ens=input("") while ens not in ('e', 'n', 's'): # if anything else but these characters are entered it will loop until it is correct print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores") ens = input() if ens == "s": s = open("scores.txt","r") file_content = s.read().splitlines() users_points = {i.split()[0]: int(i.split()[2]) for i in file_content} best_player = max(users_points.items(), key=operator.itemgetter(1))[0] print("LeaderBoard: ") print("\n") print('player with maximum points is {}, this player has {} points'.format(best_player, users_points[best_player])) best_players = sorted(users_points, key=users_points.get, reverse=True) for bp in best_players: print('{} has {} points'.format(bp, users_points[bp])) # This prints all players scores print("\n") print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores") ens=input("") if ens == "n": file = open("accountfile.txt","r+") text = file.read().strip().split() check = True while check: username=input("Please enter appropiate username: ") #Takes input of a username from user if username == "": #if no value is entered for the username continue if username in text: #username in present in the text file print("Username is taken please try another one") else: #username is absent in the text file print("Username has been accepted") check = False check = True while check: password1=input("Please enter password: ") password2=input("Please re-enter password: ") if password1 == password2: if password2 in text: print("Password has been taken please try another one") else: print("Username and Password have sucessfully been made Thankyou") file.write("username: " + username + " " + "password: " + password2 + "\n") file.close() check = False else: print("passwords do not match please try again") file.close() def write1(): print("Player 1 ",username1," Wins!") file = open("scores.txt","a") file.write(username1 + " has " + str(total_score1) + " points" + "\n") file.close() sys.exit() def write2(): print("Player 2 ",username2," Wins!") file = open("scores.txt","a") file.write(username2 + " has " + str(total_score2) + " points" + "\n") file.close() sys.exit() def validation(): global counter print("Sorry, this username or password does not exist please try again") counter = counter + 1 if counter == 3: print("----------------------------------------------------") print("You have been locked out please restart to try again") sys.exit() def game(): global total_score1 global total_score2 global rounds global number global number2 global playerOnePoints global playerTwoPoints total_score2 = total_score2 + playerTwoPoints total_score1 = total_score1 + playerOnePoints rounds = rounds + 1 number = random.randint(1,6) number2 = random.randint(1,6) playerOnePoints = number + number2 print("-------------------------------------------") print("Round",rounds) print("-------------------------------------------") print("Player 1's turn Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("Player 1's first roll is", number) print("Player 1's second roll Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("player 1's second roll is", number2) if playerOnePoints % 2 == 0: playerOnePoints = playerOnePoints + 10 print("Player 1's total is even so + 10 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") else: playerOnePoints = playerOnePoints - 5 print("player 1's total is odd so -5 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") number = random.randint(1,6) number2 = random.randint(1,6) playerTwoPoints = number + number2 print("-------------------------------------------") print("Player 2's turn Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("Player 2's first roll is", number) print("Player 2's second roll Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("player 2's second roll is", number2) if playerTwoPoints % 2 == 0: playerTwoPoints = playerTwoPoints + 10 print("Player 2's total is even so + 10 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") else: playerTwoPoints = playerTwoPoints - 5 print("player 2's total is odd so -5 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") if ens == "e": counter = 0 check_failed = True while check_failed: print("Could player 1 enter their username and password") username1=input("Please enter your username ") password=input("Please enter your password ") with open("accountfile.txt","r") as username_finder: for line in username_finder: if ("username: " + username1 + " password: " + password) == line.strip(): print("you are logged in") check_failed = False check_failed = True while check_failed: print("Could player 2 enter their username and password") username2=input("Please enter your username ") password=input("Please enter your password ") with open("accountfile.txt","r") as username_finder: for line in username_finder: if ("username: " + username2 + " password: " + password) == line.strip(): print("you are logged in") check_failed = False time.sleep(1) print("Welcome to the dice game") time.sleep(1) while rounds &lt; 5: game() print("-------------------------------------------") print("Total score for player 1 is", total_score1) print("-------------------------------------------") print("Total score for player 2 is", total_score2) print("-------------------------------------------") if total_score1 &gt; total_score2: write1() if total_score2 &gt; total_score1: write2() if total_score1 == total_score2: print("Its a draw!") game() if total_score1 &gt; total_score2: write1() if total_score1 &lt; total_score2: write2() else: validation() else: validation() </code></pre> <p><a href="https://codereview.stackexchange.com/questions/208342/2-player-dice-game-where-even-total-gains-points-and-odd-total-loses-points-nea">This is the link to my old code</a></p>
[]
[ { "body": "<p>Try to avoid using so many globals. Your code would be better-structured if you made a <code>Game</code> class and captured most or all of that state as class member variables.</p>\n\n<p>You made the same spelling mistake here as you did in your previous question. \"exsiting\" is spelled \"existing\".</p>\n\n<p>In this code:</p>\n\n<pre><code>s = open(\"scores.txt\",\"r\")\n</code></pre>\n\n<p>You open, but fail to close, <code>s</code>. Convert this to a <code>with</code> statement.</p>\n\n<p>This:</p>\n\n<pre><code>users_points = {i.split()[0]: int(i.split()[2]) for i in file_content}\n</code></pre>\n\n<p>relies on this format:</p>\n\n<pre><code>file.write(username1 + \" has \" + str(total_score1) + \" points\" + \"\\n\")\n</code></pre>\n\n<p>As such, you can convert your <code>users_points</code> initialization to:</p>\n\n<pre><code>users_points = {}\nfor line in file_content:\n user, points = re.match('r(\\w+) has (\\d+) points').groups()\n users_points[user] = int(points)\n</code></pre>\n\n<p>However, that's not ideal. If <code>scores.txt</code> doesn't need to be human-readable, then you should store it in a different format - probably JSON. That way, your loading and store can be made much more simple.</p>\n\n<p>Move your global code to a <code>main</code> method.</p>\n\n<p>As I recommended in the previous incarnation of this question, and will recommend again, stop issuing blank <code>input</code> calls. This:</p>\n\n<pre><code>print(\"Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores\")\nens=input(\"\")\n</code></pre>\n\n<p>needs to be</p>\n\n<pre><code>ens = input(\"Please enter 'n' if you are a new user, 'e' if you are an existing user, or 's' to display scores: \")\n</code></pre>\n\n<p>Try to convert some of your concatenated strings into f-strings:</p>\n\n<pre><code>username1 + \" has \" + str(total_score1) + \" points\" + \"\\n\")\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>f'{username1} has {total_score1} points\\n'\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>counter = counter + 1\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>counter += 1\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>check_failed = False\ncheck_failed = True\n</code></pre>\n\n<p>is quite strange; the first assignment will be overwritten so you should probably just delete it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T21:33:42.637", "Id": "210525", "ParentId": "210517", "Score": "4" } }, { "body": "<p>You should make better use of functions to reduce duplication.</p>\n\n<p>Here:</p>\n\n<pre><code>def write1():\n print(\"Player 1 \",username1,\" Wins!\")\n file = open(\"scores.txt\",\"a\")\n file.write(username1 + \" has \" + str(total_score1) + \" points\" + \"\\n\")\n file.close()\n sys.exit()\n\ndef write2():\n print(\"Player 2 \",username2,\" Wins!\")\n file = open(\"scores.txt\",\"a\")\n file.write(username2 + \" has \" + str(total_score2) + \" points\" + \"\\n\")\n file.close()\n sys.exit()\n</code></pre>\n\n<p>Note how 99% of those functions are identical. The only difference is the usernames and scores. Add those as parameters to the function and pass the data in as arguments. This will make even more sense once you get rid of global variables as the other answer suggested:</p>\n\n<pre><code>def write_score(username, score):\n print(username,\" wins!\") # Got rid of the \"Player #\" part for simplicity\n file = open(\"scores.txt\",\"a\")\n file.write(username + \" has \" + str(score) + \" points\" + \"\\n\")\n file.close()\n\n # This arguably shouldn't be here.\n # Do you really want it to be necessary to close the program after writing?\n sys.exit()\n</code></pre>\n\n<p>Then change the calling code to something like:</p>\n\n<pre><code>if total_score1 &gt; total_score2:\n write_score(total_score1, username1)\n\nelif total_score2 &gt; total_score1:\n write_score(total_score2, username2)\n</code></pre>\n\n<p>You don't gain as much with functions if you're just moving two nearly identical chunks of code into two separate, nearly identical functions.</p>\n\n<p>If code looks almost the same, here's a simple way to turn it into a common function: Look at the pieces of code, and determine what is the same, and what is different. Make the different parts parameters of the function and pass that data in, and make the identical parts the body of the function. You can see how I used that with the example above.</p>\n\n<p>This can be made much neater though if you tuck the name and score away into a Player object. That way you aren't needing to deal with those bits of data separately.</p>\n\n<hr>\n\n<p>Everything under <code>if ens == \"e\":</code> should be moved out into its own function. There's no reason to have that much dense code all lumped together. It makes your code much harder to read, and forces you to have a ridiculous amount of nesting/indentation. You should create a function that reads the account information from file, another function that takes that information and checks the supplied login credentials, a function that takes input from the user, and a main procedure function that encompasses the logic of the game.</p>\n\n<p>Splitting it up like that will not only reduces duplication (since then you can, for example, call the \"get user input\" function twice instead of copying and pasting nearly the same chunk of code), but it will make the program easier to test. To see if loading information works, you just need to feed data to the \"load\" function and see what it returns back. With how you have it setup now, you need to run the entire program just to see if a small part of it works.</p>\n\n<hr>\n\n<p>Another example of reducing duplication is creating a function to test if a username/password combo is correct. It would make much more sense to write something like:</p>\n\n<pre><code>def verify_login(username, password, login_data):\n for line in login_data:\n if (\"username: \" + username + \" password: \" + password) == line.strip():\n return True\n\n return False\n</code></pre>\n\n<p>And then call this function for each player in the main routine.</p>\n\n<pre><code>with open(\"accountfile.txt\",\"r\") as username_finder:\n username1 = input(...)\n password1 = input(...)\n\n if verify_login(username1, password1, username_finder):\n print(\"you are logged in\")\n\n username2 = input(...)\n password2 = input(...)\n\n if verify_login(username2, password2, username_finder):\n</code></pre>\n\n<p>Now, you can test this functionality without ever needing to load data from a file, or even run the program, and you don't need to deal with the whole <code>check_failed</code> mess.</p>\n\n<p>That part could be extracted out too so the user is asked to enter a username/password pair until it matches:</p>\n\n<pre><code>def ask_for_login(login_data):\n while True:\n username = input(...)\n password = input(...)\n\n if verify_login(username, password, login_data):\n # Return the verified username that the user entered\n return username\n\n else:\n validation()\n</code></pre>\n\n<p>Then use it as:</p>\n\n<pre><code>with open(\"accountfile.txt\",\"r\") as username_finder:\n username1 = ask_for_login(username_finder)\n username2 = ask_for_login(username_finder)\n\n # Once you get rid of the globals, you'd pass \"username1\" and\n # \"username2\" as arguments to \"game\"\n game()\n</code></pre>\n\n<p>Notice how much nesting this gets rid of.</p>\n\n<hr>\n\n<p>Practice looking at similar looking code and thinking about how it could be made into a function. This entire piece of code could be reduced by probably half once all the duplication is removed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T12:56:06.957", "Id": "407088", "Score": "0", "body": "Thanks for your help also I have a question, for the user to roll the dice they have to type `roll` and then it displayes what the user rolled but if the user types in anything else but `roll` it doesn't display what the user rolled. Do you think you could help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:17:56.493", "Id": "407090", "Score": "0", "body": "Also I can't use the function for verfiying the username/password because in my code it sayes:`username1=input(\"Please enter your username \")\n password=input(\"Please enter your password \")` and it is the same thing for player 2 but it is :`username2=input(\"Please enter username\" )` so both usernames are different so how am I suppose to use the function you mentioned above for two different users" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:32:56.237", "Id": "407093", "Score": "1", "body": "@colkat406 For the second problem, you return the username and password from the function, you don't assign in the function. Dealing with globals makes everything more difficult in the long term. The first change you should make is to do as the other answer suggested and get rid of all the global variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:33:37.547", "Id": "407094", "Score": "0", "body": "@colkat406 For the first problem, let me wake up a bit more, and I'll look it over." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:00:44.217", "Id": "407101", "Score": "0", "body": "@colkat406 Regarding the first question, what you want is good input validation that only accepts defined inputs, and prompts the user for another input when an undefined input is given. [This SO answer](https://stackoverflow.com/a/23294659/8117067) is a good primer on the topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:48:47.537", "Id": "407199", "Score": "0", "body": "@Carcigenicate Im not too sure what you mean in your second answer about the function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:53:17.113", "Id": "407200", "Score": "0", "body": "@colkat406 Which part?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:56:02.960", "Id": "407202", "Score": "0", "body": "@Carcigenicate The part when you said \"you return the username and password from the function, you don't assign in the function\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:02:39.350", "Id": "407214", "Score": "0", "body": "@colkat406 I'll elaborate on that when I get home (I'm at work). Basically, you should return data from functions and avoid using globals whenever possible. I'll show you how you can do that when I get home." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:43:12.957", "Id": "407232", "Score": "0", "body": "@Carcigenicate ok then I hope you can help me asap" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T23:56:23.183", "Id": "407259", "Score": "0", "body": "@colkat406 See my edit near the bottom regarding `verify_login` and `ask_for_login`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:20:57.163", "Id": "407379", "Score": "0", "body": "@Carcigenicate The format for the account file is this: `username: bob password: b123\nusername: jason password: j123\n` If I enter the first bob's details first then jason's it works but when i do it the other way around it sayes username or password doesn't exists for some reason and I get this problem for the `ask _for_ login part`, could you help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:41:38.530", "Id": "407383", "Score": "0", "body": "@colkat406 Debugging here isn't really appropriate. I just did up a quick reduced example on the interpreter on my phone though, and it worked. Your save format may have a stray space somewhere, or you accidentally typed an extra space when entering, or you used a capital or something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T11:32:07.443", "Id": "407500", "Score": "0", "body": "@Carcigenicate I fixed that problem now thanks. I have another question though concerning the dice game, say that the user rolls 1 and 2 which add up to 3 which is an odd number the game will -5 from the 3 which makes the total -2 but I don't want it to go into minus, I want it so that they get 0 points instead of minus points. could you help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:15:44.713", "Id": "407724", "Score": "0", "body": "@colkat406 This is beyond a code review. If you need help with broken code, you can post on Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:30:02.063", "Id": "407726", "Score": "0", "body": "ok then I will." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T22:21:23.747", "Id": "210574", "ParentId": "210517", "Score": "5" } } ]
{ "AcceptedAnswerId": "210574", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T19:53:35.167", "Id": "210517", "Score": "6", "Tags": [ "python", "python-3.x", "game", "homework", "dice" ], "Title": "Two-player dice game for NEA task computer science (Updated)" }
210517
<p>I need set of random unique Integer numbers for my unit test. I implemented this method, however I'm not sure if this is best way to implement this.</p> <pre><code>private Set&lt;Integer&gt; getRandomUniqueNumberSet(Integer min, Integer max) { Set&lt;Integer&gt; added = new LinkedHashSet&lt;Integer&gt;(); for(int i = min; i &lt;= max; i++) { Integer index = ThreadLocalRandom.current().nextInt(min, max + 1); Boolean loop = false; if(!added.add(index)) loop = true; while(loop) { index = ThreadLocalRandom.current().nextInt(min, max + 1); if(added.add(index)) loop = false; } } return added; } </code></pre> <p>Example:</p> <pre><code>for(Integer index : getRandomUniqueNumberSet(2, 15)) { System.out.println("Index: " + index); } </code></pre> <p>Results:</p> <pre><code>Index: 8 Index: 5 Index: 15 Index: 9 Index: 4 Index: 3 Index: 7 Index: 2 Index: 11 Index: 14 Index: 6 Index: 10 Index: 13 Index: 12 </code></pre>
[]
[ { "body": "<h3>Generating unique random numbers within a range</h3>\n\n<p>A good way to generate unique random numbers within a range is to create a list with the desired unique numbers, and then shuffle it.</p>\n\n<pre><code> private Set&lt;Integer&gt; getRandomUniqueNumberSet(int min, int max) {\n List&lt;Integer&gt; numbers = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());\n Collections.shuffle(numbers);\n return new LinkedHashSet&lt;&gt;(numbers);\n }\n</code></pre>\n\n<h3>Don't used boxed types when you don't need <code>null</code> values</h3>\n\n<p>This method takes <code>Integer</code> parameters, which may be <code>null</code>:</p>\n\n<blockquote>\n<pre><code>private Set&lt;Integer&gt; getRandomUniqueNumberSet(Integer min, Integer max)\n</code></pre>\n</blockquote>\n\n<p>But the implementation doesn't handle the case when these values are <code>null</code>.\nAnd it doesn't make sense to support such ranges.\nChange those types to primitive <code>int</code>.</p>\n\n<p>The same goes for the local variables <code>Integer index</code> and <code>Boolean loop</code>.</p>\n\n<h3>Why <code>ThreadLocalRandom</code>?</h3>\n\n<p>As per the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadLocalRandom.html\" rel=\"nofollow noreferrer\">javadoc</a>, <em>\"use of <code>ThreadLocalRandom</code> is particularly appropriate when multiple tasks use random numbers in parallel in thread pools\"</em>. I doubt that's necessary in your use case, in which case I suggest to use an instance of <code>Random</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T07:27:07.207", "Id": "406992", "Score": "1", "body": "Could you add an explanation for not using `ThreadLocalRandom` and `Math.random()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:22:16.560", "Id": "407014", "Score": "0", "body": "@200_success I was wrong, I remembered something different. I dropped that point now, thanks for calling it out." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T07:08:02.407", "Id": "210545", "ParentId": "210519", "Score": "3" } }, { "body": "<p>The code block</p>\n\n<pre><code>Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);\nBoolean loop = false; \nif(!added.add(index)) loop = true;\nwhile(loop)\n{\n index = ThreadLocalRandom.current().nextInt(min, max + 1);\n if(added.add(index)) loop = false;\n}\n</code></pre>\n\n<p>Contains several lines of duplicated code. This pattern can often be simplified by removing the code outside of the while block:</p>\n\n<pre><code>Boolean success = false; \nwhile (!success)\n{\n Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);\n if (added.add(index))\n success = true;\n}\n</code></pre>\n\n<p>or a do/while block, which is more idiomatic for code that needs to execute at least once:</p>\n\n<pre><code>Boolean success = false;\ndo\n{\n Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);\n success = added.add(index); // note: this is simpler than the if version\n}\nwhile (!success);\n</code></pre>\n\n<p>I'm not a huge fan of <code>while (true)</code>, but some people might prefer the simpler:</p>\n\n<pre><code>while (true)\n{\n Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);\n if (added.add(index))\n break;\n}\n</code></pre>\n\n<p>This is all if you want to simply improve the existing structure. janos is correct that if all you want is a shuffling of a range of numbers you should approach it from that direction. Your current solution can take an unbounded amount of time to run, if the random number generator is \"unlucky\". You are returning a <code>Set</code>, which generally doesn't have a predictable order. You happen to use an implementation that does preserve insert order, but callers of you code have now way of knowing that. I would return a data structure that implies ordering, like a <code>List</code>. Internally you used a <code>Set</code> to have it prevent duplicates, but if you shuffle that's not functionality you need.</p>\n\n<p>A final nit: <code>added</code> isn't a great name for the set that you are going to return. I often use <code>ret</code> to name the variable that will be the return value, though some might prefer a more descriptive name like <code>set</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T18:41:57.927", "Id": "210567", "ParentId": "210519", "Score": "2" } } ]
{ "AcceptedAnswerId": "210545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T20:15:50.860", "Id": "210519", "Score": "2", "Tags": [ "java", "random", "shuffle" ], "Title": "Return Set<Integer> with random unique Integer numbers between min and max range" }
210519
<p>I wanted to display a markdown document in WPF sensibly without relying on an HTML rendering system. I wrote a control based on the <code>RichTextBox</code>, and used Microsoft's markdown parser. What do you think?</p> <p>XAML:</p> <pre><code>&lt;RichTextBox x:Class="MarkdownViewer.MarkdownBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MarkdownViewer" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" x:Name="Content"&gt; &lt;/RichTextBox&gt; </code></pre> <p>C# backend for the XAML file:</p> <pre><code>public partial class MarkdownBox : RichTextBox { public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(MarkdownBox), new UIPropertyMetadata(default(string), PropertyChangedCallback)); private static void PropertyChangedCallback(DependencyObject source, DependencyPropertyChangedEventArgs args) { if (source is MarkdownBox control) { var newValue = (string)args.NewValue; switch (args.Property.Name) { case nameof(Text): control.Text = newValue; break; } } } public string Text { get =&gt; (string)GetValue(TextProperty); set { var old = GetValue(TextProperty); SetValue(TextProperty, value); OnPropertyChanged(new DependencyPropertyChangedEventArgs(TextProperty, old, value)); SetTextboxContent(); } } public MarkdownBox() { InitializeComponent(); } private void Hlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); e.Handled = true; } private void SetTextboxContent() { Content.Document.Blocks.Clear(); var doc = new MarkdownDocument(); doc.Parse(Text ?? string.Empty); Content.Document.Blocks.AddRange(GetBlocks(doc.Blocks)); } private IEnumerable&lt;Block&gt; GetBlocks(IList&lt;MarkdownBlock&gt; blocks) { foreach (var block in blocks) { switch (block) { case HeaderBlock header: yield return GetHeaderBlock(header); break; case ParagraphBlock paragraph: yield return GetParagraphBlock(paragraph); break; case ListBlock list: yield return GetListBlock(list); break; case CodeBlock code: yield return GetCodeBlock(code); break; case QuoteBlock quote: yield return GetQuoteBlock(quote); break; case HorizontalRuleBlock rule: yield return GetRuleBlock(rule); break; case TableBlock table: yield return GetTableBlock(table); break; default: throw new NotImplementedException(); } } } private Block GetHeaderBlock(HeaderBlock header) { var headerLevels = new Dictionary&lt;int, double&gt; { [1] = 28, [2] = 21, [3] = 16.3833, [4] = 14, [5] = 11.6167, [6] = 9.38333, }; var content = header.Inlines.Select(GetInline); var span = new Span(); span.Inlines.AddRange(content); var labelElement = new Label { Content = span, FontSize = headerLevels[header.HeaderLevel] }; var blockElement = new BlockUIContainer(labelElement); return blockElement; } private Block GetParagraphBlock(ParagraphBlock paragraph) { var paragraphElement = new Paragraph(); paragraphElement.Inlines.AddRange(paragraph.Inlines.Select(GetInline)); return paragraphElement; } private Block GetListBlock(ListBlock list) { var listElement = new List { MarkerStyle = list.Style == ListStyle.Bulleted ? TextMarkerStyle.Disc : TextMarkerStyle.Decimal }; foreach (var item in list.Items) { var listItemElement = new ListItem(); listItemElement.Blocks.AddRange(GetBlocks(item.Blocks)); listElement.ListItems.Add(listItemElement); } return listElement; } private Block GetCodeBlock(CodeBlock code) { var typeConverter = new HighlightingDefinitionTypeConverter(); var avalon = new TextEditor { Text = code.Text, SyntaxHighlighting = (IHighlightingDefinition)typeConverter.ConvertFrom("C#"), FontFamily = new FontFamily("Consolas"), FontSize = 12, Padding = new Thickness(10), BorderBrush = Brushes.LightGray, BorderThickness = new Thickness(1), HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, IsReadOnly = true, ShowLineNumbers = true, MaxHeight = 250 }; return new BlockUIContainer(avalon); } private Block GetQuoteBlock(QuoteBlock quote) { var sectionElement = new Section { Background = new SolidColorBrush(Color.FromRgb(0xFF, 0xF8, 0xDC)), BorderBrush = new SolidColorBrush(Color.FromRgb(0xff, 0xeb, 0x8e)), BorderThickness = new Thickness(2, 0, 0, 0), Padding = new Thickness(5) }; var quoteBlocks = GetBlocks(quote.Blocks).ToList(); for (var i = 0; i &lt; quoteBlocks.Count; i++) { var item = quoteBlocks[i]; item.Padding = new Thickness(5, 0, 5, 0); item.Margin = new Thickness(0); sectionElement.Blocks.Add(item); } return sectionElement; } private Block GetRuleBlock(HorizontalRuleBlock rule) { var line = new Line { Stretch = Stretch.Fill, Stroke = Brushes.DarkGray, X2 = 1 }; return new Paragraph(new InlineUIContainer(line)); } private Block GetTableBlock(TableBlock table) { var alignments = new Dictionary&lt;ColumnAlignment, TextAlignment&gt; { [ColumnAlignment.Center] = TextAlignment.Center, [ColumnAlignment.Left] = TextAlignment.Left, [ColumnAlignment.Right] = TextAlignment.Right, [ColumnAlignment.Unspecified] = TextAlignment.Justify }; var tableElement = new Table { BorderThickness = new Thickness(0, 0, 1, 1), BorderBrush = new SolidColorBrush(Color.FromRgb(0xdf, 0xe2, 0xe5)), CellSpacing = 0 }; var tableRowGroup = new TableRowGroup(); for (int rowIndex = 0; rowIndex &lt; table.Rows.Count; rowIndex++) { var row = table.Rows[rowIndex]; var tableRow = new TableRow(); if (rowIndex % 2 == 0 &amp;&amp; rowIndex != 0) { tableRow.Background = new SolidColorBrush(Color.FromRgb(0xf6, 0xf8, 0xfa)); } for (int cellIndex = 0; cellIndex &lt; row.Cells.Count; cellIndex++) { var cell = row.Cells[cellIndex]; var cellContent = new Paragraph(); cellContent.Inlines.AddRange(cell.Inlines.Select(GetInline)); var tableCell = new TableCell { TextAlignment = alignments[table.ColumnDefinitions[cellIndex].Alignment], BorderBrush = new SolidColorBrush(Color.FromRgb(0xdf, 0xe2, 0xe5)), BorderThickness = new Thickness(1, 1, 0, 0), Padding = new Thickness(13, 6, 13, 6) }; tableCell.Blocks.Add(cellContent); if (rowIndex == 0) { tableCell.FontWeight = FontWeights.Bold; } tableRow.Cells.Add(tableCell); } tableRowGroup.Rows.Add(tableRow); } tableElement.RowGroups.Add(tableRowGroup); return tableElement; } private Inline GetInline(MarkdownInline element) { switch (element) { case BoldTextInline bold: return GetBoldInline(bold); case TextRunInline text: return GetTextRunInline(text); case ItalicTextInline italic: return GetItalicInline(italic); case StrikethroughTextInline strikethrough: return GetStrikethroughInline(strikethrough); case CodeInline code: return GetCodeInline(code); case MarkdownLinkInline markdownLink: return GetMarkdownLinkInline(markdownLink); case HyperlinkInline hyperlink: return GetHyperlinkInline(hyperlink); case ImageInline image: return GetImageInline(image); case SubscriptTextInline subscript: return GetSubscriptInline(subscript); case SuperscriptTextInline superscript: return GetSuperscriptInline(superscript); default: throw new NotImplementedException(); } } private Inline GetBoldInline(BoldTextInline bold) { var boldElement = new Bold(); foreach (var inline in bold.Inlines) { boldElement.Inlines.Add(GetInline(inline)); } return boldElement; } private static Inline GetTextRunInline(TextRunInline text) { return new Run(text.ToString()); } private Inline GetItalicInline(ItalicTextInline italic) { var italicElement = new Italic(); foreach (var inline in italic.Inlines) { italicElement.Inlines.Add(GetInline(inline)); } return italicElement; } private Inline GetStrikethroughInline(StrikethroughTextInline strikethrough) { var strikethroughElement = new Span(); strikethroughElement.TextDecorations.Add(TextDecorations.Strikethrough); foreach (var inline in strikethrough.Inlines) { strikethroughElement.Inlines.Add(GetInline(inline)); } return strikethroughElement; } private static Inline GetCodeInline(CodeInline code) { return new Run(code.Text) { Background = new SolidColorBrush(Color.FromRgb(0xef, 0xf0, 0xf1)) }; } private Inline GetMarkdownLinkInline(MarkdownLinkInline markdownLink) { var markdownLinkElement = new Hyperlink(); markdownLinkElement.Inlines.AddRange(markdownLink.Inlines.Select(GetInline)); markdownLinkElement.NavigateUri = new Uri(markdownLink.Url); markdownLinkElement.ToolTip = markdownLink.Tooltip; markdownLinkElement.RequestNavigate += Hlink_RequestNavigate; return markdownLinkElement; } private Inline GetHyperlinkInline(HyperlinkInline hyperlink) { var hyperlinkElement = new Hyperlink(); hyperlinkElement.Inlines.Add(hyperlink.Text); hyperlinkElement.NavigateUri = new Uri(hyperlink.Url); hyperlinkElement.RequestNavigate += Hlink_RequestNavigate; return hyperlinkElement; } private static Inline GetImageInline(ImageInline image) { var uri = new Uri(image.RenderUrl); var bitmap = new BitmapImage(uri); var imageElement = new Image { Source = bitmap, Height = image.ImageHeight == 0 ? double.NaN : image.ImageHeight, Width = image.ImageWidth == 0 ? double.NaN : image.ImageWidth, ToolTip = image.Tooltip }; return new InlineUIContainer(imageElement); } private Inline GetSubscriptInline(SubscriptTextInline subscript) { var subscriptElement = new Span(); subscriptElement.Typography.Variants = FontVariants.Subscript; foreach (var inline in subscript.Inlines) { subscriptElement.Inlines.Add(GetInline(inline)); } return subscriptElement; } private Inline GetSuperscriptInline(SuperscriptTextInline superscript) { var superscriptElement = new Span(); superscriptElement.Typography.Variants = FontVariants.Superscript; foreach (var inline in superscript.Inlines) { superscriptElement.Inlines.Add(GetInline(inline)); } return superscriptElement; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T18:15:50.893", "Id": "407039", "Score": "0", "body": "I think everything below `GetBlocks` rendering each block could be extracted into another component and implemented nicely with the visitor-pattern which you virtually already did. I'm curious about the markdown parser by microsoft... may I please have a link? ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T18:33:29.440", "Id": "407040", "Score": "2", "body": "It's https://www.nuget.org/packages/Microsoft.Toolkit.Parsers/." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T19:21:36.647", "Id": "417976", "Score": "1", "body": "Love the idea of a rich-text editor for Markdown (being that there really aren't any I can find for WPF). What about making this a WPF Custom Control ( instead of a code-behind User Control). Then you can package it as a nuget package, and its re-themeable, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T20:47:11.140", "Id": "417986", "Score": "0", "body": "I did actually package it as a nuget package since I posted this! https://www.nuget.org/packages/MarkdownViewer/. Do note that there are some UI quirks in this release. Codeblocks don't scroll correctly, unfortunately. I'd had that working at one point (I have a GIF to prove it), but I made some tweaks and broke it before I committed, so I don't know how to fix it. I've not really been maintaining the project, but it's OSS (Unlicense) at GitHub: https://github.com/Hosch250/MarkdownViewer" } ]
[ { "body": "<blockquote>\n<pre><code>&lt;RichTextBox x:Class=\"MarkdownViewer.MarkdownBox\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local=\"clr-namespace:MarkdownViewer\"\n mc:Ignorable=\"d\" \n d:DesignHeight=\"450\" d:DesignWidth=\"800\"\n x:Name=\"Content\"&gt;\n&lt;/RichTextBox&gt;\n</code></pre>\n</blockquote>\n\n<p>Why? In the interests of KISS, why not delete this entire file, and remove <code>partial</code> and the constructor from the declaration of the class?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static void PropertyChangedCallback(DependencyObject source, DependencyPropertyChangedEventArgs args)\n {\n if (source is MarkdownBox control)\n {\n var newValue = (string)args.NewValue;\n switch (args.Property.Name)\n {\n case nameof(Text):\n control.Text = newValue;\n break;\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Either this should be deleted or it should be commented to explain why it does anything useful, because it seems to say</p>\n\n<pre><code>control.Text = control.Text\n</code></pre>\n\n<p>and be either a no-op or an infinite recursion.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> set\n {\n var old = GetValue(TextProperty);\n SetValue(TextProperty, value);\n OnPropertyChanged(new DependencyPropertyChangedEventArgs(TextProperty, old, value));\n\n SetTextboxContent();\n }\n</code></pre>\n</blockquote>\n\n<p>I think I see it now, and I think what this whole section should say is</p>\n\n<pre><code> public static readonly DependencyProperty TextProperty =\n DependencyProperty.Register(nameof(Text), typeof(string), typeof(MarkdownBox), new UIPropertyMetadata(default(string), TextPropertyChanged));\n\n private static void TextPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)\n {\n // Assert that (source is MarkdownBox) &amp;&amp; (args.Property.Name == nameof(Text)) if you want,\n // but IMO that's overkill. You've only registered the callback on one property.\n (source as MarkdownBox).SetTextboxContent();\n }\n\n public string Text\n {\n get =&gt; (string)GetValue(TextProperty);\n set =&gt; SetValue(TextProperty, value);\n }\n</code></pre>\n\n<p>And it seems to me that <code>SetTextboxContent</code> should be renamed <code>UpdateTextboxContent</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void Hlink_RequestNavigate(object sender, RequestNavigateEventArgs e)\n {\n Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));\n e.Handled = true;\n }\n</code></pre>\n</blockquote>\n\n<p>Since you're packaging this as a library, it should expose the event rather than handling it.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private IEnumerable&lt;Block&gt; GetBlocks(IList&lt;MarkdownBlock&gt; blocks)\n {\n foreach (var block in blocks)\n {\n switch (block)\n {\n case HeaderBlock header:\n yield return GetHeaderBlock(header);\n break;\n case ParagraphBlock paragraph:\n yield return GetParagraphBlock(paragraph);\n break;\n ...\n</code></pre>\n</blockquote>\n\n<p>Why <code>IList</code> instead of <code>IEnumerable</code>?</p>\n\n<p>Also, I would be tempted to pull out <code>GetBlock</code>, which can be rather more compact:</p>\n\n<pre><code> private Block GetBlock(MarkdownBlock block)\n {\n switch (block)\n {\n case HeaderBlock header:\n return GetHeaderBlock(header);\n case ParagraphBlock paragraph:\n return GetParagraphBlock(paragraph);\n ...\n</code></pre>\n\n<p>and reduce <code>GetBlocks</code> to</p>\n\n<pre><code> private IEnumerable&lt;Block&gt; GetBlocks(IEnumerable&lt;MarkdownBlock&gt; blocks) =&gt; blocks.Select(GetBlock);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private Block GetHeaderBlock(HeaderBlock header)\n {\n var headerLevels = new Dictionary&lt;int, double&gt;\n {\n [1] = 28,\n [2] = 21,\n [3] = 16.3833,\n [4] = 14,\n [5] = 11.6167,\n [6] = 9.38333,\n };\n\n var content = header.Inlines.Select(GetInline);\n var span = new Span();\n span.Inlines.AddRange(content);\n\n var labelElement = new Label\n {\n Content = span,\n FontSize = headerLevels[header.HeaderLevel]\n };\n var blockElement = new BlockUIContainer(labelElement);\n return blockElement;\n }\n</code></pre>\n</blockquote>\n\n<p>WPF, like HTML/CSS, allows separation of structure from style, but this actively works against that. At the very least the labels could use <code>Tag</code> so that I can write a style which uses triggers to override the hard-coded sizes, but since (again) this is published as a library I would look at defining separate subclasses for each of the header levels (or perhaps a single <code>Header : Paragraph</code> with a property <code>HeaderLevel</code> that can be used in a trigger) so that they can be styled directly. And the default values should be pulled out into <code>Themes/Generic.xaml</code>.</p>\n\n<p>Also, why <code>BlockUIContainer(Label)</code> instead of <code>Paragraph</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private Block GetCodeBlock(CodeBlock code)\n {\n var typeConverter = new HighlightingDefinitionTypeConverter();\n var avalon = new TextEditor\n {\n Text = code.Text,\n SyntaxHighlighting = (IHighlightingDefinition)typeConverter.ConvertFrom(\"C#\"),\n FontFamily = new FontFamily(\"Consolas\"),\n FontSize = 12,\n Padding = new Thickness(10),\n BorderBrush = Brushes.LightGray,\n BorderThickness = new Thickness(1),\n HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,\n VerticalScrollBarVisibility = ScrollBarVisibility.Auto,\n IsReadOnly = true,\n ShowLineNumbers = true,\n MaxHeight = 250\n };\n\n return new BlockUIContainer(avalon);\n }\n</code></pre>\n</blockquote>\n\n<p>Similar comments apply: the default style should be in XAML, and IMO a library shouldn't assume that code will be C#. Leave <code>SyntaxHighlighting</code> blank and document how to use highlighting for end users who want it.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private Inline GetInline(MarkdownInline element)\n</code></pre>\n</blockquote>\n\n<p>I would re-order the code a bit to put this next to <code>GetBlock</code> as \"high level\" methods, and probably use a <code>#region</code> for the lower level methods for blocks and another for the inlines.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static Inline GetCodeInline(CodeInline code)\n {\n return new Run(code.Text)\n {\n Background = new SolidColorBrush(Color.FromRgb(0xef, 0xf0, 0xf1))\n };\n }\n</code></pre>\n</blockquote>\n\n<p>I'm surprised that this doesn't use the same monospaced font as the code block.</p>\n\n<hr>\n\n<p>To finish, let me say that I love the concept. As it stands I wouldn't use the library, but if the issues I've raised (particularly about stylability) are addressed then it's possible I'll use it at some point in the future.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:49:14.170", "Id": "224957", "ParentId": "210520", "Score": "9" } } ]
{ "AcceptedAnswerId": "224957", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T20:25:01.107", "Id": "210520", "Score": "12", "Tags": [ "c#", "wpf", "markdown" ], "Title": "Markdown Display in WPF" }
210520
<p>This question is taken from <a href="https://leetcode.com/problems/3sum-closest/" rel="nofollow noreferrer">Leet code</a>. </p> <blockquote> <p>Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.</p> <p>Given array nums = [-1, 2, 1, -4], and target = 1.</p> <p>The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).</p> </blockquote> <p>I need feedback on my solution from programming interview perspective (where they rate you on quality of solution). </p> <p>My first solution is this (and preferred)</p> <pre><code>scala&gt; ((List(-1,2,1,-4).combinations(3).map(_.sum) map (sum =&gt; (sum,Math.abs(1-sum))) toList) sortWith(_._2 &lt; _._2)).head._1 res166: Int = 2 </code></pre> <p>But I expect interviewer might ask me to implement combinations (and use one provided by library) . So I implemented the same like this</p> <pre><code>def combinations(l: List[Int], c: Int): List[List[Int]] = { if (c == 1) { l map { r =&gt; List(r) } }else { l match { case Nil =&gt; List.empty case head::tail =&gt; (combinations(tail, c-1) map { r =&gt; head :: r }) ++ combinations(tail, c) } } } </code></pre> <p>I think this one is good enough to solve this problem (from point of view of interview).</p> <p>But after solving this I came across a <a href="https://stackoverflow.com/questions/2070359/finding-three-elements-in-an-array-whose-sum-is-closest-to-a-given-number">question</a> on SO where folks are trying to solve it without getting in O(n<sup>3</sup>) complexity. Kindly suggest me how you would solve it.</p> <p>Also please suggest me how I should handle this scenario where I think solution I gave is best for the problem.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T21:13:52.833", "Id": "210522", "Score": "1", "Tags": [ "interview-questions", "functional-programming", "comparative-review", "scala", "k-sum" ], "Title": "Closest 3Sum in Scala" }
210522
<p>I have a semisimple pure js countdown clock that I am having trouble converting the millisecond time correctly.</p> <p>Here is a working <a href="https://plnkr.co/edit/jRw2AeAaymkuAxT91VXp?p=preview" rel="nofollow noreferrer">Plunker</a> (besides the date counter)</p> <p>It Should only be 38 days instead of 184.</p> <pre><code>//// Should Countdown till feb, 4th 2019 ///// let cd = new Countdown({ cont: document.querySelector(".container"), endDate: 1549263600000, outputTranslation: { year: "Years", week: "Weeks", day: "Days", hour: "Hours", minute: "Minutes", second: "Seconds" }, endCallback: null, outputFormat: "day|hour|minute|second" }); </code></pre> <p>Thank's I appreciate the help!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T00:44:41.173", "Id": "406971", "Score": "2", "body": "You are getting close votes as you have ask \"How to fix bug\" This is code review we don't fix bugs, just review working code. You would have been better asking at stackOverflow. Or someone that knows how should have at least migrated this question to that site," } ]
[ { "body": "<p>The plunker has this code at the top of the <code>CountDown</code> function:</p>\n\n<pre><code>let options = { \n // ...\n },\n lastTick = null,\n intervalsBySize = [\"year\", \"week\", \"day\", \"hour\", \"minute\", \"second\"],\n TIMESTAMP_SECOND = 200,\n TIMESTAMP_MINUTE = 60 * TIMESTAMP_SECOND,\n TIMESTAMP_HOUR = 60 * TIMESTAMP_MINUTE,\n TIMESTAMP_DAY = 24 * TIMESTAMP_HOUR,\n TIMESTAMP_WEEK = 7 * TIMESTAMP_DAY,\n TIMESTAMP_YEAR = 365 * TIMESTAMP_DAY,\n elementClassPrefix = \"countDown_\",\n interval = null,\n digitConts = {};\n</code></pre>\n\n<p>... but that states that there are 200 milliseconds in a second. Obviously there are 1000 of them. So the line in question should be:</p>\n\n<pre><code>TIMESTAMP_SECOND = 1000,\n</code></pre>\n\n<p>This solves the issue. However, your <code>setInterval</code> also uses this variable for the length of the interval, and it might make sense to have more than one tick per second. So for that interval you should probably use a new variable that would indeed have the value 200.</p>\n\n<p>Nice work though on the CSS side!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T23:18:56.627", "Id": "406964", "Score": "0", "body": "Thanks this fixed my problem, I did not downvote it I don't know why we got downvoted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T23:20:14.710", "Id": "406965", "Score": "0", "body": "You're welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:29:24.827", "Id": "406974", "Score": "2", "body": "Broken code is offtopic here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T22:50:27.330", "Id": "210528", "ParentId": "210526", "Score": "0" } } ]
{ "AcceptedAnswerId": "210528", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T21:56:19.437", "Id": "210526", "Score": "0", "Tags": [ "javascript", "datetime" ], "Title": "Pure JS countdown clock not converting millisecond time correctly" }
210526
<p>Inspired by <a href="https://www.codewars.com/kata/string-%3E-x-iterations-%3E-string" rel="nofollow noreferrer">CodeWars</a></p> <blockquote> <p>We have a string <code>s</code> </p> <p>Let's say you start with this: "String"<br> The first thing you do is reverse it: "gnirtS"<br> Then you will take the string from the 1st position and reverse it again: "gStrin"<br> Then you will take the string from the 2nd position and reverse it again: "gSnirt"<br> Then you will take the string from the 3rd position and reverse it again: "gSntri" </p> <p>Continue this pattern until you have done every single position, and then you will return the string you have created. For this particular string, you would return: "gSntir"</p> <p>The Task:<br> In this kata, we also have a number <code>x</code><br> take the above reversal function, and apply it to the string <code>x</code> times.<br> Return the result of the string after applying the reversal function to it <code>x</code> times.</p> <p>Note:<br> String lengths may exceed 2 million and <code>x</code> may exceed a billion. Be ready to optimize.</p> </blockquote> <p>My solution works but times out and I am having trouble optimizing much further. The code contains a lot of useful comments but here is a summary of what I have attempted to do.</p> <p><strong>Cycle Length Calculation</strong><br> Because the above algorithm generates cycles, we can calculate a strings cycle length and perform <code>x % cycleLength</code> to determine exactly how many iterations we must perform to get our end result, instead of having to calculate all the duplicate cycles. More on cycle lengths can be found <a href="https://oeis.org/A216066" rel="nofollow noreferrer">here</a> and <a href="https://oeis.org/A003558" rel="nofollow noreferrer">here</a>.</p> <p>This method is better than nothing but can still get quite demanding on high cycle lengths. Potentially there is a better way of calculating the cycle length without so many iterations?</p> <pre><code>public final class XIterations { public static String xReverse(String s, long x) { // Using the cycle length and modular arithmetic, // We can find the exact number of reverse operations we will need to perform. // This way we will only perform operations we need to complete. long iterationsRequired = x % calculateCycleLength(s.length()); // TODO: There may exist an algorithm that allows a linear transformation given x while (iterationsRequired &gt; 0) { s = reverse(s); iterationsRequired--; } return s; } // The xReverse algorithm produces cycles and therefore duplicates. // This helper method determines the length of the cycle using the number of characters a string contains. // More detail on the algorithm can be found at: // https://oeis.org/A003558 // https://oeis.org/A216066 // TODO: There may exist an algorithm that requires less iterations to find the cycle length private static int calculateCycleLength(int n) { // Cache these so we only calculate them once. final int a = 2 * n + 1; final int b = 2 * n; int cycleLength = 1; while (true) { double c = Math.pow(2, cycleLength); if (c % a == 1 || c % a == b) { return cycleLength; } cycleLength++; } } public static String reverse(String s) { StringBuilder sb = new StringBuilder(); int front = 0; int back = s.length() - 1; // Does not account for odd length strings. Will not add the middle character. while (front &lt; back) { sb.append(s.charAt(back--)); sb.append(s.charAt(front++)); } // Account for odd length strings. Add the middle character that was never added by loop. if (front == back) { sb.append(s.charAt(front)); } return sb.toString(); } } </code></pre> <p>I am mostly interested in optimization tips but of course any feedback is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T09:39:30.103", "Id": "407282", "Score": "0", "body": "You don't need to actually run the algorithm, you can do this in one pass. Consider that each iteration you have one new character at the front that will never change position, and figure out how to get that value directly." } ]
[ { "body": "<h1>choice of language</h1>\n\n<p>Unfortunately Java is not the best choice for doing such tasks. Object creation, reference handling and alike simply takes time.</p>\n\n<p>So to speed up we need to throw away some of the benefits provides by the JVMs standard lib and switch to <em>procedural programming</em> on arrays.</p>\n\n<h1>optimizations</h1>\n\n<p>The calculation of the cycle length is a clever trick. But there must be an algorithm without looping which would speed up this calculation too. </p>\n\n<h1>implementation</h1>\n\n<p>As mentioned a fast solution must avoid object creation at all and should work on an <em>array of chars</em> rather than on <code>String</code>s. It should basically look like this:</p>\n\n<pre><code>public final class XIterations {\n public static String xReverse(String input, long iterations) {\n long iterationsRequired = iterations% calculateCycleLength(input.length());\n char[] chars = input.toCharArray();\n for(int i = 0 ; i &lt; iterationsRequired ; i++)\n chars = reverse(chars);\n return new String(chars);\n }\n}\n</code></pre>\n\n<p>In your code I cannot find how you handle the skipping of the start of the string. I would do this by using a <em>recursive call</em> like this:</p>\n\n<pre><code>private char[] reverse(char[] chars, int startIndex){\n if(chars.length == startIndex) {\n return chars;\n } else {\n // reverse chars in array starting at startIndex\n return reverse(chars, ++startIndex);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T11:11:37.240", "Id": "210550", "ParentId": "210529", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T23:09:13.910", "Id": "210529", "Score": "2", "Tags": [ "java", "performance", "strings", "programming-challenge" ], "Title": "String reversing x times" }
210529
<p>I have a working solution for this problem that was accepted in LeetCode:</p> <blockquote> <p>Given an array, rotate the array to the right by k steps, where k is non-negative."</p> </blockquote> <pre><code>function rotate(nums, k) { for (let i = 1; i &lt;= k; i += 1) { const poppedNum = nums.pop(); nums.unshift(poppedNum); } return nums; } // rotate([1, 2, 3, 4, 5, 6, 7], 3) -&gt; [5, 6, 7, 1, 2, 3, 4] </code></pre> <p>Questions:</p> <ul> <li><p>Would the time complexity be <span class="math-container">\$O(k)\$</span> and space complexity be <span class="math-container">\$O(1)\$</span>?</p></li> <li><p>Is there a better way to solve this? The question asked to rotate the elements in-place if possible, but I am not sure how to accomplish this at the moment.</p></li> </ul>
[]
[ { "body": "<h1>Review</h1>\n<p>Not bad, but there is room for a few improvements to avoid some possible problematic input arguments.</p>\n<h2>Style</h2>\n<p>Some points on your code.</p>\n<ul>\n<li>The names <code>nums</code> and <code>k</code> could be better, maybe <code>array</code> and <code>rotateBy</code></li>\n<li>Try to avoid one use variables unless it makes the lines using them to long. Thus you can pop and unshift in one line <code>nums.unshift(nums.pop());</code></li>\n<li>Idiomatic javascript uses zero based loop counters rather than starting at 1. Thus the loop would be <code>for (let i = 0; i &lt; k; i++) {</code></li>\n</ul>\n<h2>Complexity</h2>\n<p>Your complexity is <span class=\"math-container\">\\$O(n)\\$</span> and storage <span class=\"math-container\">\\$O(1)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of rotations, the range <span class=\"math-container\">\\$n&gt;0\\$</span></p>\n<p>However consider the next examples</p>\n<pre><code>rotate([1,2,3,4,5,6,7,8,9], 18); // Will rotate 18 times same as rotate 0\nrotate([1,2,3,4,5,6,7,8,9], 8); // Will rotate 8 times same as rotate left 1\nrotate([1], 8e9); // Will spend a lot of time not changing anything\n</code></pre>\n<p>Your function will do too much work if the rotations are outside the expected ranges, the rotation can be done in reverse in less steps, or rotating has no effect.</p>\n<p>You can limit the complexity to <span class=\"math-container\">\\$O(k)\\$</span> where <span class=\"math-container\">\\$0&lt;k&lt;=n/2\\$</span></p>\n<h2>Rewrite</h2>\n<p>This is a slight improvement on your function to ensure you don't rotate more than needed.</p>\n<pre><code>function rotate(array, rotateBy) {\n rotateBy %= array.length;\n if (rotateBy &lt; array.length - rotateBy) {\n while (rotateBy--) { array.unshift(array.pop()) }\n } else {\n rotateBy = array.length - rotateBy;\n while (rotateBy--) { array.push(array.shift()) }\n }\n return array;\n}\n</code></pre>\n<p><strong>Update</strong></p>\n<p>As vnp's <a href=\"https://codereview.stackexchange.com/a/210537/120556\">answer</a> points out the complexity of <code>Array.unshift</code> and <code>Array.shift</code> is not as simple as <span class=\"math-container\">\\$O(1)\\$</span> and will depend on the array type. We can assume the best case for this problem, sparse array (effectively a hash table) and thus will grow/shrink down at <span class=\"math-container\">\\$O(1)\\$</span></p>\n<p>In that case the function above has a mean complexity of <span class=\"math-container\">\\$O(log(n))\\$</span> of all possible values of <span class=\"math-container\">\\$k\\$</span></p>\n<p>Note that if the cost of grow/shrink operations is <span class=\"math-container\">\\$O(n)\\$</span> (dense array) this will add <span class=\"math-container\">\\$n\\$</span> operations for each <span class=\"math-container\">\\$k\\$</span> making the above <span class=\"math-container\">\\$O(kn)\\$</span> with <span class=\"math-container\">\\$0&lt;=k&lt;(n/2)\\$</span> Expressed in terms of <span class=\"math-container\">\\$n\\$</span> or <span class=\"math-container\">\\$k\\$</span> only it remains <span class=\"math-container\">\\$O(log(n))\\$</span> or <span class=\"math-container\">\\$O(k)\\$</span></p>\n<hr />\n<p>You could also use Array.splice</p>\n<pre><code> array.unshift(...array.splice(-rotateBy,rotateBy));\n</code></pre>\n<p>However under the hood the complexity would be a little greater <span class=\"math-container\">\\$O(2n)\\$</span> (which is still <span class=\"math-container\">\\$O(n)\\$</span>) as splice steps over each item to remove and add to a new array. Then <code>...</code> steps over them again to <code>unshift</code> each item to the array.</p>\n<p>The storage would also increase as the spliced array is held in memory until the code has finished unshifting them making storage <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p>If the array contained all the same values the rotation would have no effect thus all rotation could be done in <strong>O(1)</strong>. However there is no way to know this without checking each item in turn.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T00:33:18.553", "Id": "210532", "ParentId": "210530", "Score": "4" } }, { "body": "<p>The time complexity really depends on the <code>unshift</code> time complexity. ECMA does not specify it, but I would expect that it is not constant. I would not be surprised if it is actually linear in the size of the array. If so, the complexity of <code>rotate</code> would be <span class=\"math-container\">\\$O(nk)\\$</span>.</p>\n\n<p>In fact, I tested the performance of your code by timing your <code>rotate</code> by 1, for arrays of size from <code>100000</code> to <code>100000000</code>, doubling the size every time. The results (in milliseconds) are</p>\n\n<pre><code>1, 3, 8, 14, 29, 33, 69, 229, 447, 926\n</code></pre>\n\n<p>I did few runs, the exact numbers were different, but consistent. You can see that as size doubles the run time (at least) doubles as well.</p>\n\n<p>And again, it was rotation by 1. Rotation by <code>k</code> will take proportionally longer.</p>\n\n<hr>\n\n<p>There are few classic algorithms which perform the rotation in true <span class=\"math-container\">\\$O(n)\\$</span> complexity, that is their execution time does not depend on <code>k</code>. One is extremely simple to code, but takes effort to comprehend. In pseudocode:</p>\n\n<pre><code> reverse(0, k)\n reverse(k, n)\n reverse(0, n)\n</code></pre>\n\n<p>Notice that each element is moved twice. This is suboptimal. Another algorithm moves each element exactly once - right into the place where it belongs. I don't want to spoil the fun of discovering it. Try to figure it out (hint: it needs to compute <code>gcd(n, k)</code>).</p>\n\n<hr>\n\n<p>That said, the leetcode problem only asks to print the rotated array. I would seriously consider to not actually perform rotation, but</p>\n\n<pre><code> print values from n-k to n\n print values from 0 to n-k\n</code></pre>\n\n<p>It feels like cheating, but in fact it is valid, and sometimes very useful technique.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T08:34:39.850", "Id": "406994", "Score": "0", "body": "JS has two types of arrays, sparse and dense. There is no programmatic way to determine what an arrays type is. Sparse arrays use a cheap hash to locate items and thus would not suffer from the need to `memcpy` all items up/down one position when calling `Array.unshift` or `Array.shift` It is generally assumed that these operations are O(1). Array memory allocations are never single items but rather double array size, or wait and half. Using this scheme does make it possible to have an array that can grow in both directions at O(1). Whether this is in fact done I do not know." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:32:46.033", "Id": "210537", "ParentId": "210530", "Score": "3" } }, { "body": "<h3>Think twice before modifying function parameters</h3>\n\n<p>The posted code modifies the content of the input array <code>nums</code> and also returns it.\nWhen a function returns something,\nit can be confusing if it also modifies the input &mdash; a side effect.\nModifying the input and not returning anything (<code>void</code> in other programming languages) is not confusing.\nI think it's important to make a conscious of choice between two non-confusing behaviors: either modify the input and return nothing, or not modify the input and return the result as a new object.</p>\n\n<h3>Insert <code>k</code> items at the start of an array in one step instead of one item in <code>k</code> steps</h3>\n\n<p>In most programming languages, and I think in the context of this exercise, \"array\" usually means a contiguous area of memory. Inserting an element at the start is implemented by copying existing elements to shift them in memory by 1 position.</p>\n\n<p>For this reason, for a solution to the array rotation problem, I would avoid repeatedly inserting elements at the start of the array, to avoid repeated copying of elements. Even if arrays in JavaScript may behave differently, I would prefer a solution that doesn't raise questions about the potential underlying implementation of arrays, and looks objectively easier to accept.</p>\n\n<p>That is, I would prefer to store <code>k</code> values in temporary storage, shift the other elements by <code>k</code> steps (iterating over them only once), and then copy back the <code>k</code> elements to the correct positions.</p>\n\n<pre><code>function rotate(nums, k) {\n k %= nums.length;\n const rotated = new Array(nums.length);\n for (let i = 0; i &lt; k; i++) {\n rotated[i] = nums[nums.length - k + i];\n }\n for (let i = 0; i &lt; nums.length - k; i++) {\n rotated[i + k] = nums[i];\n }\n return rotated;\n}\n</code></pre>\n\n<p>This is <span class=\"math-container\">\\$O(n)\\$</span> in both time and space.\nThe extra space is needed to avoid modifying the input.\nIf we preferred modifying the input,\nthen only <span class=\"math-container\">\\$O(k)\\$</span> extra space would be needed,\nfor temporary storage of elements that would be overwritten.</p>\n\n<h3>Taking advantage of JavaScript's features</h3>\n\n<p>Slightly more expensive in terms of time and space,\nbut my preferred solution would make better use of the built-in functions on arrays in JavaScript than the version in the previous section,\nin much more compact code:</p>\n\n<pre><code>function rotate(nums, k) {\n k %= nums.length;\n const m = nums.length - k;\n return nums.slice(m).concat(nums.slice(0, m));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T12:01:01.250", "Id": "407087", "Score": "0", "body": "Returned reference allows chaining. Caller can shallow `rotate([...array], 1)` Shallow copy within function means all outside references need updating, the caller may not be able to. Compare `const rotate= (k, n) => (k %= n.length ? n.unshift(...n.splice(-k, k)) : 0, n)` to your last \"compact\" function, its worst is 50% faster than your best and its best is an order of mag (1700%+) faster than your best (not counting your funcs GC overhead). Google now rank pages in part on load speed, poor performing JS will cost rank points. The days of functional JS are finally over YA." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:08:50.020", "Id": "210558", "ParentId": "210530", "Score": "1" } } ]
{ "AcceptedAnswerId": "210532", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-28T23:30:05.923", "Id": "210530", "Score": "5", "Tags": [ "javascript", "algorithm", "interview-questions" ], "Title": "LeetCode 189 - Rotate Array" }
210530
<p>This is simple student information system project where you can do following things: </p> <ol> <li>Add Records</li> <li>List Records</li> <li>Modify Records</li> <li>Delete Records</li> </ol> <p>To store data a .txt file is used.</p> <p>I just want an honest critique of my code so I can improve.</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;string&gt; #include&lt;fstream&gt; using namespace std; void flowcontrol();//directs you based on what you are trying to do; int entrynumb();//counts the number astericks and stores them as a base for how many students they are for student number assignment; void addrecord();//adds new students to the database; void seerecord(string n);//lets you see the data on a student number; void modifyrecord(string n, char c);//deletes a desired record; int number = 0; string strnumber = to_string(number); struct student { string firstname, lastname, birthday; int age, grade; int number; void writeto(student a)//writes student values to a file for retrieval and modification; { ofstream datastore; datastore.open ("datastore.txt", ios_base::app); datastore &lt;&lt; '\n' &lt;&lt; "Number : " &lt;&lt; a.number; datastore &lt;&lt; '\n' &lt;&lt; "Name :" &lt;&lt; a.firstname &lt;&lt; ' ' &lt;&lt; a.lastname; datastore &lt;&lt; '\n' &lt;&lt; "DOB : " &lt;&lt; a.birthday; datastore &lt;&lt; '\n' &lt;&lt; "Age : " &lt;&lt; a.age; datastore &lt;&lt; '\n' &lt;&lt; "Grade : " &lt;&lt; a.grade; datastore &lt;&lt; '\n' &lt;&lt; "*"; datastore &lt;&lt; '\n' &lt;&lt; "----------------------------------------------"; datastore.close(); } }; int main() { flowcontrol(); } void spacer(int a)//adds a certain number of newline spaces; { cout &lt;&lt; string(a, '\n'); } void flowcontrol() { spacer(3); cout &lt;&lt; "Welcome to the student database version 1.101" &lt;&lt; '\n'; cout &lt;&lt; "&lt;-------------------------------------------&gt;" &lt;&lt; '\n'; cout &lt;&lt; " What would you like to do? " &lt;&lt; '\n'; cout &lt;&lt; " ADD | MODIFY | DELETE | SEE " &lt;&lt; '\n'; cout &lt;&lt; " a | m | d | s " &lt;&lt; '\n'; spacer(3); char ch; cin &gt;&gt; ch; spacer(22); switch(ch) { case 'a': addrecord(); break; case 's': { spacer(2); cout &lt;&lt; "Student ID number : " &lt;&lt; '\n'; string n; cin &gt;&gt; n; spacer(5); seerecord(n); break; } case 'd': { spacer(2); cout &lt;&lt; "Student ID number : " &lt;&lt; '\n'; string n; cin &gt;&gt; n; spacer(5); modifyrecord(n, 'd'); break; } case 'm': { spacer(2); cout &lt;&lt; "Student ID number : " &lt;&lt; '\n'; string n; cin &gt;&gt; n; spacer(5); modifyrecord(n, 'm'); break; } } } int entrynumb()//student number generator; { string line;//stores a line of the datastore file here for reference; vector&lt;string&gt; liner;//stores the amount of entries; ifstream myfile ("datastore.txt");//opens the datastore file; if (myfile.is_open()) { while (getline(myfile,line))//grabs the lines in datastore and does something; { if(line == "*")//does this if the condition is met; { liner.push_back("*");//pushes the asterick to the liner vector; } } myfile.close(); } return liner.size();//returns the number of astericks stored wich is directley correlated with the number of students; } void addrecord()//new student generator; { student strnumber;//initiates new student entry as a student object; strnumber.number = entrynumb();//grabs the proper student number; string strcontainer;//to store string responses such as firstname/lastname; int intcontainer;//to store int responses such as age, dob, etc; cout &lt;&lt; "First name? " &lt;&lt; '\n'; cin &gt;&gt; strcontainer; strnumber.firstname = strcontainer; spacer(1); cout &lt;&lt; "last name ? " &lt;&lt; '\n'; cin &gt;&gt; strcontainer; strnumber.lastname = strcontainer; spacer(1); cout &lt;&lt; "birthday ? " &lt;&lt; '\n'; cin &gt;&gt; strcontainer; strnumber.birthday = strcontainer; spacer(1); cout &lt;&lt; "age ? " &lt;&lt; '\n'; cin &gt;&gt; intcontainer; strnumber.age = intcontainer; spacer(1); cout &lt;&lt; "grade ? " &lt;&lt; '\n'; cin &gt;&gt; intcontainer; strnumber.grade = intcontainer; spacer(1); strnumber.writeto(strnumber);//calls to write the students data to datastore file; number++;//adds the number up by one per entry to keep track of number of students; main();//restarts the process; } void seerecord(string n)//takes the number provided and shows the student information; { string line; ifstream myfile ("datastore.txt");//opens the datastore file; if (myfile.is_open()) { while (getline(myfile,line))//grabs the lines in datastore and does something; { if(line == "Number : " + n)//loops through and prints every line related associated with the number; { cout &lt;&lt; " Student entry " &lt;&lt; '\n'; cout &lt;&lt; "&lt;-------------------------------------------&gt;" &lt;&lt; '\n'; cout &lt;&lt; '\n' &lt;&lt; line &lt;&lt; '\n'; for(int i = 0; i &lt; 5; i++ ) { getline(myfile, line); cout &lt;&lt; line &lt;&lt; '\n'; } cout &lt;&lt; "&lt;-------------------------------------------&gt;"; } } myfile.close(); } flowcontrol(); } void modifyrecord (string n, char c)//delete//modify a desired record; { vector&lt;string&gt; datahold;//holds all the entries kept unchanged; ifstream myfile ("datastore.txt");//opens the file; string line;//for reference to each line; if (myfile.is_open()) { while (getline(myfile, line)) { if(line == "Number : " + n)//if the number that is to be deleted is found it's associated entries wont be stored; { switch(c)//checks to see if your deleting or modifying a student entry; { case 'd'://delete; { for(int i = 0; i &lt; 6; i++) { getline(myfile, line); cout &lt;&lt; "DELETING: " &lt;&lt; line &lt;&lt; '\n'; } flowcontrol(); break; } case 'm'://edit; { string entries[4] = {"Name : ", "DOB : ", "Age : ", "Grade : "}; datahold.push_back(line); for(int j = 0; j &lt; 4; j++)//loops through and edits each entry; { string strcontainer; getline(myfile, line); cout &lt;&lt; "Currently: " &lt;&lt; line &lt;&lt; '\n' &lt;&lt; "Edit -&gt;"; cin &gt;&gt; strcontainer; datahold.push_back(entries[j] + strcontainer); cout &lt;&lt; "----------------------------------------&gt;" &lt;&lt; '\n'; } flowcontrol(); break; } } } else { datahold.push_back(line);//pushes entries that won't be edited or deleted; } } myfile.close(); } ofstream myfilenew; myfilenew.open ("datastore.txt"); for(unsigned int i = 0; i &lt; datahold.size(); i++)//iterates through all the kept entries and rewrites them to the file; { myfilenew &lt;&lt; datahold[i] &lt;&lt; '\n'; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:27:18.093", "Id": "406973", "Score": "0", "body": "Is there a particular aspect that you are seeking refinement with? Improved performance? Brevity? Etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:31:03.517", "Id": "406975", "Score": "0", "body": "Nothing in particular. I've never had any of my code reviewed, so I just wanted some feedback on anything that I should improve on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:33:46.263", "Id": "406978", "Score": "0", "body": "It is important that you clarify in your question/title exactly how you would like your code to be reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T02:42:25.470", "Id": "406979", "Score": "0", "body": "Okay that makes sense. I was under the impression that everything from the logic of it to the design structure would be critiqued automatically. Moving forward Ill clarify exactly what I want critiqued." } ]
[ { "body": "<p>These comments:</p>\n\n<pre><code>//directs you based on what you are trying to do;\n</code></pre>\n\n<p>don't need to end in semicolons. You're speaking English rather than C++ inside of them.</p>\n\n<blockquote>\n <p>astericks</p>\n</blockquote>\n\n<p>is spelled asterisks.</p>\n\n<p>This code:</p>\n\n<pre><code>int number = 0;\nstring strnumber = to_string(number);\n</code></pre>\n\n<p>seems out-of-place. If it's just test code, delete it.</p>\n\n<pre><code>struct student\n</code></pre>\n\n<p>First, you'll probably want to capitalize Student. Your <code>writeto</code> method should be declared as</p>\n\n<pre><code>void writeto(ostream &amp;datastore) const {\n</code></pre>\n\n<p>In particular, it shouldn't accept <code>a</code>, rather using <code>this</code> to identify the student; and it shouldn't open the file itself. It should be able to write to any stream (including <code>cout</code>).</p>\n\n<p>For code like this:</p>\n\n<pre><code>char ch; cin &gt;&gt; ch;\n</code></pre>\n\n<p>Try to avoid adding multiple statements on one line, for legibility's sake.</p>\n\n<p>A large section of your <code>addrecord</code> method should be moved to a method on <code>Student</code>. Specifically, this:</p>\n\n<pre><code>strnumber.number = entrynumb();//grabs the proper student number;\n\nstring strcontainer;//to store string responses such as firstname/lastname;\nint intcontainer;//to store int responses such as age, dob, etc;\n\ncout &lt;&lt; \"First name? \" &lt;&lt; '\\n';\ncin &gt;&gt; strcontainer; strnumber.firstname = strcontainer;\nspacer(1);\ncout &lt;&lt; \"last name ? \" &lt;&lt; '\\n';\ncin &gt;&gt; strcontainer; strnumber.lastname = strcontainer;\nspacer(1);\ncout &lt;&lt; \"birthday ? \" &lt;&lt; '\\n'; \ncin &gt;&gt; strcontainer; strnumber.birthday = strcontainer;\nspacer(1);\ncout &lt;&lt; \"age ? \" &lt;&lt; '\\n';\ncin &gt;&gt; intcontainer; strnumber.age = intcontainer;\nspacer(1);\ncout &lt;&lt; \"grade ? \" &lt;&lt; '\\n';\ncin &gt;&gt; intcontainer; strnumber.grade = intcontainer;\nspacer(1);\n</code></pre>\n\n<p>can be made into a method perhaps called <code>initFromPrompt</code> that initializes the current <code>Student</code> instance. Also, your \"container\" input pattern doesn't need to exist. For instance, for <code>grade</code>, simply</p>\n\n<pre><code>cin &gt;&gt; strnumber.grade;\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>main();//restarts the process;\n</code></pre>\n\n<p>is misdesigned. You definitely don't want to be calling <code>main</code> yourself, for many reasons - including recursion. If you want to \"restart the process\", you should make some kind of top-level loop.</p>\n\n<p>This:</p>\n\n<pre><code>ifstream myfile (\"datastore.txt\");//opens the file;\nif (myfile.is_open())\n</code></pre>\n\n<p>is somewhat of an anti-pattern. This kind of code is going to lead to silent errors. Instead, read about how to enable <code>std::ios::failbit</code> so that you get exceptions from bad stream calls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T19:51:20.773", "Id": "407046", "Score": "0", "body": "Can you give me an example of how I would call the write to method after your edit? I'm having a hard time understanding how it would work" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T23:40:07.503", "Id": "407057", "Score": "1", "body": "`strnumber.writeto(datastore)`, where datastore is your opened file and strnumber is your student instance" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T03:32:15.473", "Id": "210539", "ParentId": "210535", "Score": "4" } }, { "body": "<p>Here are some observations that may help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. </p>\n\n<h2>Return something useful from the subroutines</h2>\n\n<p>Almost every single one of the routines is declared as returning <code>void</code>. Something is wrong there. For example, if <code>addrecord</code> fails for some reason such as invalid input data, it would be nice if the function returned a value indicating this fact.</p>\n\n<h2>Eliminate global variables</h2>\n\n<p>My rewrite of this code uses no global variables, so clearly they are neither faster nor necessary. Eliminating them allows your code to be more readable and maintainable, both of which are important characteristics of well-written code. Global variables introduce messy linkages that are difficult to spot and error prone.</p>\n\n<h2>Use better naming</h2>\n\n<p>The name <code>flowcontrol</code> is not really helpful, since it does much more than simply reading -- all of the processing, including output, is done there. Names like <code>line</code> are fine in context, but <code>myfile</code> is not such a good name. Variable and function names should tell the reader <em>why</em> they exist, ideally without further comments necessary. So instead of <code>spacer()</code> I'd probably name it <code>print_empty_lines()</code> for example.</p>\n\n<h2>Use string concatenation</h2>\n\n<p>The menu includes these lines:</p>\n\n<pre><code>std::cout &lt;&lt; \"Welcome to the student database version 1.101\" &lt;&lt; '\\n';\nstd::cout &lt;&lt; \"&lt;-------------------------------------------&gt;\" &lt;&lt; '\\n';\nstd::cout &lt;&lt; \" What would you like to do? \" &lt;&lt; '\\n';\n</code></pre>\n\n<p>Each of those is a separate call to <code>operator&lt;&lt;</code> but they don't need to be. Another way to write that would be like this:</p>\n\n<pre><code>std::cout \n &lt;&lt; \"Welcome to the student database version 1.101\\n\"\n &lt;&lt; \"&lt;-------------------------------------------&gt;\\n\" \n &lt;&lt; \" What would you like to do? \\n\"\n // etc.\n</code></pre>\n\n<p>This reduces the entire menu to a single call to <code>operator&lt;&lt;</code> because consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler.</p>\n\n<h2>Don't duplicate important constants</h2>\n\n<p>The filename is hardcoded right now (see next suggestion), but worse than that, it's done in five completely indpendent places. Better would be to create a constant:</p>\n\n<pre><code>static const char *FILENAME = \"namelist.txt\";\n</code></pre>\n\n<h2>Consider the user</h2>\n\n<p>Instead of having a hardcoded filename, it might be nice to allow the user to control the name and location of the file. For this, it would make sense to use a command line argument and then pass the filename to the functions as needed.</p>\n\n<h2>Make better use of objects</h2>\n\n<p>The only member function of <code>student</code> is <code>writeto</code> which is not a good function name and may as well be a static function by the way it's written. Instead, I'd suggest something like this:</p>\n\n<pre><code>bool appendTo(const std::string &amp;filename) const {\n std::ofstream datastore{\"datastore.txt\", std::ios_base::app}; \n if (datastore) {\n datastore &lt;&lt; \n \"Number : \" &lt;&lt; number \n \"\\nName :\" &lt;&lt; firstname &lt;&lt; ' ' &lt;&lt; lastname\n \"\\nDOB : \" &lt;&lt; birthday\n \"\\nAge : \" &lt;&lt; age\n \"\\nGrade : \"&lt;&lt; grade\n \"\\n*\"\n \"\\n----------------------------------------------\\n\";\n }\n bool result{datastore};\n return result;\n}\n</code></pre>\n\n<p>Note that now it takes the filename as a parameter and return <code>true</code> if the write was successful. It is also <code>const</code> because it doesn't alter the underlying <code>student</code> data structure.</p>\n\n<h2>Understand the uniqueness of <code>main</code></h2>\n\n<p>The end of <code>flowcontrol()</code> is this:</p>\n\n<pre><code> main();//restarts the process;\n}\n</code></pre>\n\n<p>However, that's not legal C++. You can't take the address of <code>main</code> nor call it. It may seem to work with your compiler but it's explicitly <em>not</em> guaranteed by the standard and is <em>undefined behavior</em> meaning that the program might do anything and that it's not predictable. If you need to repeat something, use a loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T19:45:49.277", "Id": "407045", "Score": "0", "body": "Is there a rule of thumb for when I should use void ? Or is it just better design to return values for error handling" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T19:56:13.617", "Id": "407048", "Score": "1", "body": "Generally, if it doesn’t return something obvious like `entrynumb` and can’t fail (or throws an exception on failure) then `void` is ok. However if *all* of your functions return `void` it’s probably a sign that a little more thought about the design would be beneficial." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T20:00:35.513", "Id": "407049", "Score": "0", "body": "Thank you for your feedback I will keep that in mind during my edit/moving forward!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T03:42:33.340", "Id": "210540", "ParentId": "210535", "Score": "5" } } ]
{ "AcceptedAnswerId": "210540", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T01:44:05.840", "Id": "210535", "Score": "3", "Tags": [ "c++", "c++11" ], "Title": "Text based student information system" }
210535
<p>I am writing a gRPC Golang application and am looking for the best way to check if the deadline is exceeded or if the client cancelled the call.</p> <p>On the server side I created a channel called <code>done</code>. When <code>done</code> is called by either the go-routines the server returns with either the error or the success.</p> <p>In the code I have two go-routines. The first one runs the actual program and if successful calls the <code>done</code> channel without and error, the second waits for the <code>context.Done()</code> and if called calls the <code>done</code> channel with the error.</p> <p>I am wanting to know if there is a more efficient way to do this without two go-routines.</p> <p>I don't want to check periodically <code>ctx.Done()</code> or <code>ctx.Cancelled</code> because I feel that would be a waste of time but the method below would use more CPU resources.</p> <pre><code>package main import ( "context" "log" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" pb "mygit/controller/pb" ) // ping controller func (s *server) PingController(ctx context.Context, in *pb.PingControllerRequest) (*pb.PingControllerResponse, error) { done := make(chan error) // make a done bool var retOut pb.PingControllerResponse // run function in go routine and call done when finished without being cancelled go func(i *pb.PingControllerRequest) { log.Println(in.Client) // other business logic would go here retOut = pb.PingControllerResponse{Pong: "PONG"} done &lt;- nil }(in) // if context is done (due to error) return with done go func(c context.Context) { &lt;-c.Done() done &lt;- status.Error(codes.Canceled, c.Err().Error()) }(ctx) // wait for done channel to be called var doneErr = &lt;-done // if there was a context error return with error if doneErr != nil { return nil, doneErr } // no context error return with response return &amp;retOut, nil } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T05:37:23.393", "Id": "406984", "Score": "1", "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." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T04:25:32.800", "Id": "210542", "Score": "2", "Tags": [ "performance", "go", "concurrency" ], "Title": "Golang gRPC context to check if cancelled or if deadline is exceeded while running function code" }
210542
<p>I was just wondering if someone could check my small "random dice game", which I programmed due to a "do it yourself" from my PHP book. I am happy that it is working and finished the DIY, but however, I want to know if the solution is okay or if there is a way better/easier way to do it.</p> <p>Also please let me know if the way of adding comments is fine, if it is too much or not enough.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Random Dice Game&lt;/title&gt; &lt;link rel="stylesheet" href="css/bootstrap.min.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;table class="table"&gt; &lt;thead&gt;&lt;h3&gt;Lets go!&lt;/h3&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;?php // Defining variables $sum1 = 0; $sum2 = 0; // while loop running until $sum1 or $sum2 &gt;= 21 while($sum1 &lt; 21 &amp;&amp; $sum2 &lt; 21) { // random dice, safing result into variables $dice1 = random_int(1, 6); $dice2 = random_int(1, 6); // $sum1 is increased by $dice1 $sum1 += $dice1; // checking if game is over (winner player 1) if($sum1 &gt;= 21) { echo "&lt;tr&gt;&lt;td&gt;Spieler 1 hat $dice1 gewürfelt. Summe: &lt;b&gt;$sum1&lt;/b&gt;&lt;br&gt;Das Spiel ist beendet.&lt;/td&gt;&lt;/tr&gt;"; break; } // $sum2 is increased by $dice2 $sum2 += $dice2; // checking if game is over (winner player 2) if($sum2 &gt;= 21) { echo "&lt;tr&gt;&lt;td&gt;Spieler 2 hat $dice2 gewürfelt. Summe: &lt;b&gt;$sum2&lt;/b&gt;&lt;br&gt;Das Spiel ist beendet.&lt;/td&gt;&lt;/tr&gt;"; break; } // printing results of both players, if no one won yet echo "&lt;tr&gt;&lt;td&gt;Spieler 1 hat $dice1 gewürfelt. Summe: &lt;b&gt;$sum1&lt;/b&gt;&lt;br&gt;Spieler 2 hat $dice2 gewürfelt. Summe: &lt;b&gt;$sum2&lt;/b&gt;&lt;br&gt;&lt;/td&gt;&lt;/tr&gt;"; } // if game is over, checking who won, printing win-message if($sum1 &gt;= 21 || $sum2 &gt;= 21) { if($sum1 &gt;= 21) { echo "&lt;tr&gt;&lt;td&gt;Wir haben einen Sieger! Glückwunsch, &lt;b&gt;Spieler 1&lt;/b&gt;!&lt;br&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;"; } else { echo "&lt;tr&gt;&lt;td&gt;Wir haben einen Sieger! Glückwunsch, &lt;b&gt;Spieler 2&lt;/b&gt;!&lt;br&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;"; } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Some comments about the generated HTML:</p>\n\n<ul>\n<li><code>&lt;h3&gt;</code>: this element cannot be a child element of <code>thead</code>. Only <code>&lt;tr&gt;</code> elements can be children of <code>&lt;thead&gt;</code>. As a result the browser will in fact place the <code>&lt;h3&gt;</code> element outside of the table.</li>\n<li><code>&lt;br&gt;</code>: this element makes not a lot of sense just before a <code>&lt;/td&gt;</code>. It it was to create extra vertical white-space, then it is better to use CSS styling on your <code>&lt;td&gt;</code> elements</li>\n<li><code>&lt;table&gt;</code>: as your table contains one column only, and the contents are in fact phrases, it is it a bit odd to use a <code>&lt;table&gt;</code> for that. It would make more sense to use <code>&lt;p&gt;</code> or <code>&lt;div&gt;</code> elements.</li>\n<li>You include bootstrap CSS, which is OK, but for the little content you currently have it is probably overkill. It currently takes care of putting a horizontal border between <code>&lt;td&gt;</code> elements, but this you can manage with your own styles (if needed) on the <code>&lt;p&gt;</code> or <code>&lt;div&gt;</code> tags. </li>\n</ul>\n\n<p>Comments about the PHP code:</p>\n\n<ul>\n<li><code>if($sum1 &gt;= 21 || $sum2 &gt;= 21)</code>: this condition will always be true since the <code>while</code> would have continued if this were not the case. You should just omit the <code>if</code>.</li>\n<li>As the logic is the same for the two players it would be better not to have code repetition, but \"toggle\" the player between player 1 and 2.</li>\n<li>It would be even better to put the die-rolling logic in a <code>Player</code> class: one instance per player</li>\n<li>Separate the HTML output generation from the logic. It is better to keep a log of the game in variables and produce the output from that right at the end of your code.</li>\n</ul>\n\n<p>Here is how it could look:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;Random Dice Game&lt;/title&gt;\n &lt;link rel=\"stylesheet\" href=\"css/bootstrap.min.css\"&gt;\n&lt;style&gt;\n div.player0 {\n padding-top: 1rem;\n padding-left: 1rem;\n border-top: 1px solid #dee2e6;\n }\n div.player1 {\n padding-bottom: 1rem;\n padding-left: 1rem;\n }\n div.end {\n padding-bottom: 1rem;\n padding-left: 1rem;\n }\n&lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;h3&gt;Lets go!&lt;/h3&gt;\n &lt;?php\n class Player {\n public $sum = 0;\n public $name;\n public $iswinner = false;\n\n public function __construct($name) {\n $this-&gt;name = $name;\n }\n public function rolldie() {\n // Throw die randomly, saving result into variable\n $die = random_int(1, 6);\n // $sum is increased by $die\n $this-&gt;sum += $die;\n // Check whether game is over\n $this-&gt;iswinner = $this-&gt;sum &gt;= 21;\n }\n }\n // Defining variables\n $players = [new Player(\"Spieler 1\"), new Player(\"Spieler 2\")];\n $log = [];\n $playerid = 1;\n\n // Loop until a player wins\n while (!$players[$playerid]-&gt;iswinner) {\n // Switch player (toggle between 0 and 1)\n $playerid = 1 - $playerid;\n $player = $players[$playerid];\n // Roll the die\n $die = $player-&gt;rolldie();\n // Log the result\n $log[] = [$playerid, $player-&gt;name, $die, $player-&gt;sum];\n }\n $winner = $player-&gt;name;\n\n // Produce the HTML output\n foreach($log as list($playerid, $name, $die, $sum)) {\n ?&gt;\n &lt;div class=\"player&lt;?=$playerid?&gt;\"&gt;$name hat &lt;?=$die?&gt; gewürfelt. Summe: &lt;b&gt;&lt;?=$sum?&gt;&lt;/b&gt;&lt;/div&gt;\n &lt;?php\n }\n ?&gt;\n &lt;div class=\"end\"&gt;Das Spiel ist beendet.&lt;/div&gt;\n &lt;div class=\"winner\"&gt;Wir haben einen Sieger! Glückwunsch, &lt;b&gt;&lt;?=$winner?&gt;&lt;/b&gt;!&lt;/div&gt; \n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T15:34:23.733", "Id": "210556", "ParentId": "210552", "Score": "1" } }, { "body": "<h3>Caption vs. thead</h3>\n\n<blockquote>\n<pre><code> &lt;thead&gt;&lt;h3&gt;Lets go!&lt;/h3&gt;&lt;/thead&gt;\n</code></pre>\n</blockquote>\n\n<p>There are several problems with this. The <code>&lt;thead&gt;</code> element should contain column headers, so something like </p>\n\n<pre><code> &lt;table&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Column name&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n</code></pre>\n\n<p>Replace \"Column name\" with appropriate content. </p>\n\n<p>You may want </p>\n\n<pre><code> &lt;table&gt;\n &lt;caption&gt;Let's go!&lt;/caption&gt;\n</code></pre>\n\n<p>You can put an <code>&lt;h3&gt;</code> inside a caption, but you probably shouldn't, particularly not as the only content. Instead, use CSS to make the <code>caption</code> style match the <code>h3</code> style. </p>\n\n<p>Or semantically, what you may want is </p>\n\n<pre><code> &lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;Let's go!&lt;/td&gt;\n &lt;/tr&gt;\n</code></pre>\n\n<p>That puts this statement at the beginning of the table content rather than making it a heading or caption. That may better reflect the purpose. </p>\n\n<h3>Semantic headings</h3>\n\n<p>Another problem is that you are using headings incorrectly. Each page should have one <code>h1</code> element. In your case, it should probably be before the table and say </p>\n\n<pre><code> &lt;h1&gt;Random dice game&lt;/h1&gt;\n</code></pre>\n\n<p>to match the title. They don't have to be the same, but often are. The title appears in things like the tab's header or a bookmark. The <code>h1</code> heading appears in the content and is intended to say what is in the content. </p>\n\n<p>Below the <code>h1</code>, you can have one or more subheadings, which are <code>h2</code> elements. An <code>h3</code> element would appear below an <code>h2</code>, creating a semantic hierarchy. </p>\n\n<p>Presumably you see the problem now. Not only do you not have any <code>h2</code> elements, you don't have an <code>h1</code>. So you should not have any <code>h3</code> elements. </p>\n\n<p>As I alluded previously, \"Let's go!\" (incidentally, this is the proper spelling; \"let's\" is a contraction of \"let us\" in this context) is not really a proper semantic heading or caption. It does not describe the table or that section of content. </p>\n\n<p>Consider using a <code>&lt;span&gt;</code> with appropriate CSS or a simple <code>&lt;strong&gt;</code> to surround \"Let's go\" instead of something with more semantic meaning that you don't want. </p>\n\n<h3>Table vs. list</h3>\n\n<p>I also notice that your table isn't very tabular. It's basically a bunch of rows. Rather than using a table, consider using a list. </p>\n\n<blockquote>\n<pre><code> echo \"&lt;tr&gt;&lt;td&gt;Spieler 1 hat $dice1 gewürfelt. Summe: &lt;b&gt;$sum1&lt;/b&gt;&lt;br&gt;Das Spiel ist beendet.&lt;/td&gt;&lt;/tr&gt;\";\n</code></pre>\n</blockquote>\n\n<p>could be </p>\n\n<pre><code> echo \"&lt;li&gt;Spieler 1 hat $dice1 gewürfelt. Summe: &lt;strong&gt;$sum1&lt;/strong&gt;&lt;br/&gt;Das Spiel ist beendet.&lt;/li&gt;\";\n</code></pre>\n\n<p>I also replaced the non-semantic <code>&lt;b&gt;</code> with <code>&lt;strong&gt;</code> and changed the SGML <code>&lt;br&gt;</code> to an XML <code>&lt;br/&gt;</code>. Screen readers and other alternate browsers may find it easier to parse this way. </p>\n\n<p>The list can be either ordered (<code>&lt;ol&gt;</code>) or unordered (<code>&lt;ul&gt;</code>), whichever works better for you. </p>\n\n<h3>Comments</h3>\n\n<p>Comments should be used to explain why you are coding things a certain way, not what you are doing. Code like </p>\n\n<blockquote>\n<pre><code> $sum1 = 0;\n $sum2 = 0;\n</code></pre>\n</blockquote>\n\n<p>should be self-explanatory. You don't have to say that you are initializing variables. You might consider changing the names though. Consider </p>\n\n<pre><code> $score1 = 0;\n $score2 = 0;\n</code></pre>\n\n<p>Or even (old way of declaring PHP arrays) </p>\n\n<pre><code> $player_scores = array(0, 0);\n</code></pre>\n\n<p>Or as <a href=\"https://codereview.stackexchange.com/a/210556/71574\">previously suggested</a>, make an array of players where each player object tracks its score. </p>\n\n<p>Back to comments. </p>\n\n<blockquote>\n<pre><code> // while loop running until $sum1 or $sum2 &gt;= 21\n while($sum1 &lt; 21 &amp;&amp; $sum2 &lt; 21) {\n</code></pre>\n</blockquote>\n\n<p>Both the comment and the code say the same thing. So why have the comment? We can just read the code. Consider instead </p>\n\n<pre><code> // first player to $WINNING_SCORE or more wins\n while ($scores[0] &lt; $WINNING_SCORE &amp;&amp; $scores[1] &lt; $WINNING_SCORE) {\n</code></pre>\n\n<p>Now the comment tells my why we are comparing these two variables. Also, I replaced the magic number 21 with a constant. This makes the comment less likely to fall out of synch with the code. E.g. </p>\n\n<pre><code> // first player to 21 or more wins\n while ($scores[0] &lt; 21 &amp;&amp; $scores[1] &lt; 15) {\n</code></pre>\n\n<p>Here, I actually made the code fall out of synch as well. The idea was to make the winning condition lower for both, but the code edit only changed it for one. A constant would not have had that problem. </p>\n\n<p>The only time to use verbose comments like you are is as part of a lecture to students who don't know what the code says, so you are explaining it to them. Unfortunately, this often gives students the wrong idea about how to use comments. So if you are using comments didactically this way, I would suggest on the next slide or figure, showing the code with the comments used more as they would in production code. </p>\n\n<p>It's also worth noting that function names can be used to comment code as well. For example, if you put your random statement inside a <code>roll_die</code> function, then it is obvious that you are using it to simulate a die roll. Or </p>\n\n<pre><code>while (!has_any_won($players)) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:09:45.623", "Id": "210562", "ParentId": "210552", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T12:34:58.980", "Id": "210552", "Score": "0", "Tags": [ "beginner", "php" ], "Title": "Random dice game" }
210552
<p>Signals are represented as types. You can connect a member function of some instance to the Observer system. This connected function will be called whenever a signal of a type that is the same type as the function parameter is emitted.</p> <p>ObserverSystem.hpp:</p> <pre><code>#include &lt;vector&gt; class ObserverSystem { public: template&lt;typename SignalType&gt; inline static void emitSignal(const SignalType&amp; signal) { for(auto f : callEverything&lt;SignalType&gt;) { f(signal); } } template&lt;typename SignalType, typename ObjectType&gt; inline static void connect(ObjectType&amp; object, void (ObjectType::*function)(const SignalType&amp; signal)) { bool add = true; for(auto&amp; entry : functions&lt;SignalType, ObjectType&gt;) { if(entry.function == function &amp;&amp; entry.object == &amp;object) { add = false; break; } } if(add) { functions&lt;SignalType, ObjectType&gt;.emplace_back(ObjectFunction&lt;SignalType, ObjectType&gt;{&amp;object, function}); } add = true; for(auto&amp; entry : callEverything&lt;SignalType&gt;) { if(entry == callAll&lt;SignalType, ObjectType&gt;) { add = false; break; } } if(add) { callEverything&lt;SignalType&gt;.emplace_back(callAll&lt;SignalType, ObjectType&gt;); } } template&lt;typename SignalType, typename ObjectType&gt; inline static void disconnect(ObjectType&amp; object, void (ObjectType::*function)(const SignalType&amp; signal)) { for(size_t i = 0; i &lt; functions&lt;SignalType, ObjectType&gt;.size();) { if(functions&lt;SignalType, ObjectType&gt;[i].function == function &amp;&amp; functions&lt;SignalType, ObjectType&gt;[i].object == &amp;object) { functions&lt;SignalType, ObjectType&gt;.erase(functions&lt;SignalType, ObjectType&gt;.begin() + i); } else { i++; } } } private: template&lt;typename SignalType, typename ObjectType&gt; struct ObjectFunction { ObjectType* object; void (ObjectType::*function)(const SignalType&amp; signal); void call(const SignalType&amp; signal) { (object-&gt;*function)(signal); } }; template&lt;typename SignalType, typename ObjectType&gt; inline static std::vector&lt;ObjectFunction&lt;SignalType, ObjectType&gt;&gt; functions; template&lt;typename SignalType, typename ObjectType&gt; inline static void callAll(const SignalType&amp; signal) { for(auto function : functions&lt;SignalType, ObjectType&gt;) { function.call(signal); } } template&lt;typename SignalType&gt; inline static std::vector&lt;void (*)(const SignalType&amp; signal)&gt; callEverything; }; </code></pre> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; #include "ObserverSystem.hpp" struct SignalTypeOne { int b; }; struct SignalTypeTwo { int x; int y; }; struct Hello { int a = 123; void f(const SignalTypeOne&amp; signal) { std::cout &lt;&lt; (int*)this &lt;&lt; " : a: " &lt;&lt; a &lt;&lt; std::endl; std::cout &lt;&lt; "b: " &lt;&lt; signal.b &lt;&lt; std::endl; } }; struct Some { int vx = 0; int vy = 0; void f1(const SignalTypeTwo&amp; signal) { vx += signal.x; vy += signal.y; } void f2(const SignalTypeOne&amp; signal) { std::cout &lt;&lt; (int*)this &lt;&lt; ": " &lt;&lt; "vx = " &lt;&lt; vx &lt;&lt;", vy = " &lt;&lt; vy &lt;&lt; std::endl; } }; int main() { Hello h; Hello g = Hello{321}; Some v1; Some v2; ObserverSystem::connect(h, &amp;Hello::f); ObserverSystem::connect(g, &amp;Hello::f); ObserverSystem::connect(v1, &amp;Some::f1); ObserverSystem::connect(v2, &amp;Some::f1); ObserverSystem::connect(v1, &amp;Some::f2); ObserverSystem::connect(v2, &amp;Some::f2); ObserverSystem::emitSignal(SignalTypeTwo{1,1}); ObserverSystem::emitSignal(SignalTypeOne{444}); ObserverSystem::disconnect(h, &amp;Hello::f); ObserverSystem::disconnect(v1, &amp;Some::f1); ObserverSystem::emitSignal(SignalTypeTwo{1,2}); ObserverSystem::emitSignal(SignalTypeOne{555}); ObserverSystem::connect(h, &amp;Hello::f); ObserverSystem::emitSignal(SignalTypeTwo{2,1}); ObserverSystem::emitSignal(SignalTypeOne{666}); ObserverSystem::disconnect(h, &amp;Hello::f); ObserverSystem::disconnect(g, &amp;Hello::f); ObserverSystem::disconnect(v2, &amp;Some::f1); ObserverSystem::disconnect(v1, &amp;Some::f2); ObserverSystem::disconnect(v2, &amp;Some::f2); ObserverSystem::emitSignal(SignalTypeTwo{100,100}); ObserverSystem::emitSignal(SignalTypeOne{777}); return 0; } </code></pre> <p>Exemplary output:</p> <pre><code>0x7ffe51692a18 : a: 123 b: 444 0x7ffe51692a10 : a: 321 b: 444 0x7ffe51692a08: vx = 1, vy = 1 0x7ffe51692a00: vx = 1, vy = 1 0x7ffe51692a10 : a: 321 b: 555 0x7ffe51692a08: vx = 1, vy = 1 0x7ffe51692a00: vx = 2, vy = 3 0x7ffe51692a10 : a: 321 b: 666 0x7ffe51692a18 : a: 123 b: 666 0x7ffe51692a08: vx = 1, vy = 1 0x7ffe51692a00: vx = 4, vy = 4 </code></pre> <p>A function should always get disconnected when it gets destroyed.</p> <p>EDIT:</p> <p>Just added free functions: <a href="https://gitlab.com/tsoj/observersystem" rel="nofollow noreferrer">https://gitlab.com/tsoj/observersystem</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:32:52.757", "Id": "407029", "Score": "1", "body": "To me one sender can have more than one signal. And signalling from some global ObserverSystem is not really following other signal-slot framework implementations as well. I cannot see the proper link between one sender and one receiver." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T14:29:59.090", "Id": "407095", "Score": "0", "body": "@AlexanderV `ObserverSystem` is just the manager of all the functionality. A sender would use the function `emitSignal` and since he can use any signal-types he can practically have multiple signals. I would have made the `ObserverSystem` an instanced Object (so that all the public functions are member functions, not statics). However, this seems impossible in C++17 because template member variables are currently not allowed. It may be possible in C++23 with reflection and injection. But since `ObserverSystem` is just the manager of the functions it is not a big problem, that it is global." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:57:37.373", "Id": "407225", "Score": "1", "body": "Having to create a new type for every event (plus possibly needing to wrap the handler in a member function) seem like a lot of boilerplate. Also, this implementation doesn't seem to work with lambdas or other callable objects." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T14:50:47.413", "Id": "210554", "Score": "2", "Tags": [ "c++", "template", "event-handling", "observer-pattern" ], "Title": "Observer(Event) system (Signals and Slots), type and template based" }
210554
<p>Edit: NOTE I'm a C++ "beginner" still in undergrad trying to teach myself modern C++ (because they don't do that in uni) so I'm sure this is riddled with errors that I am unaware of.</p> <p>Made a <em>subset</em> of std's smart pointer library (unique, shared, and weak, denoted as unq, shr, and weak) in a very minimal header file. This is mostly for fun and as a learning experience but looking to improve in any way, thanks!</p> <p><strong>ptr.h</strong></p> <pre><code>#ifndef PTRLIB_H #define PTRLIB_H #include &lt;cstdint&gt; #include &lt;atomic&gt; #include &lt;iostream&gt; namespace ptr { template&lt;typename T&gt; class base //for methods common to all smart ptr types { protected: mutable T * obj; //non instatiable outside the header base() {} base(T * obj) : obj(obj) {} virtual void operator = (T * obj) { this-&gt;obj = obj; } public: //unq uses these versions virtual void reset() { delete this-&gt;obj; this-&gt;obj = nullptr; } virtual void reset(T * obj) { delete this-&gt;obj; this-&gt;obj = obj; } inline T * get() { return obj; } operator bool const () { return (obj != nullptr) ? true : false; } bool operator == (const base&lt;T&gt; rhs) { return obj == rhs.obj; } bool operator != (const base&lt;T&gt; rhs) { return obj != rhs.obj; } bool operator &lt;= (const base&lt;T&gt; rhs) { return obj &lt;= rhs.obj; } bool operator &gt;= (const base&lt;T&gt; rhs) { return obj &gt;= rhs.obj; } bool operator &lt; (const base&lt;T&gt; rhs) { return obj &lt; rhs.obj; } bool operator &gt; (const base&lt;T&gt; rhs) { return obj &gt; rhs.obj; } std::ostream &amp; operator &lt;&lt; (std::ostream &amp; stream) { return (std::cout &lt;&lt; obj); } }; template&lt;typename T&gt; class unq : public base&lt;T&gt; { public: unq() {} unq(T * obj) : base&lt;T&gt;(obj) {} unq(const unq&lt;T&gt; &amp; u) : base&lt;T&gt;(u.obj) { u.obj = nullptr; } ~unq() { delete this-&gt;obj; } T * release() { T * temp = this-&gt;obj; this-&gt;obj = nullptr; return temp; } //don't want weak to be able to access the object so duplicated in shr inline T * operator -&gt; () { return this-&gt;obj; } inline T &amp; operator * () { return *(this-&gt;obj); } }; template&lt;typename T&gt; class weak; //class forwarding for friend class template&lt;typename T&gt; class shr : public base&lt;T&gt; { private: friend class weak&lt;T&gt;; //reference counter mutable std::atomic&lt;int32_t&gt; * refs; inline bool is_last() { return ((refs == nullptr &amp;&amp; this-&gt;obj == nullptr) || *refs == 1); } public: shr() { refs = new std::atomic&lt;int32_t&gt;, *refs = 1; } shr(T * obj) : base&lt;T&gt;(obj) { refs = new std::atomic&lt;int32_t&gt;, *refs = 1; } shr(const shr&lt;T&gt; &amp; s) : base&lt;T&gt;(s.obj) { refs = (s.refs != nullptr) ? s.refs : new std::atomic&lt;int32_t&gt;, *refs += 1; } shr(const weak&lt;T&gt; &amp; w) : base&lt;T&gt;(w.obj) { refs = (w.refs != nullptr) ? w.refs : new std::atomic&lt;int32_t&gt;, *refs += 1; } ~shr() { if (is_last()) { delete this-&gt;obj; this-&gt;obj = nullptr; delete refs; refs = nullptr; } else *refs -= 1; } void operator = (T * obj) { this-&gt;obj = obj; *refs = 1; } void operator = (const shr&lt;T&gt; &amp; s) { this-&gt;obj = s.obj; refs = (s.refs != nullptr) ? s.refs : new std::atomic&lt;int32_t&gt;, *refs += 1; } void operator = (const weak&lt;T&gt; &amp; w) { this-&gt;obj = w.obj; refs = (w.refs != nullptr) ? w.refs : new std::atomic&lt;int32_t&gt;, *refs += 1; } void reset() { if (is_last()) { delete this-&gt;obj; this-&gt;obj = nullptr; delete refs; refs = nullptr; } else { this-&gt;obj = nullptr; *refs -= 1; refs = nullptr; } } void reset(T * obj) { if (is_last()) { delete this-&gt;obj; delete refs; } else *refs -= 1; this-&gt;obj = obj; refs = new std::atomic&lt;int32_t&gt;, *refs = 1; } inline const int32_t use_count() { return static_cast&lt;int32_t&gt;(*refs); } inline bool unique() { return (*refs == 1); } inline T * operator -&gt; () { return this-&gt;obj; } inline T &amp; operator * () { return *(this-&gt;obj); } }; template&lt;typename T&gt; class weak : public base&lt;T&gt; { private: friend class shr&lt;T&gt;; mutable std::atomic&lt;int32_t&gt; * refs; public: weak() {} weak(T * obj) : base&lt;T&gt;(obj) {} weak(const weak&lt;T&gt; &amp; w) : base&lt;T&gt;(w-&gt;obj) {} weak(const shr&lt;T&gt; &amp; s) : base&lt;T&gt;(s.obj), refs(s.refs) {} void operator = (T * obj) { this-&gt;obj = obj; } void operator = (const shr&lt;T&gt; &amp; s) { this-&gt;obj = s.obj; refs = s.refs; } void operator = (const weak&lt;T&gt; &amp; w) { this-&gt;obj = w.obj; refs = w.refs; } void reset() { this-&gt;obj = nullptr; refs = nullptr; } void reset(T * obj) { this-&gt;obj = obj; refs = new std::atomic&lt;int32_t&gt;; *refs = 0; } inline shr&lt;T&gt; lock() { return shr&lt;T&gt;(this-&gt;obj); } inline bool expired() { return ((refs == nullptr || *refs &lt;= 0) ? true : false); } inline const int32_t use_count() { return ((expired()) ? 0 : static_cast&lt;int32_t&gt;(*refs)); } }; template&lt;typename T&gt; const shr&lt;T&gt; make_shr(T * obj) { return shr&lt;T&gt;(obj); } template&lt;typename T&gt; const unq&lt;T&gt; make_unq(T * obj) { return unq&lt;T&gt;(obj); } } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T02:50:47.163", "Id": "407061", "Score": "0", "body": "Quite a lot missing [Have a look here](https://lokiastari.com/blog/2014/12/30/c-plus-plus-by-example-smart-pointer/index.html) [And here](https://lokiastari.com/blog/2015/01/15/c-plus-plus-by-example-smart-pointer-part-ii/index.html) [and constructors](https://lokiastari.com/blog/2015/01/23/c-plus-plus-by-example-smart-pointer-part-iii/index.html)" } ]
[ { "body": "<p>I'll hit the red flags first, and then review the details.</p>\n\n<pre><code>template&lt;typename T&gt; \nconst shr&lt;T&gt; make_shr(T * obj) { return shr&lt;T&gt;(obj); }\n</code></pre>\n\n<p>\"Returning by <code>const</code> value\" is a red flag. It doesn't do anything except occasionally disable move semantics. So at least we remove the <code>const</code>. But also, where there's one bug there's two. So we probably compare your <code>make_shr&lt;T&gt;(...)</code> to the Standard Library's <code>make_shared&lt;T&gt;(...)</code> and find out that your code does something <em>vastly</em> different. Consider</p>\n\n<pre><code>std::shared_ptr&lt;int&gt; sp = std::make_shared&lt;int&gt;(0);\nassert(sp != nullptr);\nptr::shr&lt;int&gt; ps = ptr::make_shr&lt;int&gt;(0);\nassert(ps == nullptr);\n</code></pre>\n\n<hr>\n\n<p>Well, actually I don't think <code>ps == nullptr</code> even compiles with your version, because your comparison operators only ever take <code>base&lt;T&gt;</code>, and the implicit conversion from <code>nullptr_t</code> to <code>base&lt;T&gt;</code> is <code>protected</code> so normal code can't use it. You should have a public conversion from <code>std::nullptr_t</code>, and it should express the idea that you don't <em>take ownership of</em> \"null\"; it's a special state without an owned object.</p>\n\n<hr>\n\n<pre><code>base(T * obj) : obj(obj) {} \n</code></pre>\n\n<p>Each constructor should be <code>explicit</code> unless your goal is specifically to add an implicit conversion. Make this one <code>explicit</code>.</p>\n\n<hr>\n\n<pre><code>std::ostream &amp; operator &lt;&lt; (std::ostream &amp; stream) { return (std::cout &lt;&lt; obj); }\n</code></pre>\n\n<p>The red flag here is that this operator is completely backwards and broken. What you meant was</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt; (std::ostream&amp; stream, const base&lt;T&gt;&amp; p) {\n stream &lt;&lt; p.get();\n return stream;\n}\n</code></pre>\n\n<p>Always use ADL friend functions to implement your operators (except for the few that have to be member functions, such as <code>operator++</code>).</p>\n\n<p>Where there's one bug there's two (or more).</p>\n\n<ul>\n<li>Your version was streaming to <code>std::cout</code> regardless of which <code>stream</code> was passed in.</li>\n<li>\"If it's not tested, it doesn't work.\" Even the very simplest test case would have shown that the version you wrote wasn't functional. If you don't plan to write tests for (or: don't plan to use) a feature, such as <code>operator&lt;&lt;</code>, then you might as well save time and just not write the feature!</li>\n<li><p>Iostreams sucks: Even my new version is broken for <code>ptr::shr&lt;char&gt;</code>. I mean, <code>std::cout &lt;&lt; my_shr_ptr_to_char</code> will end up calling <code>operator&lt;&lt;(ostream&amp;, char*)</code>, which will <em>not</em> print the pointer — it'll print the <em>thing it points to</em>, treated as a C string, which it almost certainly isn't. So it'll segfault and die. The simplest way to work around <em>that</em> is to make sure our code controls the exact overload of <code>operator&lt;&lt;</code> that we call: don't let it be template-dependent. So:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt; (std::ostream&amp; stream, const base&lt;T&gt;&amp; p) {\n stream &lt;&lt; static_cast&lt;void*&gt;(p.get());\n return stream;\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<pre><code>operator bool const () { return (obj != nullptr) ? true : false; }\n</code></pre>\n\n<p>This is a sneaky one I'd never seen before! You put the <code>const</code> in front of the <code>()</code> instead of behind it; so, this is another example of \"returning by <code>const</code> value.\" What you meant to type was</p>\n\n<pre><code>operator bool () const { return (obj != nullptr) ? true : false; }\n</code></pre>\n\n<p>that is, a <code>const</code> member function (which promises not to modify the <code>this</code> object), that returns (non-const-qualified) <code>bool</code>.</p>\n\n<p>Stylistically, there's no sense in writing <code>condition ? true : false</code> — that's like saying <code>if condition is true, return true; if condition is false, return false</code>. So:</p>\n\n<pre><code>operator bool () const { return (obj != nullptr); }\n</code></pre>\n\n<hr>\n\n<pre><code>inline T * get() { return obj; }\n</code></pre>\n\n<p>Any time a function promises not to modify one of its reference parameters, you should make sure to <code>const</code>-qualify that parameter's referent. So, <code>void f(int *p)</code> is saying it might modify <code>*p</code>; <code>void f(const int *p)</code> is saying it promises <em>not</em> to modify <code>*p</code>. Similarly for any member function that promises not to modify its <code>*this</code> parameter: <code>void mf()</code> is saying it <em>might</em> modify <code>*this</code>; <code>void mf() const</code> is saying it promises <em>not</em> to modify <code>*this</code>.</p>\n\n<pre><code>T *get() const { return obj; }\n</code></pre>\n\n<p>I also removed the <code>inline</code> keyword because it wasn't doing anything. Functions defined in the body of a class, like this, Java/Python-style, are already inline by default. The only time you need <code>inline</code> is when you want to define a function <em>in</em> a header file but <em>outside</em> the body of a class.</p>\n\n<hr>\n\n<p>That's enough red flags. Let me mention one super bug and then I'll call it a night.</p>\n\n<pre><code>class weak : public base&lt;T&gt; {\n[...]\n mutable std::atomic&lt;int32_t&gt; * refs;\n[...]\n [no destructor declared]\n};\n</code></pre>\n\n<p>Having an RAII type like <code>weak</code> without a destructor is an oxymoron. <code>weak</code> <em>must</em> have a destructor to clean up its <code>refs</code> member, or else you'll have a leak.\n(Also, <code>refs</code> doesn't need to be <code>mutable</code>.)</p>\n\n<p>But wait, does <code>weak</code> even own its <code>refs</code> at all? Its constructor doesn't call <code>new</code>, so maybe it's okay that its destructor doesn't call <code>delete</code>?... Right. <code>weak::refs</code> is always initialized to point the same place as some <code>shr</code>'s <code>refs</code> pointer. <code>weak::refs</code> is just an observer; <code>shr::refs</code> is the owner of the <code>atomic&lt;int32_t&gt;</code>.</p>\n\n<p>But any time we have a non-owning observer, we should think about <em>dangling</em>. Can <code>weak::refs</code> dangle? Yes, it certainly can!</p>\n\n<pre><code>ptr::shr&lt;int&gt; p(new int(42));\nptr::weak&lt;int&gt; w(p);\np.reset();\nw.expired(); // segfault\nptr::shr&lt;int&gt; q(w.lock());\nassert(q != ptr::shr&lt;int&gt;(nullptr));\n*q; // segfault\n</code></pre>\n\n<p>But your <code>weak</code> is all screwed up. Since it's unusable, you should just remove it. Bring it back if you ever run into a case where you need to use something like <code>weak_ptr</code>, so that you have some idea of what the requirements are. (For example, \"locking an expired <code>weak_ptr</code> should return null,\" or \"locking an unexpired <code>weak_ptr</code> should increment the original refcount, not create a new refcount competing with the first,\" or \"it is nonsensical to create a <code>weak_ptr</code> from a raw <code>T*</code>.\"</p>\n\n<p>Write some test cases for your <code>ptr::unq</code> and <code>ptr::shr</code>. You'll find bugs. Think about how to fix those bugs, and then (only then!) fix them. As you improve your understanding of <em>what</em> the code needs to do, you'll improve your coding style as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:51:35.147", "Id": "407024", "Score": "1", "body": "Thanks a ton for the review! And yea I had a little trouble wrapping my head around how std::weak worked and my implementation here is the result of that. Do you have any tips for effectively implementing it if I try to keep it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:59:26.253", "Id": "407026", "Score": "0", "body": "Also, any critiques on how the program is structured overall? I feel like I could've done it a bit more efficiently but not exactly sure where.\n\nOther sidenote (sorry), I also used mutable for reference counters when taking in const arguments in the constructors, not sure if there is another way around that or if just remove the 'const' altogether?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:41:59.810", "Id": "407031", "Score": "3", "body": "\"Do you have any tips for effectively implementing [`weak_ptr`]?\" Sort of. Does [\"buy my book\"](https://www.amazon.com/Mastering-17-STL-standard-components/dp/178712682X) count as a tip? ;) `weak_ptr` is explained, with diagrams and source code, in Chapter 6." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T17:42:42.787", "Id": "407032", "Score": "0", "body": "\"I also used mutable for reference counters when taking in const arguments in the constructors\" — This comment makes no sense to me. Just remove the `mutable` and recompile; it'll be fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T21:24:56.810", "Id": "407053", "Score": "2", "body": "@sjh919: Note that there are a lot more dangling/memory leak issues than the ones mentioned in this answer (e.g. `auto ptr = ptr::unq<int>(new int); ptr = new int;` leaks the old value and will `delete` the new one two times!). Also, why have a (non-working) copy contructor for `ptr::unq`? // @Quuxplusone: You might want to add a small section on the other parts of the rule of five ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T02:10:48.587", "Id": "407059", "Score": "0", "body": "To be fair, a common way to test `<<` is with `std::cout`, so it's not nearly as \"stupid\" as you make it sound to have missed this particular bug. Though, granted, it's a good lesson in how to write tests better than most of us do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T02:21:44.677", "Id": "407060", "Score": "0", "body": "\"To be fair, a common way to test `<<` is with `std::cout`\" — But another common way is with `std::ostringstream` so that you can verify the results. And OP would have found at least one \"stupid\" bug either way... unless his test was written in the form `myptr << std::cout`. ;)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T16:37:26.993", "Id": "210560", "ParentId": "210557", "Score": "23" } }, { "body": "<p>Let's have a look at some examples where it fails.</p>\n\n<h3>Rule of Three</h3>\n\n<p>You have not correctly over written the assignment operator.</p>\n\n<pre><code>ptr::unq&lt;int&gt; x(new int(5));\nptr::unq&lt;int&gt; y;\n\ny = x; // This is broken. You should look up rule of three.\n</code></pre>\n\n<p>The above code compiles. <strong>BUT</strong> is broken. This pointer will get deleted twice. In debug mode on my compiler it even shows this.</p>\n\n<pre><code>&gt; ./a.out\na.out(7619,0x10f20c5c0) malloc: *** error for object 0x7ff597c02ac0: pointer \nbeing freed was not allocated\na.out(7619,0x10f20c5c0) malloc: *** set a breakpoint in malloc_error_break to debug\n&gt;\n</code></pre>\n\n<h3>Rule of Five</h3>\n\n<p>Now I try and use the move operators.</p>\n\n<pre><code>ptr::unq&lt;int&gt; x(new int(5));\nptr::unq&lt;int&gt; y;\n\ny = std::move(x); // This compiles. Which is a surprise.\n</code></pre>\n\n<p>But again when we run the code and generate an error. </p>\n\n<pre><code>&gt; ./a.out\na.out(7619,0x10f20c5c0) malloc: *** error for object 0x7ff597c02ac0: pointer \nbeing freed was not allocated\na.out(7619,0x10f20c5c0) malloc: *** set a breakpoint in malloc_error_break to debug\n&gt;\n</code></pre>\n\n<p>This suggests that something not quite correct is happening.</p>\n\n<h3>Implicit construction</h3>\n\n<p>You have an implicit construction problem.</p>\n\n<p>Imagine this situation:</p>\n\n<pre><code>void doWork(ptr::unq&lt;int&gt; data)\n{\n std::cout &lt;&lt; \"Do Work\\n\";\n}\n\nint main()\n{\n int* x = new int(5);\n doWork(x); // This creates a ptr::unq&lt;int&gt; object.\n // This object is destroyed at the call which will\n // call delete on the pointer passed.\n\n delete x; // This means this is an extra delete on the pointer\n // which makes it a bug.\n}\n</code></pre>\n\n<p>Running this we get:</p>\n\n<pre><code>&gt; ./a.out\na.out(7619,0x10f20c5c0) malloc: *** error for object 0x7ff597c02ac0: pointer \nbeing freed was not allocated\na.out(7619,0x10f20c5c0) malloc: *** set a breakpoint in malloc_error_break to debug\n&gt;\n</code></pre>\n\n<p>I like that you added a bool operators</p>\n\n<pre><code> operator bool const () { return (obj != nullptr) ? true : false; } \n</code></pre>\n\n<p>Couple of things wrong:</p>\n\n<ul>\n<li>The <code>const</code> is in the wrong place.</li>\n<li>The test is a bit verbose. You are testing a boolean expression <code>(obj != nullptr)</code> then using a trinary operator to extract that value, much easier to simply return the expression.</li>\n<li><p>You also need to use <code>explicit</code>. Otherwise we can use the comparison to compare pointers in a way that we do not intend.</p>\n\n<pre><code>ptr::unq&lt;int&gt; uniqueInt(new int(5));\nptr::unq&lt;flt&gt; uniqueFlt(new flt(12.0));\n\nif (uniqueInt == uniqueFlt) {\n std::cout &lt;&lt; \"I bet this prints\\n\";\n}\n</code></pre></li>\n</ul>\n\n<p>Now when I run:</p>\n\n<pre><code> &gt; ./a.out\n I bet this prints\n &gt;\n</code></pre>\n\n<p>To prevent this you should tack on <code>explicit</code>. This prevents unrequired conversions.</p>\n\n<pre><code> explicit operator bool () const { return obj != nullptr; } \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:35:46.423", "Id": "407106", "Score": "0", "body": "Thank you! Didn't notice the assignment bug with unq. I did notice in your linked article that you mentioned making a smart pointer implementation for learning is a bad idea because it is hard to get it correct in all contexts. While I somewhat agree (in hindsight, after seeing all of my errors) I purposefully made this a _subset_ of a full implementation, where this is in no way intended to be the full thing. Would you agree this is fine to do? \nFurther, other than the specific errors mentioned so far, do you have any critiques of the overall structure of the implementation? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:29:56.917", "Id": "407127", "Score": "0", "body": "@sjh919 I think writing a smart pointers is a good exercise for any programmer as it teaches a lot. **BUT** I think it is also very hard and something you should try once you have a lot of experience already. I think it is way too difficult for a beginner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T03:31:26.333", "Id": "210583", "ParentId": "210557", "Score": "11" } } ]
{ "AcceptedAnswerId": "210560", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-29T15:42:14.670", "Id": "210557", "Score": "15", "Tags": [ "c++", "c++11", "pointers" ], "Title": "C++11 smart pointer 'library'" }
210557
<p>I'm working on a WPF 4.5 desktop application that has several nested collections with the following key aspects:</p> <ul> <li>writes mainly from UI thread, but also from worker threads</li> <li>writes are relatively seldom, mainly directly after a user interaction</li> <li>reads from any thread, but esp. one performance critical worker thread with very many reads (iterating in millisecond intervals)</li> <li>with the exception of the thread mentioned above, read/write performance should not be critical</li> <li>items need to be ordered, i.e. an item's position must always stay the same</li> <li>"remove item" must be supported</li> <li>"insert at" must be supported, although I'm aware that indices must be handled with care, if several threads are involved</li> <li>collection will be used as a WPF binding source and must be observable (implement <code>INotifyCollectionChanged</code> and <code>INotifyPropertyChanged</code> so WPF can update the UI, if items are added/removed)</li> <li><strong>collection must support live-shaping</strong> (allowing WPF to instantly update a control's sorting/filtering, if relevant items' properties change; requires the underlying collection to implement <code>IList</code> or similar, so a <code>ListCollectionView</code> can be used)</li> <li>a lookup via key is not required (or can be achieved using extension methods, e.g. <code>FirstOrDefault</code>)</li> <li>approx. max. number of collections &lt; 10k</li> <li>approx. max. number of items / collection &lt; 1k</li> </ul> <p>The out-of-the-box system classes have the following issues (for my use-case) which prevent me from using them as-is:</p> <ul> <li><code>System.Collections.Concurrent</code> classes do not implement <code>IList</code> - and cannot be used for live-shaping</li> <li><code>System.Collections.ObjectModel.ObservableCollection&lt;T&gt;</code> is not thread-safe</li> </ul> <p>So to fulfill all above requirements I created a wrapper class that implements the required interfaces (e.g. <code>IList</code>, <code>INotifyCollectionChanged</code>...). Internally I chose to use <code>List&lt;T&gt;</code>. (I could have chosen <code>ObservableCollection</code>, but I wanted full control when invoking/dispatching <code>CollectionChanged</code>.)</p> <p>For all <em>write</em> operations the wrapper class uses <code>lock(_lock)</code> and delegates the call to the inner list. Also - from within the lock - it updates an <code>Array</code> snapshot of the current list, stored in a private field, <code>_snapshot</code>. Then - still from within the lock - it uses <code>System.Windows.Threading.Dispatcher.InvokeAsync()</code> to raise the <code>CollectionChanged</code> event on the correct UI thread.</p> <p>All <em>read</em> operations use the cached <code>_snapshot</code>, esp. <code>GetEnumerator</code>. The intention behind the snapshot is to avoid locking in the <code>GetEnumerator</code> implementation, for performance reasons of the thread with many reads.</p> <p><strong>Is the approach ok, what am I missing, what else must I be aware of?</strong></p> <p>Here's my current code (with some omissions), which appears to work:</p> <p>EDIT: I included the previously omitted <code>ICollection</code> and <code>IList</code> implementations.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Threading; using System.Windows; namespace StackOverflow.Questions { public class ObservableConcurrentList&lt;T&gt; : IList, IList&lt;T&gt;, INotifyCollectionChanged, INotifyPropertyChanged { private readonly System.Windows.Threading.Dispatcher _context; private readonly IList&lt;T&gt; _list = new List&lt;T&gt;(); private readonly object _lock = new object(); private T[] _snapshot; public ObservableConcurrentList() { _context = Application.Current?.Dispatcher; updateSnapshot(); SuppressNotifications = suppressNotifications; } public event NotifyCollectionChangedEventHandler CollectionChanged; public event PropertyChangedEventHandler PropertyChanged; private void updateSnapshot() { lock (_lock) //precautionary; should be re-entry { Interlocked.Exchange(ref _snapshot, _list.ToArray()); } } private void notify(NotifyCollectionChangedEventArgs args) { if (_context == null) { invokeCollectionChanged(args); } else { _context.InvokeAsync(() =&gt; invokeCollectionChanged(args)); } } private void invokeCollectionChanged(NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(this, args); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); } #region IEnumerable public IEnumerator&lt;T&gt; GetEnumerator() { var localSnapshot = _snapshot; //create local variable to protect enumerator, if class member (_snapshot) should be changed/replaced while iterating return ((IEnumerable&lt;T&gt;)localSnapshot).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region ICollection&lt;T&gt; public void Add(T item) { lock (_lock) { _list.Add(item); updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, _list.Count - 1)); } } public bool Contains(T item) { return _snapshot.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _snapshot.CopyTo(array, arrayIndex); } public bool Remove(T item) { lock (_lock) { var index = _list.IndexOf(item); if (index &gt; -1) { if (_list.Remove(item)) { updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); return true; } } return false; } } public void Clear() { lock (_lock) { _list.Clear(); updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } public bool IsReadOnly =&gt; false; #endregion #region IList&lt;T&gt; public int IndexOf(T item) { return Array.IndexOf(_snapshot, item); } public void Insert(int index, T item) { lock (_lock) { _list.Insert(index, item); updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } } public void RemoveAt(int index) { lock (_lock) { var item = _list[index]; _list.RemoveAt(index); updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); } } public T this[int index] { get =&gt; _snapshot[index]; set { lock (_lock) { var item = _list[index]; _list[index] = value; updateSnapshot(); notify(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, item, index)); } } } #endregion #region ICollection (explicit) void ICollection.CopyTo(Array array, int index) { CopyTo((T[])array, index); } public int Count =&gt; _snapshot.Length; object ICollection.SyncRoot =&gt; this; //https://stackoverflow.com/questions/728896/whats-the-use-of-the-syncroot-pattern/728934#728934 bool ICollection.IsSynchronized =&gt; false; //https://stackoverflow.com/questions/728896/whats-the-use-of-the-syncroot-pattern/728934#728934 #endregion #region IList (explicit) object IList.this[int index] { get =&gt; ((IList&lt;T&gt;)this)[index]; set =&gt; ((IList&lt;T&gt;)this)[index] = (T)value; } int IList.Add(object value) { lock (_lock) { Add((T)value); return _list.Count - 1; } } bool IList.Contains(object value) { return Contains((T)value); } int IList.IndexOf(object value) { return IndexOf((T)value); } void IList.Insert(int index, object value) { Insert(index, (T)value); } bool IList.IsFixedSize =&gt; false; void IList.Remove(object value) { Remove((T)value); } #endregion } } </code></pre> <p>EDIT: Coming back to this after some time in which I've had some real-life experience with the above concept, I'd like to add:</p> <ul> <li>The above implementation will not work reliably. If I find the time, I will try to update the post using an extract from my actual working class.</li> <li>Raising <code>CollectionChanged</code> from within the lock is indeed more than a smell as noted in the comments.</li> <li>If dispatched using <code>Invoke</code> from within the lock, deadlocks can and will occur.</li> <li>Dispatching from within the lock using <code>InvokeAsync</code> defies the intention/purpose, because the event will be handled later, actually outside the lock, because the call will be added to the message loop.</li> <li>Ergo: Use <code>DispatchAsync</code> from outside the lock - as "fire &amp; forget" is often best practice regarding UI events.</li> <li>Consequences: <ul> <li>For the <code>CollectionChanged</code> event the <code>Reset</code> variant must always be used, because the colleciton may have changed since the event was raised, because it is handled at an undetermined time later. That would lead to inconsistencies and/or exceptions.</li> <li>As defined for the <code>Reset</code> flag, the UI will always update the entire list, instead of adding/removing specific items. Performance-wise this is sup-optimal, of course.</li> </ul></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T10:43:25.230", "Id": "407083", "Score": "3", "body": "I'm not happy about you ommiting the `IList` implementation. Since this is one of the main reasons you've decided to create your own type it definitely shouldn't have been removed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T10:47:10.787", "Id": "407084", "Score": "0", "body": "the IList methods only wrap IList<T> methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T11:19:07.713", "Id": "407086", "Score": "1", "body": "Please add it anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:25:30.430", "Id": "407092", "Score": "1", "body": "@t3chb0t, @Mast: I just added the implementations of `ICollection` and `IList`" } ]
[ { "body": "<p>Raising events inside of a lock is a code smell. Locks should be short lived as possible. Plus since, maybe today, you know what the events will do that doesn't mean in the future they won't change. Having a long processing event could make this a bottle neck or if an event also subscribed and wanted to update the collection has the potential for a deadlock. </p>\n\n<p>You have this statement in the constructor </p>\n\n<pre><code>SuppressNotifications = suppressNotifications;\n</code></pre>\n\n<p>This field and parameter don't exist. I assume it's a copy / paste error.</p>\n\n<p>Instead of locking and creating a snapshot each time you could use the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.7.2\" rel=\"noreferrer\">ReaderWriterLockSlim</a> class to lock reading and writing. The GetEnumerator would probably still want a snapshot but could be done by making the snapshot lazy. Then the code would look something similar to this</p>\n\n<pre><code>private void UpdateSnapshot()\n{\n if (_snapShot == null || _snapShot.IsValueCreated)\n {\n Interlocked.Exchange(ref _snapShot, new Lazy&lt;T[]&gt;(() =&gt;\n {\n T[] result;\n var lockTaken = false;\n try\n {\n _lock.EnterReadLock();\n lockTaken = true;\n result = _list.ToArray();\n }\n finally\n {\n if (lockTaken)\n {\n _lock.ExitReadLock();\n }\n }\n return result;\n }));\n }\n}\n</code></pre>\n\n<p>Basically this would defer the coping of all the items to the snapshot until an enumerator has accessed it and if no updates where done then the Lazy object is acting like a caching object. Again this code is assuming switching to the ReaderWriterLockSlim Class. But this way when collection has a process that is adding items to the collection the class doesn't make a new copy of the list every add. </p>\n\n<p>** As a side note the coding for the ReaderWriterLockSlim class is a bit much but it's not hard to create an IDisposable class that wraps it so the locks turn into using statements that hide the try/finally/lock taken code. </p>\n\n<p>For saving the dispatcher I would suggest reading this <a href=\"http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx\" rel=\"noreferrer\">blog</a>. It gets a list of event handler target to see if it's a dispatcher object</p>\n\n<pre><code>var delegates = eventHandler.GetInvocationList();\n// Walk thru invocation list\nforeach (NotifyCollectionChangedEventHandler handler in delegates)\n{\n var dispatcherObject = handler.Target as DispatcherObject;\n // If the subscriber is a DispatcherObject and different thread\n if (dispatcherObject != null &amp;&amp; dispatcherObject.CheckAccess() == false)\n {\n // Invoke handler in the target dispatcher's thread\n dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);\n }\n else // Execute handler as is\n {\n handler(this, e);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:52:21.173", "Id": "407603", "Score": "0", "body": "Regarding the event from within the lock, I get the code smell, but figured it would be safer this way when the UI (WPF) handles the event, making sure it is not changed again in the meantime which could make the `NotifyCollectionChangedEventArgs`wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:56:57.427", "Id": "407604", "Score": "0", "body": "Regarding the dispatcher: the code presented here will soon be modified to use a custom dispatcher (interface) that may wrap `System.Windows.Threading.Dispatcher`, but may also use a queue etc. Thanks a lot for the link, though, it may come in handy sometime else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T22:01:58.940", "Id": "407605", "Score": "0", "body": "Regarding the lazy snapshot for `GetEnumerator`: that is specifically the code where I want as little overhead as possible and the extra memory cost will not be a problem. Nonetheless: a lazy snapshot implementation could be an interesting (if optional) feature." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:04:31.283", "Id": "210840", "ParentId": "210575", "Score": "5" } }, { "body": "<h2>Usability (WPF Only)</h2>\n\n<p>I've read in comments on a different answer that you were going to wrap <code>private readonly System.Windows.Threading.Dispatcher _context;</code> in some kind of custom dispatcher. Don't do this! Your class depends on a WPF dispatcher, hence it's use cases are limited to WPF. You should use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext?view=netframework-4.8\" rel=\"nofollow noreferrer\">TaskScheduler</a> instead. If you create your list in the main UI thread of WPF, you could give it an instance like this:</p>\n\n<pre><code>var uiCallbackScheduler = TaskScheduler.FromCurrentSynchronizationContext();\n</code></pre>\n\n<p>You are using some nasty tricks to make the collection work for unit tests I suppose. The problem is you have a hard dependency on <code>Application.Current</code>. Whether you keep the dispatcher or use a task scheduler, you should always try to avoid dependencies like this. You won't even be able to test the production pattern (using a dispatcher) in unit tests.</p>\n\n<blockquote>\n<pre><code> // so you won't always have a dispatcher, why allow this?\n_context = Application.Current?.Dispatcher; \n\nprivate void notify(NotifyCollectionChangedEventArgs args)\n{\n if (_context == null)\n {\n invokeCollectionChanged(args);\n }\n else\n {\n _context.InvokeAsync(() =&gt; invokeCollectionChanged(args));\n }\n}\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-29T04:32:41.773", "Id": "227057", "ParentId": "210575", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T00:29:54.633", "Id": "210575", "Score": "8", "Tags": [ "c#", "multithreading", "concurrency", "wpf" ], "Title": "Concurrent observable collection" }
210575
<p>This function below (used on a timeout due to my page loading time) displays information on my site. I grab this data from my table view that I load into the page. It is launched by clicking a button in the table view, and gives that information from the corresponding row. It is very clunky. As you can see in the code, certain values (current year, costume_exists boolean value) change the output of data being displayed. Is there an easier or cleaner way of doing this?</p> <pre><code>setTimeout(function() { var table = document.getElementById("bands"); var icon = "&lt;/i&gt;"; if (table != null) { for (var i = 0; i &lt; table.rows.length; i++) { for (var j = 0; j &lt; table.rows[i].cells.length; j++) table.rows[i].cells[j].onclick = function() { if (this.cellIndex == 7) { if (!this.innerHTML.includes(icon)) { var $row = $(this).closest("tr"); var $year = $row.find(".year").text(); var $prize = $row.find(".prize").text(); var $band = $row.find(".band").text(); var $mp = $row.find(".mp").text(); var $ge_music = $row.find(".ge_music").text(); var $vp = $row.find(".vp").text(); var $ge_visual = $row.find(".ge_visual").text(); var $costume = $row.find(".costume").text(); var $total = $row.find(".total").text(); var $costumer = $row.find(".costumer").text(); var $designer = $row.find(".designer").text(); var $arranger = $row.find(".arranger").text(); var $choreographer = $row.find(".choreographer").text(); if ($costume.length &gt; 1) { costume_exists = true; } else { costume_exists = false; } if ($mp.length &gt; 0) { playing_exists = true; } else { playing_exists = false; } breakdown = "breakdown" if ($year &lt; 1991 &amp;&amp; costume_exists) { breakdown = ('&lt;h3&gt;' + $band + " " + $year + '&lt;/h3&gt;' + '&lt;i&gt;' + getOrdinal($prize) + ' Prize' + '&lt;/i&gt;&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Music:&lt;/b&gt; ' + $ge_music + '&lt;br&gt;' + '&lt;b&gt;Presentation:&lt;/b&gt; ' + $ge_visual + '&lt;br&gt;' + '&lt;b&gt;Costume:&lt;/b&gt; ' + $costume + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Total Points:&lt;/b&gt; ' + $total + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Costumer:&lt;/b&gt; ' + $costumer + '&lt;br&gt;' + '&lt;b&gt;Costume/Set Designer:&lt;/b&gt; ' + $designer + '&lt;br&gt;' + '&lt;b&gt;Music Arranger:&lt;/b&gt; ' + $arranger + '&lt;br&gt;' + '&lt;b&gt;Choreographer:&lt;/b&gt; ' + $choreographer + '&lt;br&gt;') swal({ title: 'Point Breakdown', html: breakdown }) } else if (costume_exists) { breakdown = ('&lt;h3&gt;' + $band + " " + $year + '&lt;/h3&gt;' + '&lt;i&gt;' + getOrdinal($prize) + ' Prize' + '&lt;/i&gt;&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Music Playing:&lt;/b&gt; ' + $mp + '&lt;br&gt;' + '&lt;b&gt;General Effect Music:&lt;/b&gt; ' + $ge_music + '&lt;br&gt;' + '&lt;b&gt;Visual Performance:&lt;/b&gt; ' + $vp + '&lt;br&gt;' + '&lt;b&gt;General Effect - Visual:&lt;/b&gt; ' + $ge_visual + '&lt;br&gt;' + '&lt;b&gt;Costume:&lt;/b&gt; ' + $costume + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Total Points:&lt;/b&gt; ' + $total + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Costumer:&lt;/b&gt; ' + $costumer + '&lt;br&gt;' + '&lt;b&gt;Costume/Set Designer:&lt;/b&gt; ' + $designer + '&lt;br&gt;' + '&lt;b&gt;Music Arranger:&lt;/b&gt; ' + $arranger + '&lt;br&gt;' + '&lt;b&gt;Choreographer:&lt;/b&gt; ' + $choreographer + '&lt;br&gt;') swal({ title: 'Point Breakdown', html: breakdown }) } else if (playing_exists) { breakdown = ('&lt;h3&gt;' + $band + " " + $year + '&lt;/h3&gt;' + '&lt;i&gt;' + getOrdinal($prize) + ' Prize' + '&lt;/i&gt;&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Music Playing:&lt;/b&gt; ' + $mp + '&lt;br&gt;' + '&lt;b&gt;General Effect Music:&lt;/b&gt; ' + $ge_music + '&lt;br&gt;' + '&lt;b&gt;Visual Performance:&lt;/b&gt; ' + $vp + '&lt;br&gt;' + '&lt;b&gt;General Effect - Visual:&lt;/b&gt; ' + $ge_visual + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Total Points:&lt;/b&gt; ' + $total + '&lt;br&gt;&lt;br&gt;' + '&lt;b&gt;Costumer:&lt;/b&gt; ' + $costumer + '&lt;br&gt;' + '&lt;b&gt;Costume/Set Designer:&lt;/b&gt; ' + $designer + '&lt;br&gt;' + '&lt;b&gt;Music Arranger:&lt;/b&gt; ' + $arranger + '&lt;br&gt;' + '&lt;b&gt;Choreographer:&lt;/b&gt; ' + $choreographer + '&lt;br&gt;') swal({ title: 'Point Breakdown', html: breakdown }) } else { alert("No point breakdowns for " + $year + " are available."); } } } } } }; }, 700); </code></pre>
[]
[ { "body": "<p>I don't have much experience with JavaScript, so I apologize if my suggestions aren't idiomatic (or runnable) JS. Here are a few things I see.</p>\n\n<h2>Consistent spacing</h2>\n\n<p>You switch between tabs of two spaces and four spaces. It's not clear to me why.</p>\n\n<h2>Use braces for multi-line for loops</h2>\n\n<p>Your second for loop is missing curly braces. It makes things easier to read to include curly braces if the for loop has code that spans multiple lines.</p>\n\n<h2>Use the boolean directly</h2>\n\n<p>You can assign the boolean value of an expression directly to a variable.</p>\n\n<pre><code>if ($costume.length &gt; 1) {\n costume_exists = true;\n} else {\n costume_exists = false;\n}\n\nif ($mp.length &gt; 0) {\n playing_exists = true;\n} else {\n playing_exists = false;\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>costume_exists = $costume.length &gt; 1;\nplaying_exists = $mp.length &gt; 0;\n</code></pre>\n\n<h2>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template literals</a></h2>\n\n<p>You can embed expressions into template strings directly. The parenthesis around the expression look to be unnecessary.</p>\n\n<pre><code>breakdown = ('&lt;h3&gt;' + $band + \" \" + $year + '&lt;/h3&gt;' +\n '&lt;i&gt;' + getOrdinal($prize) + ' Prize' + '&lt;/i&gt;&lt;br&gt;&lt;br&gt;' +\n '&lt;b&gt;Music:&lt;/b&gt; ' + $ge_music + '&lt;br&gt;' +\n '&lt;b&gt;Presentation:&lt;/b&gt; ' + $ge_visual + '&lt;br&gt;' +\n '&lt;b&gt;Costume:&lt;/b&gt; ' + $costume + '&lt;br&gt;&lt;br&gt;' +\n '&lt;b&gt;Total Points:&lt;/b&gt; ' + $total + '&lt;br&gt;&lt;br&gt;' +\n '&lt;b&gt;Costumer:&lt;/b&gt; ' + $costumer + '&lt;br&gt;' +\n '&lt;b&gt;Costume/Set Designer:&lt;/b&gt; ' + $designer + '&lt;br&gt;' +\n '&lt;b&gt;Music Arranger:&lt;/b&gt; ' + $arranger + '&lt;br&gt;' +\n '&lt;b&gt;Choreographer:&lt;/b&gt; ' + $choreographer + '&lt;br&gt;')\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>breakdown = `&lt;h3&gt;{$band} {$year}&lt;/h3&gt;\n &lt;i&gt;{getOrdinal($prize)} Prize&lt;/i&gt;&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Music:&lt;/b&gt; {$ge_music}&lt;br&gt;\n &lt;b&gt;Presentation:&lt;/b&gt; {$ge_visual}&lt;br&gt;\n &lt;b&gt;Costume:&lt;/b&gt; {$costume}&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Total Points: {$total}&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Costumer:&lt;/b&gt; {$costumer}&lt;br&gt;\n &lt;b&gt;Costume/Set Designer:&lt;/b&gt; {$designer}&lt;br&gt;\n &lt;b&gt;Music Arranger:&lt;/b&gt; {$arranger}&lt;br&gt;\n &lt;b&gt;Choreographer:&lt;/b&gt; {$choreographer}&lt;br&gt;`\n</code></pre>\n\n<p><strong>Edit:</strong> If <code>getOrdinal()</code> is breaking in the template, a hacky way to get around this is define <code>const prizeOrd = getOrdinal($prize);</code> then use <code>{prizeOrd}</code> in its place.</p>\n\n<h2>Reduce nesting</h2>\n\n<p>You can reduce nesting by inverting and combining your if-statements.</p>\n\n<pre><code>table.rows[i].cells[j].onclick = function() {\n if (this.cellIndex == 7) {\n if (!this.innerHTML.includes(icon)) {\n // code\n }\n }\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>table.rows[i].cells[j].onclick = function() {\n if (this.cellIndex != 7 || this.innerHTML.includes(icon)) {\n return;\n }\n\n // code\n}\n</code></pre>\n\n<p>More nesting can be reduced, like the <code>table != null</code> check.</p>\n\n<h2>Avoid unneeded duplication</h2>\n\n<p>A lot of your lines are taken up by constructing separate (but very similar) strings depending on a few conditions. With template literals, we can use one string with inner expressions.</p>\n\n<p>Define a string for the music portion as such:</p>\n\n<pre><code>music = $year &lt; 1991 &amp;&amp; costume_exists\n ? `&lt;b&gt;Music:&lt;/b&gt; {$ge_music}&lt;br&gt;`\n : `&lt;b&gt;Music Playing:&lt;/b&gt; {$mp}&lt;br&gt;`;\n</code></pre>\n\n<p>I can't verify if that's valid syntax for JS, but you get the gist. Likewise with the costume portion.</p>\n\n<p>It's not the exact same behavior, but this seems to be what you're going for:</p>\n\n<pre><code>breakdown = \"breakdown\"\n\nif ($year &gt; 1991 &amp;&amp; !costume_exists &amp;&amp; !playing_exists) {\n alert(`No point breakdowns for {$year} are available.`);\n return;\n}\n\nmusic = $year &lt; 1991 &amp;&amp; costume_exists\n ? `&lt;b&gt;Music:&lt;/b&gt; {$ge_music}&lt;br&gt;`\n : `&lt;b&gt;Music Playing:&lt;/b&gt; {$mp}&lt;br&gt;`;\n\ncostume = custume_exists\n ? `&lt;b&gt;Costume:&lt;/b&gt; {$costume}&lt;br&gt;&lt;br&gt;`\n : '';\n\nbreakdown = `&lt;h3&gt;{$band} {$year}&lt;/h3&gt;\n &lt;i&gt;{getOrdinal($prize)} Prize&lt;/i&gt;&lt;br&gt;&lt;br&gt;\n {music}\n &lt;b&gt;Presentation:&lt;/b&gt; {$ge_visual}&lt;br&gt;\n {costume}\n &lt;b&gt;Total Points: {$total}&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Costumer:&lt;/b&gt; {$costumer}&lt;br&gt;\n &lt;b&gt;Costume/Set Designer:&lt;/b&gt; {$designer}&lt;br&gt;\n &lt;b&gt;Music Arranger:&lt;/b&gt; {$arranger}&lt;br&gt;\n &lt;b&gt;Choreographer:&lt;/b&gt; {$choreographer}&lt;br&gt;`\n\nswal({\n title: 'Point Breakdown',\n html: breakdown\n})\n</code></pre>\n\n<h2>JavaScript after loading</h2>\n\n<blockquote>\n <p>This function below (used on a timeout due to my page loading time) displays information on my site.</p>\n</blockquote>\n\n<p>Normally, you would do this <a href=\"https://stackoverflow.com/a/807895/6789498\">as such</a>:</p>\n\n<pre><code>window.onload = function ...\n</code></pre>\n\n<p>This also should work consistently, whereas using a pre-defined timeout duration may not work with extremely slow internet.</p>\n\n<h2>Use <code>const</code></h2>\n\n<p>You can use the <code>const</code> keyword instead of <code>var</code> for the <code>icon</code> variable.</p>\n\n<pre><code>const icon = \"&lt;/i&gt;\";\n</code></pre>\n\n<p>Given that this is JavaScript, it will make zero difference performance-wise. But, if the value isn't meant to be changed, this gives an indication to those who read your code.</p>\n\n<h2>Performance</h2>\n\n<p>Currently you iterate over all cells in the table, <span class=\"math-container\">\\$O(mn)\\$</span>. I am not familiar enough with JavaScript to suggest something with better performance.</p>\n\n<p>However I would certainly look into this if your tables become large.</p>\n\n<h2>Conclusion</h2>\n\n<p>Here is the code I ended up with:</p>\n\n<pre><code>window.onload = function() {\n const table = document.getElementById(\"bands\");\n\n const icon = \"&lt;/i&gt;\";\n\n if (table != null) {\n for (var i = 0; i &lt; table.rows.length; i++) {\n for (var j = 0; j &lt; table.rows[i].cells.length; j++) {\n table.rows[i].cells[j].onclick = function() {\n if (this.cellIndex !== 7 || this.innerHTML.includes(icon)) {\n return;\n }\n\n const $row = $(this).closest(\"tr\");\n const $year = $row.find(\".year\").text();\n const $prize = $row.find(\".prize\").text();\n const $band = $row.find(\".band\").text();\n const $mp = $row.find(\".mp\").text();\n const $ge_music = $row.find(\".ge_music\").text();\n const $vp = $row.find(\".vp\").text();\n const $ge_visual = $row.find(\".ge_visual\").text();\n const $costume = $row.find(\".costume\").text();\n const $total = $row.find(\".total\").text();\n const $costumer = $row.find(\".costumer\").text();\n const $designer = $row.find(\".designer\").text();\n const $arranger = $row.find(\".arranger\").text();\n const $choreographer = $row.find(\".choreographer\").text();\n\n const costume_exists = $costume.length &gt; 1;\n\n const playing_exists = $mp.length &gt; 0;\n\n var breakdown = \"breakdown\"\n\n if ($year &gt; 1991 &amp;&amp; !costume_exists &amp;&amp; !playing_exists) {\n alert(`No point breakdowns for {$year} are available.`);\n return;\n }\n\n const music = $year &lt; 1991 &amp;&amp; costume_exists\n ? `&lt;b&gt;Music:&lt;/b&gt; {$ge_music}&lt;br&gt;`\n : `&lt;b&gt;Music Playing:&lt;/b&gt; {$mp}&lt;br&gt;`;\n\n const costume = custume_exists\n ? `&lt;b&gt;Costume:&lt;/b&gt; {$costume}&lt;br&gt;&lt;br&gt;`\n : '';\n\n breakdown = `&lt;h3&gt;{$band} {$year}&lt;/h3&gt;\n &lt;i&gt;{getOrdinal($prize)} Prize&lt;/i&gt;&lt;br&gt;&lt;br&gt;\n {music}\n &lt;b&gt;Presentation:&lt;/b&gt; {$ge_visual}&lt;br&gt;\n {costume}\n &lt;b&gt;Total Points: {$total}&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Costumer:&lt;/b&gt; $costumer&lt;br&gt;\n &lt;b&gt;Costume/Set Designer:&lt;/b&gt; {$designer}&lt;br&gt;\n &lt;b&gt;Music Arranger:&lt;/b&gt; {$arranger}&lt;br&gt;\n &lt;b&gt;Choreographer:&lt;/b&gt; {$choreographer}&lt;br&gt;`\n\n swal({\n title: 'Point Breakdown',\n html: breakdown\n })\n }\n }\n }\n }\n};\n</code></pre>\n\n<p>I have no way to verify that it works, but it looks like it should.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T22:05:49.163", "Id": "407148", "Score": "1", "body": "+1 A lot of great tips here. Was going to post an answer but I think you've got pretty much everything covered. Only other suggestion to add might be to pull all of those `$row.find()` constants into a function to help make the main-loop more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:25:14.673", "Id": "407239", "Score": "0", "body": "Because I'm using the table data for the information needed to display, I can't use a window.onload function for this. The code you gave did not work at all, unfortunately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:53:54.137", "Id": "407247", "Score": "0", "body": "Meaning, without the `window.onload`, it still doesn't run? What part of it isn't runnable JavaScript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T20:06:30.770", "Id": "441228", "Score": "0", "body": "Unfortunately, the culprit is the `getOrdinal` function. How do I write that to be compatible with template literals?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-27T19:24:55.180", "Id": "441425", "Score": "0", "body": "@FrankDoe Hm, maybe functions don't work in JS templates? Sorry. One possible way to get around this is to define a variable `prizeOrd = getOrdinal(...` and use `prizeOrd` in the template literal. I've updated my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-27T19:58:20.260", "Id": "441432", "Score": "1", "body": "Was a little confusing, but what was missing was the $ outside of the first curly brace in that line. Thank you for your help!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T01:58:21.597", "Id": "210579", "ParentId": "210576", "Score": "2" } }, { "body": "<p>As most of the points have been covered in the other answer I will just add some more.</p>\n\n<h2>Alert is evil</h2>\n\n<p>Do not use alert. There are only some very limited reasons to use them. This is not one of them. </p>\n\n<p>Reasons not to use them.</p>\n\n<ul>\n<li>They are blocking and stop all Javascript from running while they are up.</li>\n<li>They they prevent the client from navigating until they have been cleared.</li>\n<li>They are annoying and require user interaction (in this case) when none is needed.</li>\n<li>They can not be trusted. Clients can opt to have all alerts disabled so you can never be sure they are displayed.</li>\n<li>They are ugly as sin.</li>\n<li>They are too late. User interaction should never be a guessing game.</li>\n</ul>\n\n<p>For this type of interaction you are far better to predetermine if an item can be clicked and use the <code>cursor</code> to show if it can be clicked. A simple cursor as pointer <code>&lt;style&gt;.can-click { cursor: pointer; }&lt;/style&gt;</code> and a tooltip is all that is needed to indicate that the item can be clicked, rather than a page blocking intrusive pointless alert (I never return to a sites that do that).</p>\n\n<p>If you must have a dialog the use a custom <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\">dialog</a>. </p>\n\n<pre><code>&lt;dialog id=\"noBreakdownsEl\"&gt;\n &lt;p&gt;No point breakdowns for &lt;span id=\"dialogYearEl\"&gt;&lt;/span&gt; are available.&lt;/p&gt;\n&lt;/dialog&gt;\n&lt;script&gt;\n setTimeout(() =&gt; {\n dialogYearEl.textContent = 1992;\n noBreakdownsEl.showModal();\n },1000);\n&lt;/script&gt;\n</code></pre>\n\n<h2>Keep it D.R.Y. (Don't Repeat Yourself)</h2>\n\n<p>You code is full of repeated code and data. As a programer, each repeated string of source code (especially data) should annoy you. It is very rare that you will need to repeat data, and if you are repeating source code, it should be in a function.</p>\n\n<h2>HTML is for transport</h2>\n\n<p>HTML is specifically designed for transport (eg from server to client over network) It is not a client side rendering language, you have the DOM API for that</p>\n\n<p>Reasons not to add HTML via JS </p>\n\n<ol>\n<li>It is slow (very very slow). </li>\n<li>It encourages you to add content into the code. This means that content changes require a full testing release cycle. Not something to take on lightly. </li>\n<li>That only expert coders can make changes to content if markup in code (that's a HTML jockeys job)</li>\n<li>Adding HTML ('element.innerHTML=foo') to a page resets all the event listeners. </li>\n<li>Did I say it was SLOW....</li>\n</ol>\n\n<p>You should use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\">template</a> element so you can store the HTML on the page where it belongs. See rewrite</p>\n\n<h2>One handler.</h2>\n\n<p>I don't know how many cells you have on the page, but you add an event handler for each (even the ones that can not be clicked)</p>\n\n<p>You can use a single event listener that accepts a click on the table. You then use the event object passed to the listener to workout what to do with that click.</p>\n\n<h2>Granular code is good code.</h2>\n\n<p>You have one big function that does everything. This is not good as it make the code harder to read, debug, and most important modify.</p>\n\n<p>Break the code into discrete functions that have a very clear job to do. Use functions to replace repeated sections of similar code.</p>\n\n<p>The general rules of thumb for functions is</p>\n\n<ol>\n<li>Longer than a page is too long.</li>\n<li>Does more than one thing? Would be better as two functions.</li>\n<li>Don't go function crazy, creating a one line function used only once is too granular. A function should make the code smaller.</li>\n</ol>\n\n<h2>Rewrite</h2>\n\n<p>As you call <code>swal</code> that expects markup I do not clone the template and just add the data to the elements. When all data elements are filled I then get the templates <code>innerHTML</code> that is passed to the function <code>swal</code> </p>\n\n<p>However you should clone the template and add it directly to the page. Depending on what <code>swal</code> does of course.</p>\n\n<p>I could not see any need for jQuery and added a helper <code>queryDOM</code> to make DOM API calls a little less verbose.</p>\n\n<p>There is only one event listener on the table and it checks the target element for the added property <code>templateType</code> If the element has that property then it is processed.</p>\n\n<p>I am also assuming that the number of cells are small (less than a few 100). If not then you should scan the cells (in function <code>addBandClick</code>) using a timeout event (a few at a time) so that you do not block the page.</p>\n\n<p>The named items are taken from the template element as a data attribute <code>dataset.itemNames</code> however you could extract those names from the template elements saving some duplication in the markup.</p>\n\n<p>Note this may not work as the click listener will be removed if you add any content as markup.</p>\n\n<pre><code>const queryDOM = (qStr, element = document) =&gt; element.querySelector(qStr);\nfunction itemText(row, name) {\n const cell = queryDOM(\".\" + name, row);\n const text = cell ? cell.textContent : \"\"\n return name === \"prize\" ? getOrdinal(text) : text;\n}\nfunction bandHTML(cell) {\n const template = queryDOM(\"#template\" + cell.templateType);\n for (const name of template.dataset.itemNames.split(\",\")) { \n const element = queryDOM(`span [data-name=\"${name}\"]`, template);\n element.textContent = itemText(cell.closestRow, name);\n }\n return template.innerHTML;\n}\nfunction bandClicked(event) {\n if (event.target.templateType) {\n swal({title: 'Point Breakdown', html: bandHTML(event.target)});\n }\n}\nfunction findClickableCells(table) {\n for (const row of table.rows) {\n for (const cell of row.cells) {\n if (cell.cellIndex === 7 &amp;&amp; !queryDOM(\"i\",cell)) {\n const year = Number(itemText(row, \"year\"));\n const costume = itemText(row, \"costume\") !== \"\";\n let type;\n if (year &gt; 1991 &amp;&amp; costume) { type = \"A\" }\n else if (costume) { type = \"B\" }\n else if (itemText(row, \"mp\") !== \"\") { type = \"C\" } \n if (type) {\n cell.templateType = type; // Must have, to be clickable\n cell.classList.add(\"can-click\");\n ceil.closestRow = row;\n } else {\n cell.title = `No point breakdowns for ${year} are available.`;\n }\n }\n }\n }\n}\n\nconst table = queryDOM(\"#bands\");\nif (table) { \n findClickableCells(table);\n table.addEventListener(\"click\", bandClicked);\n}\n</code></pre>\n\n<p>CSS class so that the client has feedback indicating what can be clicked.</p>\n\n<pre><code>.can-click { cursor: pointer; }\n</code></pre>\n\n<p>HTML template example. You would create one for each display type. eg <code>id=\"templateA\"</code>, <code>templateB</code>, <code>templateC</code></p>\n\n<pre><code>&lt;template id=\"templateA\" data-item-names=\"year,mp,costume,band,prize,band,ge_music,ge_visual,total,costumer,designer,arranger,choreographer\"&gt; \n &lt;h3&gt;&lt;span data-name=\"band\"&gt;&lt;/span&gt; &lt;span data-name=\"year\"&gt;&lt;/span&gt;&lt;/h3&gt;\n &lt;i&gt;&lt;span data-name=\"prize\" Prize&lt;/i&gt;&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Music:&lt;/b&gt; &lt;span data-name=\"ge_music\"&gt;&lt;/span&gt;&lt;br&gt;\n &lt;b&gt;Presentation:&lt;/b&gt; &lt;span data-name=\"ge_visual\"&gt;&lt;/span&gt;&lt;br&gt;\n &lt;b&gt;Costume:&lt;/b&gt; &lt;span data-name=\"costume\"&gt;&lt;/span&gt;&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Total Points: &lt;span data-name=\"total\"&gt;&lt;/span&gt;&lt;br&gt;&lt;br&gt;\n &lt;b&gt;Costumer:&lt;/b&gt; &lt;span data-name=\"costumer\"&gt;&lt;/span&gt;&lt;br&gt;\n &lt;b&gt;Costume/Set Designer:&lt;/b&gt; &lt;span data-name=\"designer\"&gt;&lt;/span&gt;&lt;br&gt;\n &lt;b&gt;Music Arranger:&lt;/b&gt; &lt;span data-name=\"arranger\"&gt;&lt;/span&gt;&lt;br&gt;\n &lt;b&gt;Choreographer:&lt;/b&gt; &lt;span data-name=\"choreographer\"&gt;&lt;/span&gt;&lt;br&gt;\n&lt;/template&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:41:09.497", "Id": "407244", "Score": "0", "body": "@FrankDoe I would not expect it to run as it is incomplete (only has one template), likely has one or two typos that creeped in (There is nothing to test it with),. It is meant to be an example and not a a copy paste solution" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T03:43:29.320", "Id": "210625", "ParentId": "210576", "Score": "1" } } ]
{ "AcceptedAnswerId": "210579", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T00:57:17.607", "Id": "210576", "Score": "3", "Tags": [ "javascript", "jquery", "html", "formatting", "dom" ], "Title": "Displaying information extracted from an HTML table" }
210576
<p>Someone in this thread said I could ask for a review of my revision: <a href="https://codereview.stackexchange.com/questions/210217/ncurses-tic-tac-toe-with-simplistic-ai">Ncurses Tic Tac Toe with simplistic AI</a></p> <p>I re-wrote it from scratch using the suggestions from the answers. In particular I did the following:</p> <ol> <li><p>I got rid of Global Variables. For the few global constants I used <code>#defines</code> instead.</p></li> <li><p>I used arrays instead of lists of numbered variables, as suggested.</p></li> <li><p>Although it was not suggested I do so, I did improve the AI. This is the main reason that it is not shorter I think. </p></li> </ol> <p>There is one set of functions in particular that I think I could have combined into one function with a switch, during the AI Logic phase. I commented them so in the code and that's something I'd definitely like some feedback on how to do.</p> <p>I'd like to thank everyone in the previous thread for their tips and suggestions. There are some I did not follow, and for different reasons:</p> <ol> <li><p>I did not stop using <code>rand()</code> because it seems random enough for my purposes. I did a test on my own using 10,000 attempts and checked how often it picked each number between 0 and 99 and it was plenty random enough. So for this project I just kept using it. For those who still suggest I use a different random function, though, I am open to suggestions on how to best do that. I wouldn't mind making my OWN random function and would be stoked on tips for doing that. It's hard to imagine how I could improve even on rand() though.</p></li> <li><p>I wanted to use Structs to imitate OOP for the tile spaces but could not quite wrap my head around how to do so. In Python that kind of thing would be trivial but in C it's not easy for me to understand. Tips on how I could integrate Structs into this to get some kind of OOP would be really welcome.</p></li> </ol> <p>Note on AI: I made it much tougher this time. It will beat a human player most of the time. It would beat a human every single time (ot tie) if I did not intentionally build in a "fart" function that causes it to fail a certain percentage of the time.</p> <p>Note on the code itself: Anyone who wants to use this for their own purposes is more than welcome. Although I am super proud of it I recognize that it is amateur stuff. If anyone wants to play some tic tac toe or can think of a use for this themselves they are more than welcome to it. It should compile pretty easily on most linux systems if you have ncurses.</p> <p>Note on commenting: My comment style was a cause for concern from some of the reviewers in the other thread so I changed it up a bit. I fear it might be too verbose but I wanted it to be easy for people who aren't too familiar with ncurses to follow along.</p> <p>Note on Length: This is the real failing here. Although I implemented many of the suggestions from the other thread my code is actually longer... not shorter. There's at least one set of functions I can probably combine, but how else can I shorten it up?</p> <p>As before, any and all comments and suggestions are welcome. I want to nail down a solid coding style with simple projects like this before moving on to more complex projects in this language. Thank you! Without further ado, here is the code:</p> <pre><code>// tic tac toe v2 using suggestions from Stack Exchange for better style // Minus the struct stuff which I don't quite understand just yet. // ncurses for, well, ncurses #include &lt;ncurses.h&gt; // time for the random seed #include &lt;time.h&gt; // string.h for strlen() #include &lt;string.h&gt; // stdlib and stdio because why not #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; // ctype.h for toupper() #include &lt;ctype.h&gt; // #define's for the COLOR_PAIRs #define X_COLOR 1 #define O_COLOR 2 #define BG_COLOR 3 // #defines used as a global constant #define num_spaces 9 // Function Declarations void init_spaces(char *space_ptr); void paint_board(char playable_spaces[num_spaces]); void take_turn(char side, char *space_ptr, char playable_spaces[num_spaces]); void victory_splash(int game_over_state); void paint_background(); void player_turn(char *space_ptr, char playable_spaces[num_spaces], char side); void ai_turn(char *space_ptr, char playable_spaces[num_spaces], char side); void set_color_ai_side(char ai_side); void set_color_side(char side); int main_menu(); int evaluate_board(char playable_spaces[num_spaces]); int spaces_left(char playable_spaces[num_spaces]); int ai_fart(const int chance_to_fart); int pick_random_space(char playable_spaces[num_spaces]); int check_for_winning_move(char playable_spaces[num_spaces], char ai_side); int check_for_block(char playable_spaces[num_spaces], char side); int check_for_2_space_path(char playable_spaces[num_spaces], char ai_side); char pick_side(); int main(){ // To-Do: Try the time(NULL) method for srand initialization and see if it works the same time_t t; srand((unsigned) time(&amp;t)); char playable_spaces[num_spaces] = {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}; char *space_ptr = &amp;playable_spaces[0]; // Game over splash char game_over_str[] = " Game Over! Any key to continue... "; char go_padding[] = " "; int game_over_len = strlen(game_over_str); int row, col, x, y; //curses init initscr(); cbreak(); keypad(stdscr, 1); curs_set(0); start_color(); init_pair(X_COLOR, COLOR_CYAN, COLOR_BLACK); init_pair(O_COLOR, COLOR_GREEN, COLOR_BLACK); init_pair(BG_COLOR, COLOR_YELLOW, COLOR_BLACK); noecho(); // Main Menu outer loop int running = 1; while(running){ curs_set(0); // Main menu function quits or continues running = main_menu(); // In-Game inner loop if(running == 0){ break; } int playing = 1; while(playing){ // Init all spaces to blank init_spaces(space_ptr); // Player picks their side. char side = pick_side(); // The inner, inner turn loop int turning = 1; while(turning){ int game_over = 0; // Paint the board state as it is that turn paint_board(playable_spaces); // Function that governs the turn cycle take_turn(side, space_ptr, playable_spaces); // Evaluate the board for game over state game_over = evaluate_board(playable_spaces); if(game_over &gt; 0){ // paint the board with a splash on game over // so the player can evaluate the board for a moment paint_board(playable_spaces); getmaxyx(stdscr, row, col); y = row / 2 + 6; x = col / 2 - game_over_len / 2; attron(COLOR_PAIR(BG_COLOR)); mvprintw(y++, x, go_padding); mvprintw(y++, x, game_over_str); mvprintw(y, x, go_padding); refresh(); getch(); // call victory_splash with int game_over as a parameter // 1 = X wins, 2 = O wins, 3 = Tie victory_splash(game_over); // Reset the turning and playing loops to effectively start over turning = 0; playing = 0; } } } } // end curses endwin(); return 0; } void init_spaces(char *space_ptr){ // init all the spaces to ' '; int i; for(i = 0; i &lt; 9; i++){ *space_ptr = ' '; space_ptr++; } } void paint_board(char playable_spaces[num_spaces]){ // paint the board and the playable spaces clear(); paint_background(); char break_lines[] = " ------- "; char play_lines[] = " | | | | "; char padding[] = " "; int row, col, x, y; getmaxyx(stdscr, row, col); y = row / 2 - 4; int len; len = strlen(padding); x = col / 2 - len / 2; int k; const int num_lines = 9; attron(COLOR_PAIR(BG_COLOR)); for(k = 0; k &lt; num_lines; k++){ // Paint the board itself without the pieces if(k == 0 || k == num_lines - 1){ mvprintw(y + k, x, padding); }else{ if(k % 2 == 0){ mvprintw(y + k, x, play_lines); }else{ mvprintw(y + k, x, break_lines); } } } attroff(COLOR_PAIR(BG_COLOR)); // insert Xs and Os: // First set the dynamic x and y coordinates based on terminal size int playable_x[num_spaces] = {x+2, x+4, x+6, x+2, x+4, x+6, x+2, x+4, x+6}; int playable_y[num_spaces] = {y+2, y+2, y+2, y+4, y+4, y+4, y+6, y+6, y+6}; for(k = 0; k &lt; num_spaces; k++){ // For each of the playable spaces, first set the color if(playable_spaces[k] == 'O'){ attron(COLOR_PAIR(O_COLOR)); }else if(playable_spaces[k] == 'X'){ attron(COLOR_PAIR(X_COLOR)); }else{ attron(COLOR_PAIR(BG_COLOR)); } // then insert the char for that space into the proper spot on the terminal mvaddch(playable_y[k], playable_x[k], playable_spaces[k]); } // refresh the screen refresh(); } void take_turn(char side, char *space_ptr, char playable_spaces[num_spaces]){ // using "side" to determine the order, call the functions to play a whole turn if(side == 'X'){ player_turn(space_ptr, playable_spaces, side); paint_board(playable_spaces); if(spaces_left(playable_spaces)){ if(!(evaluate_board(playable_spaces))){ ai_turn(space_ptr, playable_spaces, side); paint_board(playable_spaces); } } }else if(side == 'O'){ ai_turn(space_ptr, playable_spaces, side); paint_board(playable_spaces); if(spaces_left(playable_spaces)){ if(!(evaluate_board(playable_spaces))){ player_turn(space_ptr, playable_spaces, side); paint_board(playable_spaces); } } } } int main_menu(){ clear(); // Takes user input and returns an int that quits or starts a game int row, col, x, y; char error_string[] = " Invalid Input! Any key to try again... "; int error_str_len = strlen(error_string); char str1[] = " NCURSES TIC TAC TOE (v2) "; char padding[] = " "; char str2[] = " (P)lay or (Q)uit? "; int len = strlen(str1); paint_background(); getmaxyx(stdscr, row, col); y = row / 2 - 2; x = col / 2 - len / 2; mvprintw(y++, x, padding); mvprintw(y++, x, str1); mvprintw(y++, x, padding); mvprintw(y++, x, str2); mvprintw(y++, x, padding); int input; refresh(); // get user input and return it input = toupper(getch()); if(input == 'P'){ return 1; }else if(input == 'Q'){ return 0; }else{ // call the function again if the input is bad x = col / 2 - error_str_len / 2; mvprintw(++y, x, error_string); getch(); main_menu(); } } int evaluate_board(char playable_spaces[num_spaces]){ // Evaluates the state of the playable spaces and either does nothing // or ends the game. // Check all the possible winning combinations: if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[1] == 'X' &amp;&amp; playable_spaces[2] == 'X'){ return 1; }else if(playable_spaces[3] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[5] == 'X'){ return 1; }else if(playable_spaces[6] == 'X' &amp;&amp; playable_spaces[7] == 'X' &amp;&amp; playable_spaces[8] == 'X'){ return 1; }else if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[3] == 'X' &amp;&amp; playable_spaces[6] == 'X'){ return 1; }else if(playable_spaces[1] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[7] == 'X'){ return 1; }else if(playable_spaces[2] == 'X' &amp;&amp; playable_spaces[5] == 'X' &amp;&amp; playable_spaces[8] == 'X'){ return 1; }else if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[8] == 'X'){ return 1; }else if(playable_spaces[2] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[6] == 'X'){ return 1; }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[1] == 'O' &amp;&amp; playable_spaces[2] == 'O'){ return 2; }else if(playable_spaces[3] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[5] == 'O'){ return 2; }else if(playable_spaces[6] == 'O' &amp;&amp; playable_spaces[7] == 'O' &amp;&amp; playable_spaces[8] == 'O'){ return 2; }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[3] == 'O' &amp;&amp; playable_spaces[6] == 'O'){ return 2; }else if(playable_spaces[1] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[7] == 'O'){ return 2; }else if(playable_spaces[2] == 'O' &amp;&amp; playable_spaces[5] == 'O' &amp;&amp; playable_spaces[8] == 'O'){ return 2; }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[8] == 'O'){ return 2; }else if(playable_spaces[2] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[6] == 'O'){ return 2; }else{ // Check all spaces for a tie int hits = 0; int i; for(i = 0; i &lt; num_spaces; i++){ if(playable_spaces[i] != ' '){ hits++; } } if(hits &gt;= num_spaces){ return 3; }else{ return 0; } } } char pick_side(){ // Takes user input and returns the chosen side clear(); paint_background(); int row, col, x, y; char str1[] = " Press 'X' for X, 'O' for O, or 'R' for random! "; char str2[] = " Good choice! Any key to continue... "; char padding[] = " "; char err_str[] = " Invalid input! Any key to continue... "; int len = strlen(str1); getmaxyx(stdscr, row, col); y = row / 2 - 2; x = col / 2 - len / 2; mvprintw(y++, x, padding); mvprintw(y++, x, str1); mvprintw(y++, x, padding); int input; int pick; refresh(); // Get user input for picking a side. 'R' is random. input = toupper(getch()); if(input == 'X' || input == 'O'){ mvprintw(y, x, str2); refresh(); getch(); return (char) input; }else if(input == 'R'){ pick = rand() % 2; if(pick == 0){ input = 'X'; }else if(pick == 1){ input = 'O'; } mvprintw(y, x, str2); refresh(); getch(); return (char) input; }else{ // Call the function again on bad input mvprintw(y, x, err_str); refresh(); getch(); pick_side(); } } void victory_splash(int game_over_state){ // Takes the game over state and creates a victory splash char padding[] = " "; char *str1 = " X Wins! "; char *str2 = " O Wins! "; char str3[] = " any key to continue... "; char *str4 = " A tie game! "; int len = strlen(padding); char *vic_pointer = NULL; // To avoid code duplication, use a pointer to pick the right string if(game_over_state == 1){ vic_pointer = str1; }else if(game_over_state == 2){ vic_pointer = str2; }else if(game_over_state == 3){ vic_pointer = str4; } clear(); paint_background(); int row, col, x, y; getmaxyx(stdscr, row, col); y = row / 2 - 2; x = col / 2 - len / 2; mvprintw(y++, x, padding); mvprintw(y++, x, vic_pointer); mvprintw(y++, x, padding); mvprintw(y, x, str3); refresh(); getch(); } void paint_background(){ // Paints an elaborate flashy background int row, col, x, y; int pick; getmaxyx(stdscr, row, col); for(y = 0; y &lt;= row; y++){ for(x = 0; x &lt;= col; x++){ pick = rand() % 3; if(pick == 0){ attron(COLOR_PAIR(X_COLOR)); mvprintw(y, x, "X"); attroff(COLOR_PAIR(X_COLOR)); }else if(pick == 1){ attron(COLOR_PAIR(O_COLOR)); mvprintw(y, x, "O"); attroff(COLOR_PAIR(O_COLOR)); }else if(pick == 2){ attron(COLOR_PAIR(BG_COLOR)); mvprintw(y, x, " "); attroff(COLOR_PAIR(BG_COLOR)); } } } refresh(); } void player_turn(char *space_ptr, char playable_spaces[num_spaces], char side){ // Function for the player turn char padding[] = " "; char str1[] = " Use arrow keys to move and 'P' to place! "; char str2[] = " Good move! "; char str3[] = " Invalid input! "; char str4[] = " You can't move that way! "; char str5[] = " Space already occupied! "; int len = strlen(padding); int row, col, x, y; getmaxyx(stdscr, row, col); const int board_line_len = 9; const int board_lines = 9; y = row / 2 - board_line_len / 2; x = col / 2 - board_line_len / 2; // Use the same method of dynamically measuring where the spaces are at using // terminal size as in the paint_board() function. int playable_x[num_spaces] = {x+2, x+4, x+6, x+2, x+4, x+6, x+2, x+4, x+6}; int playable_y[num_spaces] = {y+2, y+2, y+2, y+4, y+4, y+4, y+6, y+6, y+6}; // The variables and mvprintw functions for the "info line" const int info_line_y = (row / 2 - board_lines / 2) + 10; const int info_line_x = col / 2 - len / 2; mvprintw(info_line_y - 1, info_line_x, padding); mvprintw(info_line_y, info_line_x, str1); mvprintw(info_line_y + 1, info_line_x, padding); // Using a loop and pointers to collect user input int moving = 1; int input; int *pos_x = &amp;playable_x[0]; int *pos_y = &amp;playable_y[0]; move(*pos_y, *pos_x); curs_set(1); refresh(); while(moving){ // For each movement key, if the move is valid, use pointer // arithmetic to mov pos_x and pos_y around. input = toupper(getch()); if(input == KEY_UP){ if(*pos_y != playable_y[0]){ pos_y -= 3; move(*pos_y, *pos_x); refresh(); }else{ mvprintw(info_line_y, info_line_x, str4); move(*pos_y, *pos_x); refresh(); } }else if(input == KEY_DOWN){ if(*pos_y != playable_y[6]){ pos_y += 3; move(*pos_y, *pos_x); refresh(); }else{ mvprintw(info_line_y, info_line_x, str4); move(*pos_y, *pos_x); refresh(); } }else if(input == KEY_LEFT){ if(*pos_x != playable_x[0]){ pos_x -= 1; move(*pos_y, *pos_x); refresh(); }else{ mvprintw(info_line_y, info_line_x, str4); move(*pos_y, *pos_x); refresh(); } }else if(input == KEY_RIGHT){ if(*pos_x != playable_x[2]){ pos_x += 1; move(*pos_y, *pos_x); refresh(); }else{ mvprintw(info_line_y, info_line_x, str4); move(*pos_y, *pos_x); refresh(); } }else if(input == 'P'){ // I wanted to use KEY_ENTER instead of 'P' but it would not work // for some reason. When the user presses 'P' it checks where the // cursor is and sets the space_ptr to the appropriate index in the // playable_spaces array. if(*pos_y == playable_y[0] &amp;&amp; *pos_x == playable_x[0]){ space_ptr = &amp;playable_spaces[0]; }else if(*pos_y == playable_y[1] &amp;&amp; *pos_x == playable_x[1]){ space_ptr = &amp;playable_spaces[1]; }else if(*pos_y == playable_y[2] &amp;&amp; *pos_x == playable_x[2]){ space_ptr = &amp;playable_spaces[2]; }else if(*pos_y == playable_y[3] &amp;&amp; *pos_x == playable_x[3]){ space_ptr = &amp;playable_spaces[3]; }else if(*pos_y == playable_y[4] &amp;&amp; *pos_x == playable_x[4]){ space_ptr = &amp;playable_spaces[4]; }else if(*pos_y == playable_y[5] &amp;&amp; *pos_x == playable_x[5]){ space_ptr = &amp;playable_spaces[5]; }else if(*pos_y == playable_y[6] &amp;&amp; *pos_x == playable_x[6]){ space_ptr = &amp;playable_spaces[6]; }else if(*pos_y == playable_y[7] &amp;&amp; *pos_x == playable_x[7]){ space_ptr = &amp;playable_spaces[7]; }else if(*pos_y == playable_y[8] &amp;&amp; *pos_x == playable_x[8]){ space_ptr = &amp;playable_spaces[8]; } // Then checks to see if that space is empty. // If so it sets the color properly and then places the piece. if(*space_ptr == ' '){ if(side == 'X'){ attron(COLOR_PAIR(X_COLOR)); mvaddch(*pos_y, *pos_x, 'X'); attron(COLOR_PAIR(BG_COLOR)); *space_ptr = 'X'; }else if(side == 'O'){ attron(COLOR_PAIR(O_COLOR)); mvaddch(*pos_y, *pos_x, 'O'); attron(COLOR_PAIR(BG_COLOR)); *space_ptr = 'O'; } refresh(); moving = 0; }else{ mvprintw(info_line_y, info_line_x, str5); move(*pos_y, *pos_x); refresh(); } }else{ mvprintw(info_line_y, info_line_x, str3); move(*pos_y, *pos_x); refresh(); } } } ////////////////////////////////////////////////////////////////////////////////////// // Begin AI Logic //////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// void ai_turn(char *space_ptr, char playable_spaces[num_spaces], char side){ // wrapper for the AI turn /* Note: Since it is easy to accidentally create an unbeatable AI for tic tac toe I am building into the AI the chance for it to not make the optimal move. This intentional fuzziness will be built into the functions that check for avaialable spaces. When they find an optimal move they may just decide to return 0 anyway. P-Code: if center square not taken, take center square 70% of the time; else: if opponent about to win, block them 90% of the time; elif self about to win take winning spot 90% of the time; else pick a random open spot; */ // The chances for the AI to blow a move const int chance_to_fart_big_move = 10; const int chance_to_fart_center = 30; // Picking the character for the AI to use in its calculations char ai_side; if(side == 'X'){ ai_side = 'O'; }else if(side == 'O'){ ai_side = 'X'; } // Check the board state with a few functions. // These all return 0 if FALSE and the number of a valid // index to move into if TRUE int can_block_opponent = check_for_block(playable_spaces, side); int can_winning_move = check_for_winning_move(playable_spaces, ai_side); // Flow through the decision making logic applying the functions and checking for a fart int thinking = 1; int picked_space; while(thinking){ if(playable_spaces[4] == ' '){ if(!(ai_fart(chance_to_fart_center))){ picked_space = 4; thinking = 0; break; } } if(can_winning_move){ if(!(ai_fart(chance_to_fart_big_move))){ picked_space = can_winning_move; thinking = 0; }else{ picked_space = pick_random_space(playable_spaces); thinking = 0; } }else if(can_block_opponent){ if(!(ai_fart(chance_to_fart_big_move))){ picked_space = can_block_opponent; thinking = 0; }else{ picked_space = pick_random_space(playable_spaces); thinking = 0; } }else{ picked_space = pick_random_space(playable_spaces); thinking = 0; } } space_ptr = &amp;playable_spaces[picked_space]; if(ai_side == 'X'){ attron(COLOR_PAIR(X_COLOR)); }else if(ai_side == 'O'){ attron(COLOR_PAIR(O_COLOR)); } *space_ptr = ai_side; attron(COLOR_PAIR(BG_COLOR)); } int ai_fart(const int chance_to_fart){ // Takes the fart chance and returns 1 if the AI blows the move, 0 otherwise int roll; roll = rand() % 100 + 1; if(roll &lt; chance_to_fart){ return 1; }else{ return 0; } } int pick_random_space(char playable_spaces[num_spaces]){ // Returns a random open space on the board int roll; int rolling = 1; int pick; while(rolling){ roll = rand() % num_spaces; if(playable_spaces[roll] == ' '){ pick = roll; rolling = 0; }else{ continue; } } return pick; } int check_for_winning_move(char playable_spaces[num_spaces], char ai_side){ // Checks to see if the AI can win the game with a final move and returns the // index of the valid move if TRUE, returns 0 if FALSE int space; int pick; int picked = 0; for(space = 0; space &lt; num_spaces; space++){ // For each space: Check to see if it is a potential winning space and if so // switch "picked" to 1 and set "pick" to the winning index switch(space){ case(0): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[3] == ai_side &amp;&amp; playable_spaces[6] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[8] == ai_side){ pick = space; picked = 1; } } break; case(1): if(playable_spaces[space] == ' '){ if(playable_spaces[0] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[7] == ai_side){ pick = space; picked = 1; } } break; case(2): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == ai_side &amp;&amp; playable_spaces[0] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[6] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[5] == ai_side &amp;&amp; playable_spaces[8] == ai_side){ pick = space; picked = 1; } } break; case(3): if(playable_spaces[space] == ' '){ if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[5] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[0] == ai_side &amp;&amp; playable_spaces[6] == ai_side){ pick = space; picked = 1; } } break; case(4): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == ai_side &amp;&amp; playable_spaces[7] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[3] == ai_side &amp;&amp; playable_spaces[5] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[0] == ai_side &amp;&amp; playable_spaces[8] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[6] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; } } break; case(5): if(playable_spaces[space] == ' '){ if(playable_spaces[8] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[3] == ai_side &amp;&amp; playable_spaces[4] == ai_side){ pick = space; picked = 1; } } break; case(6): if(playable_spaces[space] == ' '){ if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[7] == ai_side &amp;&amp; playable_spaces[8] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[3] == ai_side &amp;&amp; playable_spaces[0] == ai_side){ pick = space; picked = 1; } } break; case(7): if(playable_spaces[space] == ' '){ if(playable_spaces[6] == ai_side &amp;&amp; playable_spaces[8] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[1] == ai_side){ pick = space; picked = 1; } } break; case(8): if(playable_spaces[space] == ' '){ if(playable_spaces[5] == ai_side &amp;&amp; playable_spaces[2] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[4] == ai_side &amp;&amp; playable_spaces[0] == ai_side){ pick = space; picked = 1; }else if(playable_spaces[7] == ai_side &amp;&amp; playable_spaces[6] == ai_side){ pick = space; picked = 1; } } break; } } // return winning index if any if(picked){ return pick; }else{ return 0; } } int check_for_block(char playable_spaces[num_spaces], char side){ // Checks to see if the AI can block the player from winning the game with a final move // and returns the index of the valid move if TRUE, returns 0 if FALSE // Note: I am sure there is a way to combine this this function with the // check_for_winning_move() function in order to avoid code duplication, probably using // one more parameter as a switch of some kind. I'd be open to examples of how to do that. int space; int pick; int picked = 0; for(space = 0; space &lt; num_spaces; space++){ // For each space: Check to see if it is a potential winning space and if so // switch "picked" to 1 and set "pick" to the winning index switch(space){ case(0): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; }else if(playable_spaces[3] == side &amp;&amp; playable_spaces[6] == side){ pick = space; picked = 1; }else if(playable_spaces[4] == side &amp;&amp; playable_spaces[8] == side){ pick = space; picked = 1; } } break; case(1): if(playable_spaces[space] == ' '){ if(playable_spaces[0] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; }else if(playable_spaces[4] == side &amp;&amp; playable_spaces[7] == side){ pick = space; picked = 1; } } break; case(2): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == side &amp;&amp; playable_spaces[0] == side){ pick = space; picked = 1; }else if(playable_spaces[4] == side &amp;&amp; playable_spaces[6] == side){ pick = space; picked = 1; }else if(playable_spaces[5] == side &amp;&amp; playable_spaces[8] == side){ pick = space; picked = 1; } } break; case(3): if(playable_spaces[space] == ' '){ if(playable_spaces[4] == side &amp;&amp; playable_spaces[5] == side){ pick = space; picked = 1; }else if(playable_spaces[0] == side &amp;&amp; playable_spaces[6] == side){ pick = space; picked = 1; } } break; case(4): if(playable_spaces[space] == ' '){ if(playable_spaces[1] == side &amp;&amp; playable_spaces[7] == side){ pick = space; picked = 1; }else if(playable_spaces[3] == side &amp;&amp; playable_spaces[5] == side){ pick = space; picked = 1; }else if(playable_spaces[0] == side &amp;&amp; playable_spaces[8] == side){ pick = space; picked = 1; }else if(playable_spaces[6] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; } } break; case(5): if(playable_spaces[space] == ' '){ if(playable_spaces[8] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; }else if(playable_spaces[3] == side &amp;&amp; playable_spaces[4] == side){ pick = space; picked = 1; } } break; case(6): if(playable_spaces[space] == ' '){ if(playable_spaces[4] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; }else if(playable_spaces[7] == side &amp;&amp; playable_spaces[8] == side){ pick = space; picked = 1; }else if(playable_spaces[3] == side &amp;&amp; playable_spaces[0] == side){ pick = space; picked = 1; } } break; case(7): if(playable_spaces[space] == ' '){ if(playable_spaces[6] == side &amp;&amp; playable_spaces[8] == side){ pick = space; picked = 1; }else if(playable_spaces[4] == side &amp;&amp; playable_spaces[1] == side){ pick = space; picked = 1; } } break; case(8): if(playable_spaces[space] == ' '){ if(playable_spaces[5] == side &amp;&amp; playable_spaces[2] == side){ pick = space; picked = 1; }else if(playable_spaces[4] == side &amp;&amp; playable_spaces[0] == side){ pick = space; picked = 1; }else if(playable_spaces[7] == side &amp;&amp; playable_spaces[6] == side){ pick = space; picked = 1; } } break; } } // return winning index if any if(picked){ return pick; }else{ return 0; } } /////////////////////////////////////////////////////////////////////////////////// // End AI Logic /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// int spaces_left(char playable_spaces[num_spaces]){ // Returns 0 if no spaces left int hits = 0; int k; for(k = 0; k &lt; num_spaces; k++){ if(playable_spaces[k] == ' '){ hits++; } } return hits; } </code></pre> <p>Edit: Thanks guys! So many good tips. We are getting closer to a good style! I will re-write this again for sure. My goal is to develop a style with this project that I can carry forward into more complicated ones and the critique I have received is invaluable. Don't stop it coming just because I marked an answer! I've already begun on Tic Tac Toe v3 using many of these suggestions.</p> <p>If I may ask for something specific I would ask that someone go in to detail about how I can use STRUCTS to emulate OOP for my tile spaces. I larger projects (say, a Roguelike) I would want to use Objects to represent the tiles. How would I go about doing that in C, with Structs? </p> <p>Edit 2: One of the people who gave an answer asked me to put this up on GitHub so here you go: <a href="https://github.com/JanitorsBucket/tic_tac_toe_NCURSES_v2" rel="nofollow noreferrer">https://github.com/JanitorsBucket/tic_tac_toe_NCURSES_v2</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T16:04:55.997", "Id": "407109", "Score": "2", "body": "I finally decided to compile and run this. Nice background! I might submit a separate answer with a \"suggested implementation\"." } ]
[ { "body": "<p><strong>I've made this Community Wiki because my answer revolves around 1 example that those more knowledgeable about C could probably improve and expand. Improvements are welcome!</strong></p>\n\n<h1>Practice DRY code</h1>\n\n<p>There's one piece of feedback you received a bit in your previous review, and I think taking it to heart would improve your coding style tremendously: practice <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> code. You should never have code that could be basically copy-pasted with only a few value changes. Learning how to avoid this will make your code shorter, easier to read, and easier to maintain. You can often avoid repetition by modularizing your code further, usually by making more functions. </p>\n\n<p>To demonstrate what I mean, let's take a section of your code as a case study:</p>\n\n<h2>Case study: win-checking conditionals</h2>\n\n<pre><code> if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[1] == 'X' &amp;&amp; playable_spaces[2] == 'X'){\n return 1;\n }else if(playable_spaces[3] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[5] == 'X'){\n return 1;\n }else if(playable_spaces[6] == 'X' &amp;&amp; playable_spaces[7] == 'X' &amp;&amp; playable_spaces[8] == 'X'){\n return 1;\n }else if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[3] == 'X' &amp;&amp; playable_spaces[6] == 'X'){\n return 1;\n }else if(playable_spaces[1] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[7] == 'X'){\n return 1;\n }else if(playable_spaces[2] == 'X' &amp;&amp; playable_spaces[5] == 'X' &amp;&amp; playable_spaces[8] == 'X'){\n return 1;\n }else if(playable_spaces[0] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[8] == 'X'){\n return 1;\n }else if(playable_spaces[2] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[6] == 'X'){\n return 1;\n }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[1] == 'O' &amp;&amp; playable_spaces[2] == 'O'){\n return 2;\n }else if(playable_spaces[3] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[5] == 'O'){\n return 2;\n }else if(playable_spaces[6] == 'O' &amp;&amp; playable_spaces[7] == 'O' &amp;&amp; playable_spaces[8] == 'O'){\n return 2;\n }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[3] == 'O' &amp;&amp; playable_spaces[6] == 'O'){\n return 2;\n }else if(playable_spaces[1] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[7] == 'O'){\n return 2;\n }else if(playable_spaces[2] == 'O' &amp;&amp; playable_spaces[5] == 'O' &amp;&amp; playable_spaces[8] == 'O'){\n return 2;\n }else if(playable_spaces[0] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[8] == 'O'){\n return 2;\n }else if(playable_spaces[2] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[6] == 'O'){\n return 2;\n }\n</code></pre>\n\n<p>Without even comprehending what this code does, I can tell it's not quite right because it has too much repetition.</p>\n\n<p>If you have multiple conditional branches that return the same thing, you can combine them with the <code>||</code> or operator (only the <code>'X'</code> code is shown below):</p>\n\n<pre><code> if((playable_spaces[0] == 'X' &amp;&amp; playable_spaces[1] == 'X' &amp;&amp; playable_spaces[2] == 'X')\n || (playable_spaces[3] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[5] == 'X')\n || (playable_spaces[6] == 'X' &amp;&amp; playable_spaces[7] == 'X' &amp;&amp; playable_spaces[8] == 'X')\n || (playable_spaces[0] == 'X' &amp;&amp; playable_spaces[3] == 'X' &amp;&amp; playable_spaces[6] == 'X')\n || (playable_spaces[1] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[7] == 'X')\n || (playable_spaces[2] == 'X' &amp;&amp; playable_spaces[5] == 'X' &amp;&amp; playable_spaces[8] == 'X')\n || (playable_spaces[0] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[8] == 'X')\n || (playable_spaces[2] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[6] == 'X')) {\n return 1;\n }\n</code></pre>\n\n<p>I've skipped reproducing the 'O' code because it's identical to the 'X' code aside from a change from 'O'. This is also unnecessary repetition. You could make a function that takes 'X' and 'O' as char arguments, and returns the above <code>||</code> sequence.</p>\n\n<h2>A simpler way</h2>\n\n<p>First, let's assume we have some constants:</p>\n\n<pre><code>#define SIDE_LEN 3\n#define NUM_SQUARES (SIDE_LEN*SIDE_LEN)\n</code></pre>\n\n<p>Now let's create a <code>Board</code> structure that is defined like this:</p>\n\n<pre><code>typedef struct board {\n char spaces[NUM_SQUARES];\n int available;\n} Board;\n</code></pre>\n\n<p>The <code>spaces</code> contain the tokens for either <code>X</code> or <code>0</code> or empty. The value <code>available</code> simply holds the number of empty squares. Initialization of this structure is obvious and should be done before each game.</p>\n\n<p>Now we can easily create a helper function:</p>\n\n<pre><code>char board_gettoken(const Board *b, int row, int col) {\n return b-&gt;spaces[row + col * SIDE_LEN];\n}\n</code></pre>\n\n<p>If we were describing how to win to a child, we might say that anywhere we get three in a row, a column or along the diagonal, it's a win. If all of the squares are filled (that is, <code>available == 0</code>) and there isn't a winner, it's a tie. Finally, note that only the player who just made a move can possibly win. We can use these simple facts to write a very simple <code>board_evaluate</code> function:</p>\n\n<pre><code>// given that `token` just moved, return \n// 0 if no winner\n// 1 if token just won\n// 2 if tie\nint board_evaluate(const Board *b, char token) {\n bool diag_winner = true;\n bool rev_diag_winner = true;\n for (int i=0; i &lt; SIDE_LEN; ++i) {\n diag_winner &amp;= board_gettoken(b, i, i) == token;\n rev_diag_winner &amp;= board_gettoken(b, i, SIDE_LEN-1-i) == token;\n }\n if (diag_winner || rev_diag_winner) {\n return 1;\n }\n for (int i=0; i &lt; SIDE_LEN; ++i) {\n bool row_winner = true;\n bool col_winner = true;\n for (int j=0; j &lt; SIDE_LEN; ++j) {\n col_winner &amp;= board_gettoken(b, i, j) == token;\n row_winner &amp;= board_gettoken(b, j, i) == token;\n }\n if (row_winner || col_winner) {\n return 1;\n }\n }\n // must be a non-win or tie\n return b-&gt;available == 0 ? 2 : 0;\n}\n</code></pre>\n\n<p>Finally, note that if we wanted to create 4x4 or 9x9 version, all that would need to be changed is the <code>SIDE_LEN</code> constant value. It's also handy to prefix functions that deal with a board with <code>board_</code> so it's easy to see that they are related. In object-oriented language such as C++, these would likely be member functions.</p>\n\n<h2>Using DRY code for a better AI</h2>\n\n<p>One can use the function above to write a faster, better, shorter AI player as well. First, we define another helper function:</p>\n\n<pre><code>int board_makemove(Board *b, int i, int j, char token) {\n board_settoken(b, i, j, token);\n --b-&gt;available;\n return board_evaluate(b, token);\n}\n</code></pre>\n\n<p>When we've made a final selection, this function uses the <code>board_settoken</code> to update the data structure, decrements the available square count and then returns the result of the board evaluation. There's a reason we don't decrement the <code>available</code> count in the <code>board_settoken</code> routine as we'll see in the following function:</p>\n\n<pre><code>int ai_turn(Board *b, char token) {\n const char antitoken = token == 'X' ? 'O' : 'X';\n // first look for a move that would win\n for (int i=0; i &lt; SIDE_LEN; ++i) {\n for (int j=0; j &lt; SIDE_LEN; ++j) {\n if (board_gettoken(b, i, j) == ' ') {\n board_settoken(b, i, j, token);\n int status = board_evaluate(b, token);\n if (status) {\n --b-&gt;available;\n return status;\n } else {\n board_settoken(b, i, j, ' '); // undo move\n }\n }\n }\n }\n // next look for a move that would block\n for (int i=0; i &lt; SIDE_LEN; ++i) {\n for (int j=0; j &lt; SIDE_LEN; ++j) {\n if (board_gettoken(b, i, j) == ' ') {\n board_settoken(b, i, j, antitoken);\n if (board_evaluate(b, antitoken) == 1) {\n return board_makemove(b, i, j, token);\n } else {\n board_settoken(b, i, j, ' '); // undo move\n }\n }\n }\n }\n // look for center\n { \n int i = SIDE_LEN/2;\n if (board_gettoken(b, i, i) == ' ') {\n return board_makemove(b, i, i, token);\n }\n }\n // look for corner \n for (int i=0; i &lt; SIDE_LEN; i += (SIDE_LEN-1)) { \n for (int j=0; j &lt; SIDE_LEN; j += (SIDE_LEN-1)) { \n if (board_gettoken(b, i, j) == ' ') {\n return board_makemove(b, i, j, token);\n }\n }\n }\n // choose first available\n for (int i=0; i &lt; SIDE_LEN; ++i) {\n for (int j=0; j &lt; SIDE_LEN; ++j) {\n if (board_gettoken(b, i, j) == ' ') {\n return board_makemove(b, i, j, token);\n }\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>This is a very simple bit of code, and easy to follow, but it's very competent at playing the game. There are still more opportunities to DRY the code above. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:07:38.167", "Id": "407065", "Score": "0", "body": "I felt that even as I wrote that. The evaluate_board() function was the only one I had to come back and bug fix multiple times. I agree that a loop is probably the way to do it and I'd be interested in some examples. For games with bigger boards I won't ever be able to do it like that. In python I'd just create objects for the tiles and loop over them one by one, calling functions to check nearby spaces. How can I better do that in C?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:21:22.563", "Id": "407068", "Score": "1", "body": "@some_guy632 I'm unfortunately probably not the best person to ask this, because I'm more of a Python programmer than a C programmer, hence the community wiki. I *am* familiar enough with C syntax to be able to edit in an example of doing it with a loop, so I will do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T09:11:39.743", "Id": "407082", "Score": "0", "body": "The more I think about this one the more I want to stick with forward declarations. What if you have functiones that depend on other functions but you coded them in the wrong order? Is there any good reason NOT to forward declare?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T14:41:45.107", "Id": "407097", "Score": "1", "body": "@some_guy632 It's probably better to ask Reinderien, who's actually coded in C. For my part, for code that's restricted to your own file, it's probably better to put a bit of care into ordering your functions so there's no conflicts, before resorting to forward declarations. The reason for this is DRY: copying function declarations twice creates another vector for continuity error, where the forward declaration may go out of sync with the forward declaration. In either case, AFAIK, the worst thing that can happen is a compilation error, so I'm not sure if verbose forward declaring is that bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:55:34.280", "Id": "407108", "Score": "2", "body": "@some_guy632 I think you meant that comment on my answer. You are more than welcome to continue using forward decisions. If you code in the wrong ordwr your compiler will warn you. The more functions you have the more important organizing your code becomes. And forward declarations don't organize things for you they just make it so you don't have to. They have their uses but in this case you are using them as a messy workaround. And header files aren't the same thing as forward declarations." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:01:30.620", "Id": "210585", "ParentId": "210577", "Score": "8" } }, { "body": "<h2>Capitalize your defines</h2>\n\n<pre><code>#define num_spaces 9\n</code></pre>\n\n<p>should have <code>NUM_SPACES</code> instead of <code>num_spaces</code>.</p>\n\n<h2>Identify your local functions</h2>\n\n<p>Tell the compiler when you don't intend to export functions to a different translation unit. Mark all of your functions <code>static</code> except <code>main</code>.</p>\n\n<h2>Const integral args aren't needed</h2>\n\n<p>This:</p>\n\n<pre><code>int ai_fart(const int chance_to_fart);\n</code></pre>\n\n<p>doesn't really need its argument made <code>const</code>. <code>const</code> is most often applied to pointer-type arguments to indicate that the value won't be changed, but for integral types, the caller's copy <em>cannot</em> be changed, so doing this has little value.</p>\n\n<h2>Use real booleans</h2>\n\n<p>There are several variables, including <code>running</code> and <code>turning</code>, that are <code>int</code> but should be boolean. Include <code>stdbool.h</code> for this purpose.</p>\n\n<h2>Use enums for integer signalling values</h2>\n\n<p>In at least one spot (the return value of <code>evaluate_board</code>), you're returning an integer that has special meaning. This is the perfect situation to change the return type from <code>int</code> to an <code>enum</code> type that you <code>typedef</code>, and have both the caller and callee use the enum's named constants to make the code clearer, more meaningful, and (to a certain extent) more able to be statically checked by the compiler.</p>\n\n<h2>Don't separate declaration from initialization</h2>\n\n<p>You do this in several places:</p>\n\n<pre><code>int i;\nfor(i = 0; i &lt; 9; i++){\n *space_ptr = ' ';\n space_ptr++;\n}\n// ...\nint len;\nlen = strlen(padding);\n// ...\nint input;\ninput = toupper(getch());\n</code></pre>\n\n<p>Don't do this. Just use the syntax <code>int input = toupper(getch());</code></p>\n\n<h2>Remove redundant <code>else</code></h2>\n\n<p>Whenever you <code>return</code> in an <code>if</code>, the following code doesn't need an <code>else</code>. So delete <code>else</code> from code like this:</p>\n\n<pre><code>if(input == 'Q'){\n return 0;\n}else{\n// ...\n</code></pre>\n\n<p>This occurs many times throughout your code.</p>\n\n<h2>Use more loops</h2>\n\n<p>Computers are good at repetition. This:</p>\n\n<pre><code>int playable_x[num_spaces] = {x+2, x+4, x+6, x+2, x+4, x+6, x+2, x+4, x+6};\n</code></pre>\n\n<p>should not be initialized in a literal. Initialize it in a loop. The compiler will make the (usually right) decision as to whether the loop should be unrolled.</p>\n\n<p>Similarly, in your <code>evaluate_board</code> function, you have highly repeated code that should be refactored into loops to check <code>playable_spaces</code>.</p>\n\n<p>More code that needs to be a loop -</p>\n\n<pre><code> if(*pos_y == playable_y[0] &amp;&amp; *pos_x == playable_x[0]){\n space_ptr = &amp;playable_spaces[0]; \n // ... \n</code></pre>\n\n<h2>Choose better variable names</h2>\n\n<p>Particularly for <code>str1</code>, <code>str2</code>, etc.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>This block of code:</p>\n\n<pre><code> if(input == KEY_UP){\n if(*pos_y != playable_y[0]){\n pos_y -= 3;\n move(*pos_y, *pos_x);\n refresh();\n }else{\n mvprintw(info_line_y, info_line_x, str4);\n move(*pos_y, *pos_x);\n refresh();\n }\n</code></pre>\n\n<p>is repeated nearly verbatim four times. You should put this into a function. The same goes for your <code>case</code>s in <code>check_for_winning_move</code> and <code>check_for_block</code>.</p>\n\n<h2>Don't hard-code things that should be computed</h2>\n\n<p>For instance, don't store or hard-code \"9\" anywhere. \"9\" is just the game grid width squared, so define the game grid width (3), and then make a convenience <code>#define</code> equal to the game grid width squared.</p>\n\n<h2>Make symbols to explain magic numbers</h2>\n\n<p>For instance, you're using 0 as \"invisible cursor\". It's the fault of <code>ncurses</code> for not giving you a symbol to use, but you can still fix this in your code by doing something like</p>\n\n<pre><code>#define INVISIBLE_CUR 0\n</code></pre>\n\n<h2>Pass arrays as <code>const</code> where appropriate</h2>\n\n<p>Many of your functions accept arrays but don't modify them:</p>\n\n<ul>\n<li><code>spaces_left</code></li>\n<li><code>pick_random_space</code></li>\n<li><code>check_for_winning_move</code></li>\n<li><code>check_for_block</code></li>\n</ul>\n\n<p>The array arguments there should be declared <code>const</code>.</p>\n\n<h2>Use a standard <code>main</code> signature</h2>\n\n<p>i.e.</p>\n\n<pre><code>int main(int argc, char **argv)\n</code></pre>\n\n<h2>Don't abuse loops</h2>\n\n<p>Several of your loops need to die, specifically:</p>\n\n<pre><code>while(playing){\n</code></pre>\n\n<p>That only gets executed once, so kill it.</p>\n\n<pre><code>for(i = 0; i &lt; 9; i++){\n *space_ptr = ' ';\n space_ptr++;\n}\n</code></pre>\n\n<p>This shouldn't exist at all. Call <code>memset</code> instead.</p>\n\n<pre><code>while(thinking)\n</code></pre>\n\n<p>This seems to just be a way to hack in the equivalent of a <code>goto</code>; the loop only executes once. Kill the loop and move its contents to a separate function, so that you can use <code>return</code> for early termination.</p>\n\n<h2>Use boolean expressions directly</h2>\n\n<p>This:</p>\n\n<pre><code>if(roll &lt; chance_to_fart){\n return 1;\n}else{\n return 0;\n}\n</code></pre>\n\n<p>is an anti-pattern; you can just do:</p>\n\n<pre><code>return roll &lt; chance_to_fart;\n</code></pre>\n\n<h2>Use more switches</h2>\n\n<p>The following should all be converted to switches:</p>\n\n<pre><code>if(playable_spaces[k] == 'O'){\n</code></pre>\n\n<p>and</p>\n\n<pre><code>input = toupper(getch());\nif(input == 'P'){\n</code></pre>\n\n<p>and</p>\n\n<pre><code>input = toupper(getch());\nif(input == 'X' || input == 'O'){\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if(game_over_state == 1){\n vic_pointer = str1;\n</code></pre>\n\n<p>and</p>\n\n<pre><code> pick = rand() % 3;\n if(pick == 0){\n</code></pre>\n\n<h2>UI bug</h2>\n\n<p>If the user tries to navigate off of the grid, you show the message <code>You can't move that way</code>, which is good - but that message obscures the prompt, and doesn't go away even when the user navigates to a different, valid cell. There are several ways to fix this. The easiest one is to have the error message be output on a different line from the prompt, and erase the error message as soon as the user has entered valid input.</p>\n\n<h2>Sample refactored code</h2>\n\n<p>This is nowhere near complete.</p>\n\n<pre><code>// Refer to https://codereview.stackexchange.com/questions/210577/tic-tac-toe-in-c-w-ncurses-revision\n\n// tic tac toe v2 using suggestions from Stack Exchange for better style\n// Minus the struct stuff which I don't quite understand just yet.\n\n#include &lt;ctype.h&gt;\n#include &lt;ncurses.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;time.h&gt;\n\n// #define's for the COLOR_PAIRs\n#define X_COLOR 1\n#define O_COLOR 2\n#define BG_COLOR 3\n\n#define SQSIZE 3\n#define NUM_SPACES (SQSIZE*SQSIZE)\n\n#define INVISIBLE_CURSOR 0\n\n// Function Declarations\nstatic void init_spaces(char *space_ptr);\nstatic void paint_board(char playable_spaces[NUM_SPACES]);\nstatic void take_turn(char side, char *space_ptr,\n char playable_spaces[NUM_SPACES]);\nstatic void victory_splash(int game_over_state);\nstatic void paint_background();\nstatic void player_turn(char *space_ptr, char playable_spaces[NUM_SPACES],\n char side);\nstatic void ai_turn(char *space_ptr, char playable_spaces[NUM_SPACES],\n char side);\nstatic int pick_ai_space(const char playable_spaces[NUM_SPACES],\n int chance_to_fart_big_move,\n int chance_to_fart_center,\n char side, char ai_side);\nstatic bool main_menu();\nstatic int evaluate_board(char playable_spaces[NUM_SPACES]);\nstatic int spaces_left(const char playable_spaces[NUM_SPACES]);\nstatic bool ai_fart(int chance_to_fart);\nstatic int pick_random_space(const char playable_spaces[NUM_SPACES]);\nstatic int check_for_winning_move(const char playable_spaces[NUM_SPACES],\n char ai_side);\nstatic int check_for_block(const char playable_spaces[NUM_SPACES], char side);\nstatic char pick_side();\n\n\nint main(int argc, char **argv) {\n // To-Do: Try the time(NULL) method for srand initialization and see if it\n // works the same\n time_t t;\n srand((unsigned)time(&amp;t));\n char playable_spaces[NUM_SPACES] = \"XXX\"\n \"XXX\"\n \"XXX\";\n char *space_ptr = playable_spaces;\n\n // Game over splash\n const char *game_over_str = \" Game Over! Any key to continue... \",\n *go_padding = \" \";\n int game_over_len = strlen(game_over_str);\n\n //curses init\n initscr();\n cbreak();\n keypad(stdscr, 1);\n curs_set(INVISIBLE_CURSOR);\n start_color();\n init_pair(X_COLOR, COLOR_CYAN, COLOR_BLACK);\n init_pair(O_COLOR, COLOR_GREEN, COLOR_BLACK);\n init_pair(BG_COLOR, COLOR_YELLOW, COLOR_BLACK);\n noecho();\n\n // Main Menu outer loop\n // Main menu function quits or continues\n while (main_menu()) {\n // Init all spaces to blank\n init_spaces(space_ptr);\n // Player picks their side.\n char side = pick_side();\n // The inner, inner turn loop\n int game_over;\n do {\n // Paint the board state as it is that turn\n paint_board(playable_spaces);\n // Function that governs the turn cycle\n take_turn(side, space_ptr, playable_spaces);\n // Evaluate the board for game over state\n game_over = evaluate_board(playable_spaces);\n } while (!game_over);\n // paint the board with a splash on game over\n // so the player can evaluate the board for a moment\n paint_board(playable_spaces);\n int row, col;\n getmaxyx(stdscr, row, col);\n int y = row/2 + 6,\n x = col/2 - game_over_len/2;\n attron(COLOR_PAIR(BG_COLOR));\n mvprintw(y++, x, go_padding);\n mvprintw(y++, x, game_over_str);\n mvprintw(y, x, go_padding);\n refresh();\n getch();\n // call victory_splash with int game_over as a parameter\n // 1 = X wins, 2 = O wins, 3 = Tie\n victory_splash(game_over);\n }\n\n // end curses\n endwin();\n\n return 0;\n}\n\nstatic void init_spaces(char *space_ptr) {\n // init all the spaces to ' '\n memset(space_ptr, ' ', NUM_SPACES);\n}\n\nstatic void paint_board(char playable_spaces[NUM_SPACES]) {\n // paint the board and the playable spaces\n clear();\n paint_background();\n const char *break_lines = \" ------- \",\n *play_lines = \" | | | | \",\n *padding = \" \";\n int row, col;\n getmaxyx(stdscr, row, col);\n int y = row/2 - 4,\n len = strlen(padding),\n x = col/2 - len/2;\n attron(COLOR_PAIR(BG_COLOR));\n for (int k = 0; k &lt; NUM_SPACES; k++) {\n // Paint the board itself without the pieces\n if (k == 0 || k == NUM_SPACES - 1)\n mvprintw(y + k, x, padding);\n else if (k%2 == 0)\n mvprintw(y + k, x, play_lines);\n else\n mvprintw(y + k, x, break_lines);\n }\n attroff(COLOR_PAIR(BG_COLOR));\n\n // insert Xs and Os:\n // First set the dynamic x and y coordinates based on terminal size\n int playable_x[NUM_SPACES], playable_y[NUM_SPACES];\n for (int i = 0; i &lt; SQSIZE; i++) {\n int ycoord = y + 2*(i + 1);\n for (int j = 0; j &lt; SQSIZE; j++) {\n int idx = SQSIZE*i + j;\n playable_x[idx] = x + 2*(j + 1);\n playable_y[idx] = ycoord;\n }\n }\n\n for (int k = 0; k &lt; NUM_SPACES; k++) {\n // For each of the playable spaces, first set the color\n int color;\n switch (playable_spaces[k]) {\n case 'O':\n color = O_COLOR;\n break;\n case 'X':\n color = X_COLOR;\n break;\n default:\n color = BG_COLOR;\n }\n attron(COLOR_PAIR(color));\n // then insert the char for that space into the proper spot on the terminal\n mvaddch(playable_y[k], playable_x[k], playable_spaces[k]);\n }\n // refresh the screen\n refresh();\n}\n\nstatic void take_turn(char side, char *space_ptr,\n char playable_spaces[NUM_SPACES]) {\n // using \"side\" to determine the order, call the functions to play a whole turn\n if (side == 'X') {\n player_turn(space_ptr, playable_spaces, side);\n paint_board(playable_spaces);\n if (spaces_left(playable_spaces)) {\n if (!(evaluate_board(playable_spaces))) {\n ai_turn(space_ptr, playable_spaces, side);\n paint_board(playable_spaces);\n }\n }\n }\n else if (side == 'O') {\n ai_turn(space_ptr, playable_spaces, side);\n paint_board(playable_spaces);\n if (spaces_left(playable_spaces)) {\n if (!(evaluate_board(playable_spaces))) {\n player_turn(space_ptr, playable_spaces, side);\n paint_board(playable_spaces);\n }\n }\n }\n}\n\nstatic bool main_menu() {\n const char *error_string = \" Invalid Input! Any key to try again... \",\n *str1 = \" NCURSES TIC TAC TOE (v2) \",\n *padding = \" \",\n *str2 = \" (P)lay or (Q)uit? \";\n int len = strlen(str1),\n error_str_len = strlen(error_string);\n for (;;) {\n clear();\n // Takes user input and returns an int that quits or starts a game\n int row, col;\n\n paint_background();\n getmaxyx(stdscr, row, col);\n int y = row/2 - 2,\n x = col/2 - len/2;\n mvprintw(y++, x, padding);\n mvprintw(y++, x, str1);\n mvprintw(y++, x, padding);\n mvprintw(y++, x, str2);\n mvprintw(y++, x, padding);\n refresh();\n // get user input and return it\n switch (toupper(getch())) {\n case 'P':\n return true;\n case 'Q':\n return false;\n default:\n // call the function again if the input is bad\n x = col/2 - error_str_len/2;\n mvprintw(++y, x, error_string);\n getch();\n }\n }\n}\n\nstatic int evaluate_board(char playable_spaces[NUM_SPACES]) {\n // Evaluates the state of the playable spaces and either does nothing\n // or ends the game.\n // Check all the possible winning combinations:\n if (playable_spaces[0] == 'X' &amp;&amp; playable_spaces[1] == 'X' &amp;&amp; playable_spaces[2] == 'X') {\n return 1;\n }\n if (playable_spaces[3] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[5] == 'X') {\n return 1;\n }\n if (playable_spaces[6] == 'X' &amp;&amp; playable_spaces[7] == 'X' &amp;&amp; playable_spaces[8] == 'X') {\n return 1;\n }\n if (playable_spaces[0] == 'X' &amp;&amp; playable_spaces[3] == 'X' &amp;&amp; playable_spaces[6] == 'X') {\n return 1;\n }\n if (playable_spaces[1] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[7] == 'X') {\n return 1;\n }\n if (playable_spaces[2] == 'X' &amp;&amp; playable_spaces[5] == 'X' &amp;&amp; playable_spaces[8] == 'X') {\n return 1;\n }\n if (playable_spaces[0] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[8] == 'X') {\n return 1;\n }\n if (playable_spaces[2] == 'X' &amp;&amp; playable_spaces[4] == 'X' &amp;&amp; playable_spaces[6] == 'X') {\n return 1;\n }\n if (playable_spaces[0] == 'O' &amp;&amp; playable_spaces[1] == 'O' &amp;&amp; playable_spaces[2] == 'O') {\n return 2;\n }\n if (playable_spaces[3] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[5] == 'O') {\n return 2;\n }\n if (playable_spaces[6] == 'O' &amp;&amp; playable_spaces[7] == 'O' &amp;&amp; playable_spaces[8] == 'O') {\n return 2;\n }\n if (playable_spaces[0] == 'O' &amp;&amp; playable_spaces[3] == 'O' &amp;&amp; playable_spaces[6] == 'O') {\n return 2;\n }\n if (playable_spaces[1] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[7] == 'O') {\n return 2;\n }\n if (playable_spaces[2] == 'O' &amp;&amp; playable_spaces[5] == 'O' &amp;&amp; playable_spaces[8] == 'O') {\n return 2;\n }\n else if (playable_spaces[0] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[8] == 'O') {\n return 2;\n }\n else if (playable_spaces[2] == 'O' &amp;&amp; playable_spaces[4] == 'O' &amp;&amp; playable_spaces[6] == 'O') {\n return 2;\n }\n\n // Check all spaces for a tie\n int hits = 0;\n for (int i = 0; i &lt; NUM_SPACES; i++)\n if (playable_spaces[i] != ' ')\n hits++;\n\n if (hits &gt;= NUM_SPACES)\n return 3;\n\n return 0;\n}\n\nchar pick_side() {\n const char *str1 = \" Press 'X' for X, 'O' for O, or 'R' for random! \",\n *str2 = \" Good choice! Any key to continue... \",\n *padding = \" \",\n *err_str = \" Invalid input! Any key to continue... \";\n int len = strlen(str1);\n\n for (;;) {\n // Takes user input and returns the chosen side\n clear();\n paint_background();\n int row, col;\n getmaxyx(stdscr, row, col);\n int y = row / 2 - 2,\n x = col / 2 - len / 2;\n mvprintw(y++, x, padding);\n mvprintw(y++, x, str1);\n mvprintw(y++, x, padding);\n refresh();\n // Get user input for picking a side. 'R' is random.\n char input = toupper(getch());\n switch (input) {\n case 'X':\n case 'O': {\n mvprintw(y, x, str2);\n refresh();\n getch();\n return input;\n }\n case 'R': {\n bool pick = rand() % 2;\n if (pick)\n input = 'X';\n else\n input = 'O';\n mvprintw(y, x, str2);\n refresh();\n getch();\n return input;\n }\n default: {\n // Call the function again on bad input\n mvprintw(y, x, err_str);\n refresh();\n getch();\n }\n }\n }\n}\n\nstatic void victory_splash(int game_over_state) {\n // Takes the game over state and creates a victory splash\n const char *padding = \" \",\n *str1 = \" X Wins! \",\n *str2 = \" O Wins! \",\n *str3 = \" any key to continue... \",\n *str4 = \" A tie game! \";\n int len = strlen(padding);\n const char *vic_pointer;\n // To avoid code duplication, use a pointer to pick the right string\n switch (game_over_state) {\n case 1:\n vic_pointer = str1;\n case 2:\n vic_pointer = str2;\n case 3:\n vic_pointer = str4;\n }\n clear();\n paint_background();\n int row, col;\n getmaxyx(stdscr, row, col);\n int y = row/2 - 2,\n x = col/2 - len/2;\n mvprintw(y++, x, padding);\n mvprintw(y++, x, vic_pointer);\n mvprintw(y++, x, padding);\n mvprintw(y, x, str3);\n refresh();\n getch();\n}\n\nstatic void paint_background() {\n // Paints an elaborate flashy background\n int row, col;\n getmaxyx(stdscr, row, col);\n for (int y = 0; y &lt;= row; y++) {\n for (int x = 0; x &lt;= col; x++) {\n int color;\n char draw;\n switch (rand() % 3) {\n case 0:\n color = X_COLOR;\n draw = 'X';\n break;\n case 1:\n color = O_COLOR;\n draw = 'O';\n break;\n case 2:\n color = BG_COLOR;\n draw = ' ';\n break;\n }\n attron(COLOR_PAIR(color));\n char draw_str[] = {draw, '\\0'};\n mvprintw(y, x, draw_str);\n attroff(COLOR_PAIR(color));\n }\n }\n refresh();\n}\n\nstatic void player_turn(char *space_ptr, char playable_spaces[NUM_SPACES], char side) {\n // Function for the player turn\n char padding[] = \" \";\n char str1[] = \" Use arrow keys to move and 'P' to place! \";\n char str3[] = \" Invalid input! \";\n char str4[] = \" You can't move that way! \";\n char str5[] = \" Space already occupied! \";\n int len = strlen(padding);\n int row, col, x, y;\n getmaxyx(stdscr, row, col);\n const int board_line_len = 9;\n const int board_lines = 9;\n y = row / 2 - board_line_len / 2;\n x = col / 2 - board_line_len / 2;\n // Use the same method of dynamically measuring where the spaces are at using\n // terminal size as in the paint_board() function.\n int playable_x[NUM_SPACES] = {x+2, x+4, x+6, x+2, x+4, x+6, x+2, x+4, x+6};\n int playable_y[NUM_SPACES] = {y+2, y+2, y+2, y+4, y+4, y+4, y+6, y+6, y+6};\n // The variables and mvprintw functions for the \"info line\"\n const int info_line_y = (row / 2 - board_lines / 2) + 10;\n const int info_line_x = col / 2 - len / 2;\n mvprintw(info_line_y - 1, info_line_x, padding);\n mvprintw(info_line_y, info_line_x, str1);\n mvprintw(info_line_y + 1, info_line_x, padding);\n // Using a loop and pointers to collect user input\n int moving = 1;\n int input;\n int *pos_x = &amp;playable_x[0];\n int *pos_y = &amp;playable_y[0];\n move(*pos_y, *pos_x);\n curs_set(1);\n refresh();\n while(moving) {\n // For each movement key, if the move is valid, use pointer\n // arithmetic to mov pos_x and pos_y around.\n input = toupper(getch());\n if (input == KEY_UP) {\n if (*pos_y != playable_y[0]) {\n pos_y -= 3;\n move(*pos_y, *pos_x);\n refresh();\n }\n else{\n mvprintw(info_line_y, info_line_x, str4);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n else if (input == KEY_DOWN) {\n if (*pos_y != playable_y[6]) {\n pos_y += 3;\n move(*pos_y, *pos_x);\n refresh();\n }\n else{\n mvprintw(info_line_y, info_line_x, str4);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n else if (input == KEY_LEFT) {\n if (*pos_x != playable_x[0]) {\n pos_x -= 1;\n move(*pos_y, *pos_x);\n refresh();\n }\n else{\n mvprintw(info_line_y, info_line_x, str4);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n else if (input == KEY_RIGHT) {\n if (*pos_x != playable_x[2]) {\n pos_x += 1;\n move(*pos_y, *pos_x);\n refresh();\n }\n else{\n mvprintw(info_line_y, info_line_x, str4);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n else if (input == 'P') {\n // I wanted to use KEY_ENTER instead of 'P' but it would not work\n // for some reason. When the user presses 'P' it checks where the\n // cursor is and sets the space_ptr to the appropriate index in the\n // playable_spaces array.\n if (*pos_y == playable_y[0] &amp;&amp; *pos_x == playable_x[0]) {\n space_ptr = &amp;playable_spaces[0]; \n }\n else if (*pos_y == playable_y[1] &amp;&amp; *pos_x == playable_x[1]) {\n space_ptr = &amp;playable_spaces[1];\n }\n else if (*pos_y == playable_y[2] &amp;&amp; *pos_x == playable_x[2]) {\n space_ptr = &amp;playable_spaces[2];\n }\n else if (*pos_y == playable_y[3] &amp;&amp; *pos_x == playable_x[3]) {\n space_ptr = &amp;playable_spaces[3];\n }\n else if (*pos_y == playable_y[4] &amp;&amp; *pos_x == playable_x[4]) {\n space_ptr = &amp;playable_spaces[4];\n }\n else if (*pos_y == playable_y[5] &amp;&amp; *pos_x == playable_x[5]) {\n space_ptr = &amp;playable_spaces[5];\n }\n else if (*pos_y == playable_y[6] &amp;&amp; *pos_x == playable_x[6]) {\n space_ptr = &amp;playable_spaces[6];\n }\n else if (*pos_y == playable_y[7] &amp;&amp; *pos_x == playable_x[7]) {\n space_ptr = &amp;playable_spaces[7];\n }\n else if (*pos_y == playable_y[8] &amp;&amp; *pos_x == playable_x[8]) {\n space_ptr = &amp;playable_spaces[8];\n }\n // Then checks to see if that space is empty.\n // If so it sets the color properly and then places the piece.\n if (*space_ptr == ' ') {\n if (side == 'X') {\n attron(COLOR_PAIR(X_COLOR));\n mvaddch(*pos_y, *pos_x, 'X');\n attron(COLOR_PAIR(BG_COLOR));\n *space_ptr = 'X';\n }\n else if (side == 'O') {\n attron(COLOR_PAIR(O_COLOR));\n mvaddch(*pos_y, *pos_x, 'O');\n attron(COLOR_PAIR(BG_COLOR));\n *space_ptr = 'O';\n }\n refresh();\n moving = 0;\n }\n else{\n mvprintw(info_line_y, info_line_x, str5);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n else{\n mvprintw(info_line_y, info_line_x, str3);\n move(*pos_y, *pos_x);\n refresh();\n }\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Begin AI Logic ////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////\n\nstatic void ai_turn(char *space_ptr, char playable_spaces[NUM_SPACES], char side) {\n // wrapper for the AI turn\n /*\n Note: Since it is easy to accidentally create an unbeatable AI for tic tac toe\n I am building into the AI the chance for it to not make the optimal move.\n This intentional fuzziness will be built into the functions that check for\n avaialable spaces. When they find an optimal move they may just decide\n to return 0 anyway.\n\n P-Code:\n if center square not taken, take center square 70% of the time;\n else:\n if opponent about to win, block them 90% of the time;\n elif self about to win take winning spot 90% of the time;\n else pick a random open spot;\n */\n // Picking the character for the AI to use in its calculations\n char ai_side;\n if (side == 'X')\n ai_side = 'O';\n else\n ai_side = 'X';\n\n // Check the board state with a few functions.\n int picked_space = pick_ai_space(playable_spaces, 10, 30, side, ai_side);\n space_ptr = &amp;playable_spaces[picked_space];\n if (ai_side == 'X')\n attron(COLOR_PAIR(X_COLOR));\n else\n attron(COLOR_PAIR(O_COLOR));\n *space_ptr = ai_side;\n attron(COLOR_PAIR(BG_COLOR));\n}\n\nstatic int pick_ai_space(const char playable_spaces[NUM_SPACES],\n int chance_to_fart_big_move,\n int chance_to_fart_center,\n char side, char ai_side) {\n int can_block_opponent = check_for_block(playable_spaces, side),\n can_winning_move = check_for_winning_move(playable_spaces, ai_side);\n\n // Flow through the decision making logic applying the functions and\n // checking for a fart\n if (playable_spaces[4] == ' ' &amp;&amp;\n !(ai_fart(chance_to_fart_center)))\n return 4;\n if (can_winning_move) {\n if (!(ai_fart(chance_to_fart_big_move)))\n return can_winning_move;\n return pick_random_space(playable_spaces);\n }\n if (can_block_opponent) {\n if (!(ai_fart(chance_to_fart_big_move)))\n return can_block_opponent;\n return pick_random_space(playable_spaces);\n }\n return pick_random_space(playable_spaces);\n}\n\nstatic bool ai_fart(int chance_to_fart) {\n // Takes the fart chance and returns 1 if the AI blows the move, 0 otherwise\n int roll = rand() % 100 + 1;\n return roll &lt; chance_to_fart;\n}\n\nstatic int pick_random_space(const char playable_spaces[NUM_SPACES]) {\n // Returns a random open space on the board\n for (;;) {\n int roll = rand() % NUM_SPACES;\n if (playable_spaces[roll] == ' ')\n return roll;\n }\n}\n\nstatic int check_for_winning_move(const char playable_spaces[NUM_SPACES], char ai_side) {\n // Checks to see if the AI can win the game with a final move and returns the\n // index of the valid move if TRUE, returns 0 if FALSE\n int pick;\n bool picked = false;\n for (int space = 0; space &lt; NUM_SPACES; space++) {\n // For each space: Check to see if it is a potential winning space and if so\n // switch \"picked\" to 1 and set \"pick\" to the winning index\n switch (space) {\n case 0:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == ai_side &amp;&amp; playable_spaces[6] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[8] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 1:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[0] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[7] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 2:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == ai_side &amp;&amp; playable_spaces[0] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[6] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[5] == ai_side &amp;&amp; playable_spaces[8] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 3:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[5] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[0] == ai_side &amp;&amp; playable_spaces[6] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 4:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == ai_side &amp;&amp; playable_spaces[7] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == ai_side &amp;&amp; playable_spaces[5] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[0] == ai_side &amp;&amp; playable_spaces[8] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[6] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 5:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[8] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == ai_side &amp;&amp; playable_spaces[4] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 6:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[7] == ai_side &amp;&amp; playable_spaces[8] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == ai_side &amp;&amp; playable_spaces[0] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 7:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[6] == ai_side &amp;&amp; playable_spaces[8] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[1] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 8:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[5] == ai_side &amp;&amp; playable_spaces[2] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == ai_side &amp;&amp; playable_spaces[0] == ai_side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[7] == ai_side &amp;&amp; playable_spaces[6] == ai_side) {\n pick = space;\n picked = true;\n }\n }\n break;\n }\n }\n // return winning index if any\n if (picked)\n return pick;\n return 0;\n}\n\nstatic int check_for_block(const char playable_spaces[NUM_SPACES], char side) {\n // Checks to see if the AI can block the player from winning the game with a final move\n // and returns the index of the valid move if TRUE, returns 0 if FALSE\n // Note: I am sure there is a way to combine this this function with the\n // check_for_winning_move() function in order to avoid code duplication, probably using\n // one more parameter as a switch of some kind. I'd be open to examples of how to do that.\n int pick;\n bool picked = false;\n for (int space = 0; space &lt; NUM_SPACES; space++) {\n // For each space: Check to see if it is a potential winning space and if so\n // switch \"picked\" to 1 and set \"pick\" to the winning index\n switch (space) {\n case 0:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == side &amp;&amp; playable_spaces[6] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == side &amp;&amp; playable_spaces[8] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 1:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[0] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == side &amp;&amp; playable_spaces[7] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 2:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == side &amp;&amp; playable_spaces[0] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == side &amp;&amp; playable_spaces[6] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[5] == side &amp;&amp; playable_spaces[8] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 3:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[4] == side &amp;&amp; playable_spaces[5] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[0] == side &amp;&amp; playable_spaces[6] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 4:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[1] == side &amp;&amp; playable_spaces[7] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == side &amp;&amp; playable_spaces[5] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[0] == side &amp;&amp; playable_spaces[8] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[6] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 5:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[8] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == side &amp;&amp; playable_spaces[4] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 6:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[4] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[7] == side &amp;&amp; playable_spaces[8] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[3] == side &amp;&amp; playable_spaces[0] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 7:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[6] == side &amp;&amp; playable_spaces[8] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == side &amp;&amp; playable_spaces[1] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n case 8:\n if (playable_spaces[space] == ' ') {\n if (playable_spaces[5] == side &amp;&amp; playable_spaces[2] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[4] == side &amp;&amp; playable_spaces[0] == side) {\n pick = space;\n picked = true;\n }\n else if (playable_spaces[7] == side &amp;&amp; playable_spaces[6] == side) {\n pick = space;\n picked = true;\n }\n }\n break;\n }\n }\n // return winning index if any\n if (picked)\n return pick;\n return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////////\n// End AI Logic ///////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////\n\nstatic int spaces_left(const char playable_spaces[NUM_SPACES]) {\n // Returns 0 if no spaces left\n int hits = 0;\n for (int k = 0; k &lt; NUM_SPACES; k++)\n if (playable_spaces[k] == ' ')\n hits++;\n return hits;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:15:55.180", "Id": "407066", "Score": "0", "body": "\"Tell the compiler when you don't intend to export functions to a different translation unit. Mark all of your functions static except main.\"\n\nWhy?\n\n\"There are several variables, including running and turning, that are int but should be boolean. Include stdbool.h for this purpose.\"\n\nI did this for a reason though. If they return 0 then they are passed over, otherwise they return integers that do different things. Is that bad practice?\n\nThanks for your tips! I'll keep working at it. C sure is harder than Python in a lot of ways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:22:53.977", "Id": "407069", "Score": "0", "body": "I mis-spoke in my above comment but ran out of time to edit. Running and turning are just booleans but is it bad practice to use 1 and 0? What about using #defines? \n\nI have a lot of functions that I use in testing if statements that return 0 if false and return a variety of possible numbers if true, doing different things. Is that also bad practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:25:54.570", "Id": "407071", "Score": "0", "body": "Thanks! Can I get you to expand on why this is? What other functionality does stdbool.h offer to make it superior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:27:14.077", "Id": "407073", "Score": "2", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/87664/discussion-between-reinderien-and-some-guy632)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T06:27:09.123", "Id": "407079", "Score": "0", "body": "Hey I have one more for you: since ncurses.h defines its own TRUE and FALSE will I run into conflicts using stdbool.h?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:58:19.420", "Id": "407155", "Score": "0", "body": "You say that while(playing){} is an unneeded loop but looking at your refactor it is hard to see how you can replay? I had it in there so that when you end a game you can go back to the main menu where you choose to quit or continue, where hitting play sends you into the playing loop, where you pick a side, and then you go into the turning loop where the turn sequence is carried out. Did you just do away with the main menu in your refactor? If so, why? I'm tempted to mark this one as the answer because it's so full of really good tips but I'm curious about that choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:59:02.280", "Id": "407156", "Score": "0", "body": "Also curses recommends using FALSE for the invisible cursor. So curs_set(FALSE). That's on me for using a magic number. ncurses.h simply defines TRUE as 1 and FALSE as 0." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:06:45.910", "Id": "210587", "ParentId": "210577", "Score": "8" } }, { "body": "<h2><strong>A small review</strong></h2>\n\n<p>I noticed in both iterations of your code that you have to forward declare every single function. This is not advisable. It is better to declare <code>main()</code> last, thereby eliminating your need to forward declare. After all just imagine the forward declarations required for a project of significant size.</p>\n\n<p>After that you might also want to start separating your logic into modular files that you can then <code>#include</code>. Small logically connected groups of functions, <code>#define</code>s, <code>struct</code>s and the like.</p>\n\n<hr>\n\n<p>also don't do this:</p>\n\n<pre><code>// ncurses for, well, ncurses\n#include &lt;ncurses.h&gt;\n// time for the random seed\n#include &lt;time.h&gt;\n// string.h for strlen() \n#include &lt;string.h&gt;\n// stdlib and stdio because why not\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n// ctype.h for toupper()\n#include &lt;ctype.h&gt;\n</code></pre>\n\n<p>If you want to comment what each include is for (which I find unnecessary but I could be wrong) at least do it off to the side so scanning the <code>#include</code>s is readable. Like so:</p>\n\n<pre><code>#include &lt;ncurses.h&gt; // for, well, ncurses\n#include &lt;time.h&gt; // for random seed\n#include &lt;string.h&gt; // for strlen()\n#include &lt;stdlib.h&gt; // why not?\n#include &lt;stdio.h&gt; // why not?\n#include &lt;ctype.h&gt; // for toupper()\n</code></pre>\n\n<p>And <strong>never, ever, <em>ever</em></strong> include headers you don't need. (I didn't read enough of the code but the comment \"why not?\" makes me think you didn't know if you were going to need <code>stdlib</code> or <code>stdio</code> and that's a bad reason to include something.) Just add the header when you need it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T05:08:53.953", "Id": "407075", "Score": "0", "body": "Does forward declaring serve a purpose? I did it because it seems like the formal way to do it but coming from Python I'm cool not doing it! I commented the #includes hoping specifically that I'd get feedback on my choice of includes. I've often heard you should always include stdlib.h unless you're hurting for resources. Is that true? Thank you for the review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T05:15:49.740", "Id": "407076", "Score": "3", "body": "You have to forward declare because your main uses those functions. without a forward declaration your code would not compile. but if you put the `main()` at the end then its a non-issue. Anytime you use a function in another one though it needs to be declared or defined prior to its use. As for including `stdlib.h` I can't say for sure as I don't actually write in C but I imagine it's far more likely you were taught that because almost everything you write will use it. (After all it has `size_t` which is ubiquitous in C and C++) And good inclination to get your includes reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T14:44:14.857", "Id": "407098", "Score": "1", "body": "Re. forward declaration. It's important to note that for a \"project of significant size\", your functions would be spread across several translation units and you'd have headers, making forward declaration mandatory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:32:27.730", "Id": "407105", "Score": "0", "body": "@Reinderien but you won't be forward declaring. The computer will. I sorta touched on that. I'll rephrase when I get a chance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T04:32:31.400", "Id": "407168", "Score": "0", "body": "\"And never, ever, ever include headers you don't need.\" is an overstatement. Inclusions of \"unneeded\" standard header files helps insure code does not create functions that collide with standard function, types, defines, like `div()`, `sqrt()`, `complex`, `INT_MAX`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T04:37:10.800", "Id": "407169", "Score": "0", "body": "@chux I may have been a bit hyperbolic but it seems to me that one could check their name collisions without including unnecessary headers in a final compilation unit. But I could be wrong on this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T04:45:15.373", "Id": "407170", "Score": "1", "body": "For clarity, I agree about code should avoid adding non-standard `.h` files. To include only just the right standard header files is _work_ with little benefit. In my experience, better to include unneeded standard header files than to miss one. IMO, I'd like to see a tool that auto checked code for standard identifiers and the auto included those header. Save human programing time for the larger issues." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T04:58:05.917", "Id": "210588", "ParentId": "210577", "Score": "8" } }, { "body": "<p>Based on the length of my original answer, the nature of my new advice and <a href=\"https://codereview.meta.stackexchange.com/questions/20/should-one-person-have-multiple-answers\">this guidance</a>, I'm submitting another answer here.</p>\n\n<p>You need to have a fundamental re-think about the nature of your data. This is not C-specific; the same thing would apply in Python (or whatever other language you use). You're very often carrying around display information (the letter 'X' and 'O', for instance, or coordinates on the screen) and using those to affect your logic. Your logical data should be pure, in the sense that:</p>\n\n<ul>\n<li>Your logic should not have anything to do with screen coordinates</li>\n<li>Your logic should not ever refer to 'X' and 'O', but rather to player numbers.</li>\n<li>You should never be reading the contents of the screen, or any display buffers, back into the logic to decide what to do next.</li>\n</ul>\n\n<p>You have another habit - hard-coding things that should be computed. This especially applies to manipulating coordinates of the game grid. The contents of the game grid should not be 'X' and 'O', but rather an <code>enum</code> with three values - blank, player1, or player2. The game grid should be represented as a two-dimensional, and not one-dimensional, array. Manipulating this grid should be done with two-dimensional coordinates, and not a one-dimensional \"flattened\" index. Rewriting your code like this will make it easier to write loops and functions, and significantly DRY up your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T00:06:52.720", "Id": "407157", "Score": "0", "body": "\"You should never be reading the contents of the screen, or any display buffers, back into the logic to decide what to do next.\" Can you expand on this? The nature of ncurses makes it very easy to conflate the two compared to, say, Pygame." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T00:15:24.917", "Id": "407158", "Score": "0", "body": "@some_guy632 Let's discuss this in the same chat - https://chat.stackexchange.com/rooms/87664/discussion-between-reinderien-and-some-guy632" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:43:08.880", "Id": "210614", "ParentId": "210577", "Score": "4" } }, { "body": "<p>Compiling using clang with warnings turned on reveals a number of issues:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>$ clang -Wall -lcurses -o ttt ttt.c\nttt.c:240:1: warning: control may reach end of non-void function [-Wreturn-type]\n}\n^\n</code></pre>\n</blockquote>\n\n<p>Why is <code>main_menu()</code> calling itself recursively? If you want a loop, write a loop.</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>ttt.c:339:1: warning: control may reach end of non-void function [-Wreturn-type]\n}\n^\n</code></pre>\n</blockquote>\n\n<p>Same issue with <code>pick_side()</code>. It should be a loop.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>ttt.c:402:10: warning: unused variable 'str2' [-Wunused-variable]\n char str2[] = \" Good move! \";\n ^\n</code></pre>\n</blockquote>\n\n<p>Self-explanatory.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>ttt.c:555:14: warning: variable 'ai_side' is used uninitialized whenever 'if'\n condition is false [-Wsometimes-uninitialized]\n }else if(side == 'O'){\n ^~~~~~~~~~~\nttt.c:562:68: note: uninitialized use occurs here\n int can_winning_move = check_for_winning_move(playable_spaces, ai_side);\n ^~~~~~~\nttt.c:555:11: note: remove the 'if' if its condition is always true\n }else if(side == 'O'){\n ^~~~~~~~~~~~~~~\nttt.c:552:17: note: initialize the variable 'ai_side' to silence this warning\n char ai_side;\n ^\n = '\\0'\n4 warnings generated.\n</code></pre>\n</blockquote>\n\n<p>That if-elseif would be better written as <code>char ai_side = (side == 'X') ? 'O' : 'X';</code>, which would have avoided all of those warnings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T22:27:50.627", "Id": "407150", "Score": "4", "body": "On the last point, better still would to have an array of function pointers and call either `human_turn` or `ai_turn`. All other turn processing is identical and that entire function simply goes away." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T22:23:09.723", "Id": "210617", "ParentId": "210577", "Score": "7" } } ]
{ "AcceptedAnswerId": "210587", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T01:34:33.713", "Id": "210577", "Score": "8", "Tags": [ "beginner", "c", "tic-tac-toe", "ai", "curses" ], "Title": "Tic Tac Toe in C w/ ncurses Revision" }
210577
<p>I'm creating an image class that can be used by other classes to create visualizations of data. The class doesn't need to be complicated as the classes will be editing the images pixel by pixel.</p> <p>The image class will be used to create RGB images and export them to any of the netbpm image formats (<a href="http://netpbm.sourceforge.net/doc/pbm.html" rel="nofollow noreferrer">pbm</a>, <a href="http://netpbm.sourceforge.net/doc/pgm.html" rel="nofollow noreferrer">pgm</a>, <a href="http://netpbm.sourceforge.net/doc/ppm.html" rel="nofollow noreferrer">ppm</a>). I may expand the class to export in other formats and maybe load images, but for the moment, I just need the basic functionality of editing and exporting.</p> <p>I'm mostly looking for feedback on the use of <code>enum</code> values.</p> <hr> <p><strong>Image.h</strong></p> <pre><code>#ifndef IMAGE_H #define IMAGE_H #include &lt;string&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;cctype&gt; #include &lt;cmath&gt; using namespace std; class Image { public: enum Enum_Colors {WHITE, BLACK, GREY, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA}; private: const unsigned int NUM_PIXEL_VALUES = 3; const unsigned int FILE_EXTENSION_LENGTH = 4; struct Pixel { unsigned int red; unsigned int green; unsigned int blue; }; unsigned int maxValue; vector&lt;vector&lt;Pixel&gt;&gt; imageData; /** * Creates a pixel representing the given color. * * @param color an enumerated color * @return a pixel representing the given color **/ Pixel ColorPixel(Enum_Colors color) const; /** * Creates an image file from the image data. * * The type of the created file is determined by the function name. * * @param fileName the name of the created file * @return false if an error occurred * @return true otherwise **/ bool ExportPBM(string fileName); bool ExportPGM(string fileName); bool ExportPPM(string fileName); public: Image(unsigned int width, unsigned int height, unsigned int maxValue) : maxValue(maxValue), imageData(vector&lt;vector&lt;Pixel&gt;&gt;(height, vector&lt;Pixel&gt;(width, ColorPixel(WHITE)))) {}; ~Image() {imageData.clear();} /** * Returns the pixel width of the image. * * @return the pixel width of the image **/ unsigned int Width(); /** * Returns the pixel height of the image. * * @return the pixel height of the image **/ unsigned int Height(); /** * Returns the maximum intensity value of the image. * * @return the maximum intensity value of the image **/ unsigned int MaxValue(); /** * Sets the given pixel value to the given color. * * @param x the location along the width * @param y the location along the height * @param color the color to set the pixel to * * @return false if the indices are out of bounds * @return true otherwise **/ bool SetPixelColor(unsigned int x, unsigned int y, Enum_Colors color); /** * Sets the given pixel value to the given color. * * @param x the location along the width * @param y the location along the height * @param redVal the intensity of the red value to set the pixel to * @param greenVal the intensity of the green value to set the pixel to * @param blueVal the intensity of the blue value to set the pixel to * * @return false if the indices are out of bounds or the color values are out of bounds * @return true otherwise **/ bool SetPixelValue(unsigned int x, unsigned int y, unsigned int redValue, unsigned int greenValue, unsigned int blueValue); /** * Creates an image file from the image data. * * The type of the created file is determined by the file name. * (Supported extensions: .pbm, .pgm, .ppm) * * @param fileName the name of the created file * @return false if the extension is not supported or an error occurred * @return true otherwise **/ bool ExportImage(string fileName); }; #endif </code></pre> <p><strong>Image.cpp</strong></p> <pre><code>#include "Image.h" Image::Pixel Image::ColorPixel(Enum_Colors color) const { Pixel pixel; switch (color) { case WHITE: pixel.red = maxValue; pixel.green = maxValue; pixel.blue = maxValue; break; case BLACK: pixel.red = 0; pixel.green = 0; pixel.blue = 0; break; case GREY: pixel.red = maxValue / 2; pixel.green = maxValue / 2; pixel.blue = maxValue / 2; break; case RED: pixel.red = maxValue; pixel.green = 0; pixel.blue = 0; break; case GREEN: pixel.red = 0; pixel.green = maxValue; pixel.blue = 0; break; case BLUE: pixel.red = 0; pixel.green = 0; pixel.blue = maxValue; break; case YELLOW: pixel.red = maxValue; pixel.green = maxValue; pixel.blue = 0; break; case CYAN: pixel.red = 0; pixel.green = maxValue; pixel.blue = maxValue; break; case MAGENTA: pixel.red = maxValue; pixel.green = 0; pixel.blue = maxValue; break; default: pixel.red = maxValue; pixel.green = maxValue; pixel.blue = maxValue; break; } return pixel; } bool Image::ExportPBM(string fileName) { ofstream fout; /* Attempt to create the file and check for errors */ fout.open(fileName); if (fout.fail()) { return false; } /* Write heading */ fout &lt;&lt; "P1" &lt;&lt; endl; // file type identifier fout &lt;&lt; "# CREATOR: C++ Image Class, by Jacob Bischoff" &lt;&lt; endl; fout &lt;&lt; imageData.at(0).size() &lt;&lt; " " &lt;&lt; imageData.size() &lt;&lt; endl; // width height /* Write body */ for (unsigned int i = 0; i &lt; imageData.size(); i++) { /* Add end line in proper locations */ if (i &gt; 0) { fout &lt;&lt; endl; } /* Output pixel values; 0 - White, 1 - Black */ for (unsigned int j = 0; j &lt; imageData.at(i).size(); j++) { Pixel pixel = imageData.at(i).at(j); if (j &gt; 0) { fout &lt;&lt; " "; } fout &lt;&lt; 1 - (int)roundf((pixel.red + pixel.green + pixel.blue) / (double)NUM_PIXEL_VALUES / (double)maxValue); } } return true; } bool Image::ExportPGM(string fileName) { ofstream fout; /* Attempt to create the file and check for errors */ fout.open(fileName); if (fout.fail()) { return false; } /* Write heading */ fout &lt;&lt; "P2" &lt;&lt; endl; // file type identifier fout &lt;&lt; "# CREATOR: C++ Image Class, by Jacob Bischoff" &lt;&lt; endl; fout &lt;&lt; imageData.at(0).size() &lt;&lt; " " &lt;&lt; imageData.size() &lt;&lt; endl; // width height fout &lt;&lt; maxValue &lt;&lt; endl; /* Write body */ for (unsigned int i = 0; i &lt; imageData.size(); i++) { /* Add end line in proper locations */ if (i &gt; 0) { fout &lt;&lt; endl; } /* Output pixel values; 0 - black, maxValue - white */ for (unsigned int j = 0; j &lt; imageData.at(i).size(); j++) { Pixel pixel = imageData.at(i).at(j); if (j &gt; 0) { fout &lt;&lt; " "; } fout &lt;&lt; (int)roundf((pixel.red + pixel.green + pixel.blue) / (double)NUM_PIXEL_VALUES); } } return true; } bool Image::ExportPPM(string fileName) { ofstream fout; /* Attempt to create the file and check for errors */ fout.open(fileName); if (fout.fail()) { return false; } /* Write heading */ fout &lt;&lt; "P3" &lt;&lt; endl; // file type identifier fout &lt;&lt; "# CREATOR: C++ Image Class, by Jacob Bischoff" &lt;&lt; endl; fout &lt;&lt; imageData.at(0).size() &lt;&lt; " " &lt;&lt; imageData.size() &lt;&lt; endl; // width height fout &lt;&lt; maxValue &lt;&lt; endl; /* Write body */ for (unsigned int i = 0; i &lt; imageData.size(); i++) { /* Add end line in proper locations */ if (i &gt; 0) { fout &lt;&lt; endl; } /* Output pixel values; 0 0 0 - black, maxValue maxValue maxValue - white */ for (unsigned int j = 0; j &lt; imageData.at(i).size(); j++) { Pixel pixel = imageData.at(i).at(j); if (j &gt; 0) { fout &lt;&lt; "\t"; } fout &lt;&lt; pixel.red &lt;&lt; " " &lt;&lt; pixel.green &lt;&lt; " " &lt;&lt; pixel.blue; } } return true; } unsigned int Image::Width() { /* prevent out of bounds error */ if (imageData.size() == 0) { /* no second order elements */ return 0; } else { /* return the second order size */ return imageData.at(0).size(); } } unsigned int Image::Height() { /* return the first order size */ return imageData.size(); } unsigned int Image::MaxValue() { /* return the maximum intensity value */ return maxValue; } bool Image::SetPixelColor(unsigned int x, unsigned int y, Enum_Colors color) { /* check if indices are withing bounds */ if ((y &lt; imageData.size()) &amp;&amp; (x &lt; imageData.at(y).size())) { imageData.at(y).at(x) = ColorPixel(color); return true; } else { return false; } } bool Image::SetPixelValue(unsigned int x, unsigned int y, unsigned int redValue, unsigned int greenValue, unsigned int blueValue) { /* check if indices are withing bounds */ if ((y &lt; imageData.size()) &amp;&amp; (x &lt; imageData.at(y).size())) { /* check if intensity values are larger than max */ if ((redValue &lt;= maxValue) || (greenValue &lt;= maxValue) || (blueValue &lt;= maxValue)) { imageData.at(y).at(x).red = redValue; imageData.at(y).at(x).green = greenValue; imageData.at(y).at(x).blue = blueValue; return true; } else {return false;} } else {return false;} } bool Image::ExportImage(string fileName) { string fileExtension = fileName.substr(fileName.size() - FILE_EXTENSION_LENGTH, FILE_EXTENSION_LENGTH); /* Make extension all lowercase for ease of comparison */ for (unsigned int i = 0; i &lt; fileExtension.size(); ++i) { fileExtension.at(i) = tolower(fileExtension.at(i)); } /* Evaluate extension to determine which file type to create. */ if (fileExtension == ".pbm") { return ExportPBM(fileName); } else if (fileExtension == ".pgm") { return ExportPGM(fileName); } else if (fileExtension == ".ppm") { return ExportPPM(fileName); } else { return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T13:16:28.977", "Id": "407508", "Score": "1", "body": "There are [standard web color names](https://html-color-codes.info/color-names/), as used in CSS in HTML. Available in for instance java, so you might think of using them. A 32 bit int 0xRRGGBB might be another shortcut." } ]
[ { "body": "<p><strong>Code:</strong></p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/a/1453605/673679\">Don't use <code>using namespace std;</code>.</a></p></li>\n<li><p>It looks like you're including more dependencies in the header than necessary (<code>cmath</code>, <code>fstream</code>, <code>cctype</code>). These are only used in the <code>.cpp</code> file, so they should be included there.</p></li>\n<li><p>Use <code>enum class</code> for type safety instead of a plain <code>enum</code>.</p></li>\n<li><p>We don't need to call <code>imageData.clear()</code> in the destructor, or even define a destructor. (The compiler generated destructor will call the <code>std::vector</code> destructor automatically).</p></li>\n<li><p>It's easier to store width and height directly in the image class, instead of getting them from the vectors.</p></li>\n<li><p>It's more efficient to store data in a one-dimensional vector of <code>width * height</code> elements, as the allocated memory is all in one place, and we aren't storing a size for each individual row vector. The index in this vector can be calculated as <code>x + width * y</code>.</p></li>\n<li><p>The file formats seem to indicate a max component value of 65535. This can be represented by a <code>std::uint16_t</code> (i.e. <code>short unsigned int</code>), so it might be better to use that for the pixel component type and for <code>maxValue</code>.</p></li>\n<li><p><code>ColorPixel()</code> can use braced init-list to return values, which is rather more concise:</p>\n\n<pre><code>Image::Pixel Image::ColorPixel(Enum_Colors color) const {\n switch (color) {\n case Enum_Colors::WHITE: return{ maxValue, maxValue, maxValue };\n case Enum_Colors::BLACK: return{ 0, 0, 0 };\n // ...\n }\n}\n</code></pre></li>\n<li><p><code>ColorPixel()</code> should perhaps <code>assert</code> or <code>throw</code> an exception if the <code>enum</code> value is invalid, rather than returning white.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Design:</strong></p>\n\n<p>I'd suggest a slightly different architecture.</p>\n\n<p>Currently this class is doing 3 separate things:</p>\n\n<ul>\n<li>Storing image data.</li>\n<li>Converting image data from one format to another (for export to each file format).</li>\n<li>Exporting image data.</li>\n</ul>\n\n<p>It would be cleaner to split this up accordingly. Something like the following:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;cstdint&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\n// IMAGE STORAGE:\ntemplate&lt;class T, std::size_t Size&gt;\nstruct Pixel\n{\n std::array&lt;T, Size&gt; Data;\n};\n\nusing Pixel_BW = Pixel&lt;bool, 1u&gt;;\nusing Pixel_Gray8 = Pixel&lt;std::uint8_t, 1u&gt;;\nusing Pixel_RGB8 = Pixel&lt;std::uint8_t, 3u&gt;;\n\ntemplate&lt;class PixelT&gt;\nclass Image\n{\npublic:\n\n Image(std::size_t width, std::size_t height, PixelT initialValue):\n m_width(width),\n m_height(height),\n m_data(width * height)\n {\n\n }\n\n PixelT const&amp; At(std::size_t x, std::size_t y) const\n {\n return m_data.at(GetIndex(x, y));\n }\n\n PixelT&amp; At(std::size_t x, std::size_t y)\n {\n return m_data.at(GetIndex(x, y));\n }\n\n // ...\n\nprivate:\n\n std::size_t GetIndex(std::size_t x, std::size_t y) const\n {\n return x + m_width * y;\n }\n\n std::size_t m_width;\n std::size_t m_height;\n std::vector&lt;PixelT&gt; m_data;\n};\n\n// CONVERT:\nImage&lt;Pixel_BW&gt; ConvertRGBToBW(Image&lt;Pixel_RGB8&gt; const&amp; image)\n{\n auto result = Image&lt;Pixel_BW&gt;(image.GetWidth(), image.GetHeight(), false);\n\n // ... convert\n // ... for each (x, y): result.At(x, y) = ConvertRGBPixelToBWPixel(image.At(x, y));\n\n return result;\n}\n\n// EXPORT:\nvoid ExportPBM(std::string const&amp; fileName, Image&lt;Pixel_BW&gt; const&amp; data)\n{\n // ... export\n}\n\nvoid ExportPGM(std::string const&amp; fileName, Image&lt;Pixel_Gray&gt; const&amp; data)\n{\n // ... export\n}\n\nvoid ExportPPM(std::string const&amp; fileName, Image&lt;Pixel_RGB&gt; const&amp; data)\n{\n // ... export\n}\n</code></pre>\n\n<p>Making <code>Pixel</code> an externally visible class and templating <code>Image</code> on it is much more flexible, and allows us to create whatever image types we need. We can access elements of the array by index, or we could use inheritance instead of typedefs to get named accessors for each component, e.g.:</p>\n\n<pre><code>struct Pixel_RGB8 : Pixel&lt;std::uint8_t, 3u&gt;\n{\n std::uint8_t const&amp; R() const\n {\n return Data[0];\n }\n\n std::uint8_t&amp; R()\n {\n return Data[0];\n }\n\n // ... G(), B()\n};\n</code></pre>\n\n<p>This would also provide type safety for storing images with the same component types, but different meanings (e.g. RGB vs YUV).</p>\n\n<p>Since there are lots of different ways to convert an image from RGB to Grayscale (e.g. specifying different multipliers for each color component) it's more flexible to separate the conversion from the image export. Using separate functions like this does create an extra copy of the image data, but that probably isn't a concern unless working with very large images. (And we could solve that issue by creating an <code>ImageView</code> class that performs the conversion on accessing a pixel).</p>\n\n<hr>\n\n<p>This does make creating colors a little more difficult, since something like \"magenta\" doesn't really make sense for a black and white image. The simplest thing to do is probably to define the constants that do make sense for each pixel type:</p>\n\n<pre><code>namespace Colors\n{\n\n constexpr auto Black_BW = Pixel_BW{ false };\n constexpr auto White_BW = Pixel_BW{ true };\n\n constexpr auto Black_RGB8 = Pixel_RGB8{ 0, 0, 0 };\n constexpr auto White_RGB8 = Pixel_RGB8{ 255, 255, 255 };\n // ...\n\n constexpr auto Black_RGB32F = Pixel_RGB32F{ 0.f, 0.f, 0.f };\n constexpr auto White_RGB32F = Pixel_RGB32F{ 1.f, 1.f, 1.f };\n // ...\n\n} // Colors\n</code></pre>\n\n<p>We could perhaps use templates or multiplication to reduce duplication between different RGB pixel types.</p>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T10:29:03.433", "Id": "210805", "ParentId": "210580", "Score": "6" } } ]
{ "AcceptedAnswerId": "210805", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T02:27:36.507", "Id": "210580", "Score": "2", "Tags": [ "c++", "image", "enum" ], "Title": "Image pixel-editing class with an enum for colors" }
210580
<p>I'm creating a login system and I have been reading a lot about the security measures needed to prevent session hijacking, fixation, and injection attacks, etc. These two Stack Overflow posts were particularly helpful: <a href="https://stackoverflow.com/questions/8419332/proper-session-hijacking-prevention-in-php">Link</a> <a href="https://stackoverflow.com/questions/5081025/php-session-fixation-hijacking#5081453">Link 2</a></p> <p>Below is my login system so far. Have I sufficiently protected myself against attacks?</p> <pre><code> &lt;?php // convert password to hash function passwordHash($string) { return password_hash($string, PASSWORD_DEFAULT); } // compare password to hash function passwordVerify($string, $hash) { return password_verify($string, $hash); } // authenticate login password function login($submitted_password, $password, $username) { global $link; if(passwordVerify($submitted_password, $password)) { ini_set('session.use_trans_sid', FALSE); ini_set('session.entropy_file', '/dev/urandom'); ini_set('session.hash_function', 'whirlpool'); ini_set('session.use_only_cookies', TRUE); ini_set('session.cookie_httponly', TRUE); ini_set('session.cookie_lifetime', 1200); ini_set('session.cookie_secure', TRUE); session_start(); $link-&gt;query("SELECT id, password, username, user_level FROM users WHERE username = :username"); $link-&gt;bind(':username', $username); $link-&gt;execute(); $row = $link-&gt;getOneRow(); $link-&gt;closeStream(); $id = $row['id']; $username = $row['username']; $user_level = $row['user_level']; $_SESSION['userID'] = $id; $_SESSION['username'] = $username; $_SESSION['user_level'] = $user_level; $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR']; $_SESSION['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT']; // store in db to use in page_protect() $user_ip = $_SERVER['REMOTE_ADDR']; $useragent_hash = passwordHash($_SESSION['HTTP_USER_AGENT']); $link-&gt;query("UPDATE users SET user_ip = :user_ip, useragent_hash = :useragent_hash WHERE id = :id"); $link-&gt;bind(':user_ip', $user_ip); $link-&gt;bind(':useragent_hash', $useragent_hash); $link-&gt;bind(':id', $id); $link-&gt;execute(); $link-&gt;closeStream(); header("Location: dashboard.php"); exit(); } else { $error = "Username or password error"; // password fails } } // function called by every page requiring you to be logged in function page_protect() { global $link; if (session_status() == PHP_SESSION_NONE) { session_start(); } if(!isset($_SESSION['user_ip']) || $_SESSION['user_ip'] != $_SERVER['REMOTE_ADDR']) { logout(); exit(); } // referenced in question #5 below if (!isset($_SESSION['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] != $_SESSION['HTTP_USER_AGENT']) { logout(); exit(); } // check that IP address/useragent hash stored in db at login match current session variables $link-&gt;query("SELECT useragent_hash, user_ip FROM users WHERE username = :username"); $link-&gt;bind(':username', $_SESSION['username']); $link-&gt;execute(); $row = $link-&gt;getOneRow(); $link-&gt;closeStream(); $user_ip = $row['user_ip']; $useragent_hash = $row['useragent_hash']; if($_SESSION['user_ip'] != $user_ip || !passwordVerify($_SESSION['HTTP_USER_AGENT'], $useragent_hash)) { logout(); exit(); } session_regenerate_id(true); } function logout() { if (session_status() == PHP_SESSION_NONE) { session_start(); } unset($_SESSION); session_unset(); session_destroy(); header("Location: index.php"); exit(); } ?&gt; </code></pre> <ol> <li><p>Am I missing anything or does anything look wrong?</p></li> <li><p>I'm not sure I'm using <code>session_regenerate_id()</code> in a good spot. I know it needs to be called periodically, so I figured every time a protected page is called would be good.</p></li> <li><p>All of the <code>ini_set</code>'s only appear before the <code>session_start()</code> in the login function. However, the top of each page protected with <code>page_protect()</code> has a <code>session_start()</code>. Should it be preceded by all of the same <code>ini_set</code>'s on every page, or once they're set during the initial login, they stay set?</p></li> <li><p>Should I remove this line? <code>ini_set('session.cookie_lifetime', 1200);</code> That would require the user to login again after 20 minutes. I think it would be good to log the user out after 20 minutes of inactivity, but not after 20 minutes of moving around the site.</p></li> <li><p>In <code>page_protect</code>, when I check the IP and user agent hash, should I use <code>&amp;&amp;</code> instead of <code>||</code>? If both conditions are met, something is definitely amiss.</p></li> </ol>
[]
[ { "body": "<p>First of all, you are heavily overthinking it. And, as a result, over-engineer the code, making it mostly overkill. A theory is a good thing, in reality it is always a trade-off between security and user experience. For example, on most sites, including Stack Overflow, a user is \"remembered\", which is essentially like an endless session which doesn't care for the changed IP address. </p>\n\n<p>Besides, you must take any information that is older than 2-3 years with a pinch of salt. For example, when these 2 answers have been written, HTTPS weren't a commonplace thing. But now it is, making most of these measures obsoleted. Yet at the same time HTTPS is <strong>way much more important</strong> than most of these tricks. </p>\n\n<p>Besides, I just don't understand some measures you are taking. Why you are hashing a user agent? Or why you're checking a user agent and an ip address both against a session and a database? Isn't just a session enough? Or that decision to set the cookie lifetime. As far as I remember, the cookie would renewed at each request, so it shouldn't be an issue, but really. Did you <em>ever</em> try to work with a site with such a restriction? Even my bank logs me out after the inactivity timeout, not every 20 minutes. And your site is not a bank nor anything of similar level of security.</p>\n\n<p>Some levels of verbosity I just don't understand. </p>\n\n<pre><code> $id = $row['id'];\n $_SESSION['userID'] = $id;\n</code></pre>\n\n<p>can't we have it already as <code>$_SESSION['userID'] = $row['id'];</code>?</p>\n\n<p>So in the end I would </p>\n\n<ul>\n<li>first and foremost make your site https</li>\n<li>use <code>session_set_cookie_params()</code> instead of that set of ini_set before each session_start(), because PHP's execution is atomic, each new instance knows nothing of the settings made in the other instance</li>\n<li>make <code>page_protect()</code> just check the user_id in the session. it should be enough.</li>\n</ul>\n\n<p>There are other issues in this code</p>\n\n<p>Your database wrapper is <a href=\"https://phpdelusions.net/pdo/common_mistakes#statefulness\" rel=\"nofollow noreferrer\">stateful</a>. Means the first query you will run in a loop will give you unexpected results. </p>\n\n<p>Your wrapper should be either spit in two classes, as PDO itself does, or offer methods that give you the desired result in one run, without storing any state. For example,</p>\n\n<pre><code> $sql = \"SELECT id, password, username, user_level FROM users WHERE username = ?\";\n $row = $link-&gt;getOneRow($sql, [$username]);\n</code></pre>\n\n<p>And you may note that the bind function is overkill as well. PDO can accept query parameters as an array, which i way more convenient. I even wrote an article about usual misconceptions in database wrappers linked above, you may find it useful. </p>\n\n<p>Your database wrapper is accessed via global keyword which is unanimously frowned upon. At least make it a singleton, which is also despised but at least cannot be written over. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T16:55:04.797", "Id": "407113", "Score": "0", "body": "I appreciate the detailed response. I'm going through my code page by page updating all the database queries now to start off. I read a lot on phpdelusions.net and I'm basically structuring my queries the way it suggests there now. When I finish updating my code, should I edit the above post or start a new one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T16:59:55.913", "Id": "407114", "Score": "0", "body": "The rules for this site say that it should be a new one. Besides, I would suggest to post your question regarding session security on https://security.stackexchange.com/ which is specifically dedicated t security" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:26:20.127", "Id": "407124", "Score": "0", "body": "Is there a way to create those same ini_set properties through session_set_cookie_params()? I'm having trouble on the first one, session.use_trans_sid, for example. When I search for \"use_trans_sid\" the only results that come up are related to setting it through ini_set()." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:28:23.967", "Id": "407126", "Score": "0", "body": "session.use_trans_sid's default value is 0. I wonder why would you bother to set it to 0 again, but no, it's impossible through session_set_cookie_params" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:35:51.323", "Id": "407129", "Score": "0", "body": "Then how would I set the same set_ini parameters, i.e.the entropy file or hash function, using session_set_cookie_params()?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:37:11.550", "Id": "407131", "Score": "0", "body": "To me, all this stuff is overkill as well, as for the current PHP version all parameters' default values are already good. including enthropy and hash function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T01:37:39.767", "Id": "407162", "Score": "0", "body": "Got it, thanks! I'm still working on cleaning up my code." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T10:32:54.623", "Id": "210597", "ParentId": "210584", "Score": "3" } }, { "body": "<p>A few things I noticed,</p>\n\n<p>First of all this is plain wrong (if it's pure PDO):</p>\n\n<pre><code>$link-&gt;query(\"SELECT useragent_hash, user_ip FROM users WHERE username = :username\");\n$link-&gt;bind(':username', $_SESSION['username']);\n$link-&gt;execute();\n</code></pre>\n\n<blockquote>\n <p><strong>PDO::query</strong> — Executes an SQL statement, returning a result set as a PDOStatement object </p>\n</blockquote>\n\n<p><a href=\"http://php.net/manual/en/pdo.query.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/pdo.query.php</a></p>\n\n<p>This should be <code>PDO::prepare</code> like this:</p>\n\n<pre><code>$stmt = $link-&gt;prepare(\"SELECT useragent_hash, user_ip FROM users WHERE username = :username\");\n$stmt-&gt;bindParam(':username', $_SESSION['username']);\n$stmt-&gt;execute();\n</code></pre>\n\n<p>Also note you have to bind and execute against the PDOStatment object and not the PDO object itself.</p>\n\n<p><strong>Function arguments, and code responsibility</strong></p>\n\n<p>Then even your function arguments:</p>\n\n<pre><code>function login($submitted_password, $password, $username) {\n</code></pre>\n\n<p>You most likely wont know <code>$password</code> at this point, nor should you know it. If you redo your function like this:</p>\n\n<pre><code>//note $submitted_password was renamed as $password\nfunction login($password, $username) {\n global $link;\n\n $stmt = $link-&gt;prepare(\"SELECT id, password, username, user_level FROM users WHERE username = :username\");\n //string arguments can be passed as an array directly to execute\n $stmt-&gt;execute([':username'=&gt;$username]);\n\n if(false !== ($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC))){\n if(passwordVerify($password, $row['password'])) {\n ///...rest of code here\n } else {\n $error = \"Password error\"; // password fails\n }\n }else{\n $error = \"Username error\"; // username fails\n }\n}\n\n/*\n you don't have to do separate errors for Username &amp; Password,\n in fact there is a good argument to keep these errors the same \n from the end users perspective.\n*/\n</code></pre>\n\n<p>This way you only need the submitted username, and password. Which are both easily available from a login form. Another thing to mention, is that after the password check you don't verify the row data. It's probably unnecessary given the larger context. For example if you had to previously (before calling login) pull the user data to get the encrypted password. Then you know that the user must be valid. However, when looking at the code as a single unit, it should be verified right when it's pulled from the DB. Because, if that larger context changes then there is no check being done.</p>\n\n<p>Instead you can consolidate it, by just letting the login function take care of pulling the stored password at the same time it's checking the username (by querying for it).</p>\n\n<p>What I mean by <strong>code responsibility</strong> is some other code must be getting the password from the DB, otherwise how would you know the stored password. This code whatever it is, really shouldn't be responsible for that. On top of that every time you call login, you will have to pull that password before hand. So it's better to wrap those operations into login function. It just makes more sense to do it that way and have the arguments both be end user submitted data, instead of a mix of stored data and user data.</p>\n\n<p>Hope that makes sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:01:58.087", "Id": "407118", "Score": "0", "body": "There is no PDOStatement:bind() method :) And no, it's not pure PDO" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:03:49.353", "Id": "407119", "Score": "0", "body": "The bind method is in my PDO object: public function query($query) {\n $this->sql = $this->dbConnection->prepare($query);\n }\n public function bind($param, $value) {\n $this->sql->bindParam($param, $value);\n }\nHowever, as I said in my comment above, I'm currently redoing all of my database queries throughout the code to the way suggested on phpdelusions.net" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:04:49.280", "Id": "407120", "Score": "0", "body": "Thats right its `bindParam` To be honest I almost never use that ... lol ... i sort of had a feeling it wasn't \"pure\" PDO. But what I said about the function args still hold. You souldn't pass the encrypted password to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:20:09.060", "Id": "407122", "Score": "0", "body": "What you said about code responsibility makes sense. I'm also now currently redoing my login function per your suggestions. I'm glad I asked for help. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:22:57.527", "Id": "407123", "Score": "0", "body": "Sure, I always try to make functions/methods or even classes do just one thing and to it well. They should be a complete operation, taking as little setup to call as possible. They should handle as raw of data as possible and return as finished a product as possible. If that makes sense. What do they call that a black box, where the implementation details of the function don't matter to the outside world." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:27:43.203", "Id": "407125", "Score": "0", "body": "@John - The only other thing I would add is that wrapping this in a class would be worth while. Then you can include things like `getCurrentUserId` `logout` `getLogoutLink` etc.. all in one place. Personally I usually have a `User `Class for data storage and then a `UserFactory` class for login and other functions. With PDO you can even fetch the data right into a class. So for example you can `$stmt->fetch(PDO::FETCH_CLASS, 'User');`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:36:52.807", "Id": "407130", "Score": "0", "body": "All of that also makes sense as well. Going through this code is turning out to be a monumental task, but I'm planning to repost once I've made changes. Thanks again for your help. I'm learning a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T19:34:39.807", "Id": "407134", "Score": "0", "body": "Sure, one thing I keep in mind, is that it always takes around 3 times of writing the code to get it perfect. The first time is just getting it to work, then I organize it (simplify it), then I optimize it and comment/document it.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:35:33.280", "Id": "407153", "Score": "0", "body": "I like that, less pressure to get it perfect the first time!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T17:56:21.767", "Id": "210604", "ParentId": "210584", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T03:38:18.627", "Id": "210584", "Score": "3", "Tags": [ "php", "security", "authentication", "session" ], "Title": "PHP login system with prevention for session hijacking, fixation, injection, etc" }
210584
<p>I am wondering whether my template usage in <a href="https://github.com/kaihendry/ltabus/blob/d26fb62dfbe0c7c5798bfa1212f4319b5a9af764/main.go" rel="nofollow noreferrer"><code>main.go</code></a> could be better. For example in other code I notice:</p> <pre><code>var views = template.Must(template.ParseGlob("static/*.tmpl")) </code></pre> <p>Defined outside main, hence the templates are loaded on process start. And then in the handler:</p> <pre><code>views.ExecuteTemplate(w, "passwordprompt.tmpl", map[string]interface{}{}) </code></pre> <p>In my own code, I am wondering if it is worth applying the same practice. Is it possible with functions &amp; the code below?</p> <pre><code>func handleIndex(w http.ResponseWriter, r *http.Request) { funcs := template.FuncMap{ "nameBusStopID": func(s string) string { return bs.nameBusStopID(s) }, "getenv": os.Getenv, } t, err := template.New("").Funcs(funcs).ParseFiles("templates/index.html") if err != nil { log.WithError(err).Error("template failed to parse") http.Error(w, err.Error(), http.StatusInternalServerError) return } arriving, err := busArrivals(r.URL.Query().Get("id")) if err != nil { log.WithError(err).Error("failed to retrieve bus timings") } t.ExecuteTemplate(w, "index.html", arriving) } </code></pre> <p>Please feel free to critique all the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:06:43.313", "Id": "407435", "Score": "0", "body": "could you also post your `templates/index.html` file here ?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T06:32:35.890", "Id": "210589", "Score": "1", "Tags": [ "html", "go", "template" ], "Title": "Displaying Singapore bus arrival times using a Go template" }
210589
<p>I am still fairly new to go, and would appreciate any tips on style, best practices, etc, but am especially interested to know if this non-recursive cartesian product implementation can be made significantly faster (eg, when the number of results in the result set is on the order of 1e9).</p> <p>I've played around with adding more goroutines, but parallelism doesn't seem to help much, if at all. I may be missing a much better approach though. </p> <p><a href="https://play.golang.org/p/H-M6CbmeFoV" rel="nofollow noreferrer">https://play.golang.org/p/H-M6CbmeFoV</a></p> <pre><code>package main import ( "fmt" ) // Given a mixed base, returns a function that: // // Increments a number, represented as a slice of digits, defined // in that base. For example, if our base is 2 3 2, we'll count // like this: // // 0 0 0 ; 0 0 1; 0 1 0; 0 1 1; 0 2 0; 0 2 1; // 1 0 0 ; 1 0 1; 1 1 0; 1 1 1; 1 2 0; 1 2 1; func mixedBaseInc(bases []int) func(*[]int) { return func(digits *[]int) { ret := *digits i := len(ret) - 1 for { base := bases[i] ret[i] = (ret[i] + 1) % base noCarry := ret[i] != 0 if noCarry || i == 0 { return } i-- } } } func pick(indexes []int, params [][]interface{}) []interface{} { ret := make([]interface{}, len(params)) for i, x := range indexes { ret[i] = params[i][x] } return ret } func XProd(params ...[]interface{}) chan []interface{} { var paramLens, digits []int numElms := 1 c := make(chan []interface{}) for _, x := range params { paramLens = append(paramLens, len(x)) numElms *= len(x) digits = append(digits, 0) } inc := mixedBaseInc(paramLens) go func() { defer close(c) for i := 0; i &lt; numElms; i++ { c &lt;- pick(digits, params) inc(&amp;digits) } }() return c } func main() { for x := range XProd([]interface{}{1, 2, 3}, []interface{}{4, 5}) { fmt.Println(x) } } </code></pre>
[]
[ { "body": "<p>I think you should replace <code>mixedBaseInc</code> with a generator that returns the combinations of indexes. That would simplify XProd by taking out <code>numElms</code> and the construction of <code>digits</code>.</p>\n\n<p>That gives you the <em>option</em> to parallelise XProd by instantiating more instances of the goroutine that outputs the product vectors (because the closure no longer binds <code>digits</code>). <em>If</em> that is the bottleneck then that improves throughput.</p>\n\n<p>However it depends on the program where this is used; if most of the work is done by the consumer of the output vectors then the best speed-up is for the consumer to consume in a way that can be parallelised.</p>\n\n<p>An alternative approach is to build the output vectors one element at a time — <a href=\"https://github.com/schwarmco/go-cartesian-product/blob/master/cartesian.go\" rel=\"nofollow noreferrer\">https://github.com/schwarmco/go-cartesian-product/blob/master/cartesian.go</a> for example . That solution has pros and cons and it's a bit more complicated to increase its parallelism, but it might be much better on some inputs (perhaps if there are a large number of small input sets to the product).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T09:46:58.963", "Id": "210595", "ParentId": "210590", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T06:43:03.983", "Id": "210590", "Score": "0", "Tags": [ "go" ], "Title": "Cartesian Product in Go" }
210590
<p>I am trying to make a simple clone of the command line utility <strong>grep</strong>. I'm working on it just for fun and to practice Go. The thing is, I am trying to make it in a way that if several files are given at the command line, a different goroutine is generated to speed up the process. Even so, standard grep still gets results faster by an amount of around 60% less processing time.</p> <p>Here it is the code for it. Can you please provide some opinions about it?</p> <pre><code>package main import ( "bufio" "flag" "fmt" "io" "os" "path/filepath" "regexp" "sync" ) type result struct { Filename string Line string LineNumber int Error error } var strRex string var filenames []string var regRex *regexp.Regexp var wg sync.WaitGroup var allResults []result var verbose = false var recursive string var recursiveFileList []string var fileFilter string var rexfileFilter *regexp.Regexp var inverseSearch bool func init() { var rexError error flag.StringVar(&amp;strRex, "r", "", "Regular expresion to match against the input files") flag.BoolVar(&amp;verbose, "v", false, "It sets verbose output (Basically showing filename and line number for each match)") flag.BoolVar(&amp;inverseSearch, "i", false, "It does what you might expect.. reverse the search") flag.StringVar(&amp;recursive, "R", "", "Recursively find all files starting from the current folder and apply the given search to them") flag.StringVar(&amp;fileFilter, "FF", "", "Filter to be applied to the filenames when used recursevily") flag.Parse() if strRex == "" { fmt.Fprintf(os.Stderr, "The '-r' (regular expression flag is mandatory)\n") os.Exit(1) } regRex, rexError = regexp.Compile(strRex) if rexError != nil { fmt.Fprintf(os.Stderr, "Your regex '%s' cant compile. Error : %s", strRex, rexError.Error()) os.Exit(2) } rexfileFilter, rexError = regexp.Compile(fileFilter) if rexError != nil { fmt.Fprintf(os.Stderr, "Your regex '%s' cant compile. Error : %s", rexfileFilter, rexError.Error()) os.Exit(3) } if recursive != "" { var err error filenames, err = walkDir(recursive) if err != nil { fmt.Fprintf(os.Stderr, "%s", err.Error()) } } else { filenames = flag.Args() } } func main() { stat, err := os.Stdin.Stat() if err != nil { fmt.Fprintf(os.Stderr, "There is an error reading from stdin : %s", err) os.Exit(3) } if (stat.Mode() &amp; os.ModeNamedPipe) != 0 { grepStdin(os.Stdin, regRex) } else { chResults := make(chan *result, 4) wg.Add(len(filenames)) for _, fn := range filenames { go grep(fn, regRex, &amp;wg, chResults) } go func(wait *sync.WaitGroup, ch chan&lt;- *result) { wg.Wait() close(ch) }(&amp;wg, chResults) for res := range chResults { if verbose { formatRes(res, 1) } else { formatRes(res, 2) } } } } func grepStdin(ptr io.Reader, reg *regexp.Regexp) { bf := bufio.NewScanner(ptr) var lineno = 1 for bf.Scan() { // There is no XOR in Golang, so you ahve to do this : if line := bf.Text(); (reg.Match([]byte(line)) &amp;&amp; !inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; inverseSearch) { formatRes(&amp;result{ Line: line, LineNumber: lineno, Error: nil, }, 3) } lineno++ } } func grep(file string, reg *regexp.Regexp, wait *sync.WaitGroup, ch chan&lt;- *result) { fd, err := os.Open(file) if err != nil { ch &lt;- &amp;result{ Filename: file, Error: err, } } bf := bufio.NewScanner(fd) var lineno = 1 for bf.Scan() { // There is no XOR in Golang, so you ahve to do this : if line := bf.Text(); (reg.Match([]byte(line)) &amp;&amp; !inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; inverseSearch) { ch &lt;- &amp;result{ Filename: file, Line: line, LineNumber: lineno, Error: nil, } } lineno++ } wg.Done() } func formatRes(r *result, format int) { if format == 1 { if r.Error == nil { fmt.Printf("%d - %s - %s\n", r.LineNumber, r.Filename, r.Line) } else { fmt.Fprintf(os.Stderr, "%s - %s \n", r.Filename, r.Error) } } if format == 2 { if r.Error == nil { fmt.Printf("%s\n", r.Line) } else { fmt.Fprintf(os.Stderr, "%s - %s \n", r.Filename, r.Error) } } if format == 3 { if r.Error == nil { fmt.Printf("%s\n", r.Line) } else { fmt.Fprintf(os.Stderr, "%s\n", r.Error) } } } func walkDir(path string) ([]string, error) { list := make([]string, 0, 50) err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if fileFilter != "" { if rexfileFilter.Match([]byte(filepath.Base(path))) { list = append(list, path) } } else { list = append(list, path) } return nil // Unreachable code }) if err != nil { return nil, err } return list, nil } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T13:06:10.230", "Id": "407089", "Score": "3", "body": "Code must be correct. To be sure that code is correct, code must be readable. I find your double-spaced code to be unreadable." } ]
[ { "body": "<pre><code>if line := bf.Text(); (reg.Match([]byte(line)) &amp;&amp; !inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; inverseSearch) {\n</code></pre>\n\n<p>As in other C-like languages, golang <a href=\"https://golang.org/ref/spec#Logical_operators\" rel=\"nofollow noreferrer\">evaluates binary logical operators conditionally left-to-right</a>. As written, the program is often going to evaluate the reg.Match() twice, because it appears twice and in each subexpression it is tested before <code>inverseSearch</code>. As this is the program's most expensive operation, that's significant for performance.</p>\n\n<pre><code>if line := bf.Text(); (!inverseSearch &amp;&amp; reg.Match([]byte(line))) || (inverseSearch &amp;&amp; !reg.Match([]byte(line))) {\n</code></pre>\n\n<p>should avoid the double evaluation. Or write an xor helper function.</p>\n\n<p>Other things:</p>\n\n<p>Don't test for stdin being usable if you aren't reading from it. It's common for programs executing a program in a subprocess to close filehandles that the program shouldn't need to use. In other words <code>/bin/grep foo filename &lt;&amp;-</code> works, your <code>./grep -r foo filename &lt;&amp;-</code> does not and should.</p>\n\n<p>Rewrite/replace grepStdin() so that it reuses grep(). Nobody likes having the algorithm implemented twice in the same program. You can use /dev/stdin as a filename for stdin on *nix; or, keep the file opening part separate and have a common function for grepping over the opened file handle used by both codepaths.</p>\n\n<p>The <code>format</code> parameter to formatRes uses magic constant values that one has to read its implementation to understand. It would be better to replace it with <code>verbose bool</code> so the verbose flag can be passed directly and its meaning is then obvious. The stdin case would be better not to treat specially here also.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T16:23:10.853", "Id": "210601", "ParentId": "210591", "Score": "4" } }, { "body": "<blockquote>\n <p>The thing is, even so, standard grep still gets results faster by an amount of 60 % less processing time</p>\n</blockquote>\n\n<p>For more information on what makes GNU grep fast, read <a href=\"https://lists.freebsd.org/pipermail/freebsd-current/2010-August/019310.html\" rel=\"noreferrer\">this</a> by the original author.</p>\n\n<hr>\n\n<p>Here is some feedback on writing idiomatic Go.</p>\n\n<h2>Lines</h2>\n\n<p>Your code is oddly formatted.</p>\n\n<p>It is very uncommon to have empty lines everywhere. In your code, empty lines more than double the length of your code. In most cases, I only add extra lines to separate functions, structs, if statements, for loops, etc.</p>\n\n<pre><code>package main\n\n\nimport (\n \"bufio\"\n\n \"flag\"\n\n \"fmt\"\n\n \"io\"\n\n \"os\"\n\n \"path/filepath\"\n\n \"regexp\"\n\n \"sync\"\n\n)\n\n\ntype result struct {\n\n Filename string\n\n Line string\n\n LineNumber int\n\n Error error\n\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"flag\"\n \"fmt\"\n \"io\"\n \"os\"\n \"path/filepath\"\n \"regexp\"\n \"sync\"\n)\n\n\ntype result struct {\n Filename string\n Line string\n LineNumber int\n Error error\n}\n</code></pre>\n\n<h2>Line length</h2>\n\n<p>Keep lines to a length of 80 characters. It makes code easier to read on smaller monitors or if you split your screen to view multiple things.</p>\n\n<pre><code>flag.StringVar(&amp;strRex, \"r\", \"\", \"Regular expresion to match against the input files\")\n\nflag.BoolVar(&amp;verbose, \"v\", false, \"It sets verbose output (Basically showing filename and line number for each match)\")\n\nflag.BoolVar(&amp;inverseSearch, \"i\", false, \"It does what you might expect.. reverse the search\")\n\nflag.StringVar(&amp;recursive, \"R\", \"\", \"Recursively find all files starting from the current folder and apply the given search to them\")\n\nflag.StringVar(&amp;fileFilter, \"FF\", \"\", \"Filter to be applied to the filenames when used recursevily\")\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>flag.StringVar(&amp;strRex, \"r\", \"\",\n \"Regular expresion to match against the input files\")\n\nflag.BoolVar(&amp;verbose, \"v\", false,\n \"It sets verbose output (Basically showing filename and line number \"+\n \"for each match)\")\n\nflag.BoolVar(&amp;inverseSearch, \"i\", false,\n \"It does what you might expect.. reverse the search\")\n\nflag.StringVar(&amp;recursive, \"R\", \"\",\n \"Recursively find all files starting from the current folder and \"+\n \"apply the given search to them\")\n\nflag.StringVar(&amp;fileFilter, \"FF\", \"\",\n \"Filter to be applied to the filenames when used recursevily\")\n</code></pre>\n\n<h2>Use a C-style for loop</h2>\n\n<p>In <code>grepStdin()</code> you initialize <code>lineno</code>, increment it and only use it in the for loop. That's a standard for loop. Once inside the for loop, we can rename it to <code>l</code> because it's purpose is clear from it's usage.</p>\n\n<pre><code>var lineno = 1\n\nfor bf.Scan() {\n // There is no XOR in Golang, so you ahve to do this:\n if line := bf.Text(); (reg.Match([]byte(line)) &amp;&amp; !inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; inverseSearch) {\n formatRes(&amp;result{\n Line: line,\n LineNumber: lineno,\n Error: nil,\n }, 3)\n }\n lineno++\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>for l := 1; bf.Scan(); l++ {\n // There is no XOR in Golang, so you ahve to do this:\n if line := bf.Text(); (reg.Match([]byte(line)) &amp;&amp; !inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; inverseSearch) {\n formatRes(&amp;result{\n Line: line,\n LineNumber: l,\n Error: nil,\n }, 3)\n }\n}\n</code></pre>\n\n<h2>Combine multiple <code>var</code> declarations</h2>\n\n<p>You can combine multiple variables declared with <code>var</code> as such:</p>\n\n<pre><code>var strRex string\n\nvar filenames []string\n\nvar regRex *regexp.Regexp\n\nvar wg sync.WaitGroup\n\nvar allResults []result\n\nvar verbose = false\n\nvar recursive string\n\nvar recursiveFileList []string\n\nvar fileFilter string\n\nvar rexfileFilter *regexp.Regexp\n\nvar inverseSearch bool\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>var (\n strRex string\n filenames []string\n regRex *regexp.Regexp\n wg sync.WaitGroup\n allResults []result\n verbose = false\n recursive string\n recursiveFileList []string\n fileFilter string\n rexfileFilter *regexp.Regexp\n inverseSearch bool\n)\n</code></pre>\n\n<p>This is far more readable.</p>\n\n<h2>Use <code>log</code> to write to standard error</h2>\n\n<p>You can utilize the <code>log</code> package to print (possibly fatal) errors to standard error.</p>\n\n<pre><code>fmt.Fprintf(os.Stderr,\n \"The '-r' (regular expression flag is mandatory)\\n\")\n\nos.Exit(1)\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>if strRex == \"\" {\n log.Fatalln(\"The regular expression flag '-r' is mandatory\")\n}\n</code></pre>\n\n<p>And</p>\n\n<pre><code>if rexError != nil {\n fmt.Fprintf(os.Stderr, \"Your regex '%s' cant compile. Error : %s\", strRex, rexError.Error())\n os.Exit(2)\n\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>if rexError != nil {\n log.Fatalf(\"Your regex '%s' cant compile. Error : %s\\n\", strRex,\n rexError)\n}\n</code></pre>\n\n<p>Notice that you don't need to call <code>Error()</code> to get the string from it.</p>\n\n<p>By doing this, you won't get custom return values. I don't think they're very useful in lieu of a good error message.</p>\n\n<h2>Combine if and assignment</h2>\n\n<pre><code>var err error\n\nfilenames, err = walkDir(recursive)\n\nif err != nil {\n fmt.Fprintf(os.Stderr, \"%s\", err.Error())\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>var err error\n\nif filenames, err = walkDir(recursive); err != nil {\n log.Println(err)\n}\n</code></pre>\n\n<h2>Move things out of the global scope</h2>\n\n<p>Your <code>wg</code> wait group is in the global scope. It doesn't need to be. You already pass <code>wait</code> to <code>grep()</code>, so use it.</p>\n\n<p><code>allResults</code> is never used. <code>recursiveFileList</code> is never used.</p>\n\n<p>We can also move all of your flag variables to a common <code>struct</code>. This is just a preference, but it tells readers what is a flag and what isn't.</p>\n\n<h2>Use a switch statement</h2>\n\n<p>In <code>formatRes</code> you can use a switch statement instead of multiple if statements.</p>\n\n<p>You can also clean up how you print things, like using <code>Println</code> instead of <code>Printf</code>.</p>\n\n<pre><code>switch format {\ncase 1:\n if r.Error == nil {\n fmt.Printf(\"%d - %s - %s\\n\", r.LineNumber, r.Filename, r.Line)\n } else {\n log.Printf(\"%s - %s\\n\", r.Filename, r.Error)\n }\n break\ncase 2:\n if r.Error == nil {\n fmt.Printf(\"%s\\n\", r.Line)\n } else {\n log.Printf(\"%s - %s\\n\", r.Filename, r.Error)\n }\n break\ncase 3:\n if r.Error == nil {\n fmt.Printf(\"%s\\n\", r.Line)\n } else {\n log.Println(r.Error)\n }\n}\n</code></pre>\n\n<h2>Move your condition to a separate function</h2>\n\n<p>Your condition</p>\n\n<pre><code>(reg.Match([]byte(line)) &amp;&amp; !fl.inverseSearch) || (!reg.Match([]byte(line)) &amp;&amp; fl.inverseSearch)\n</code></pre>\n\n<p>Is long, and as Colin points out, you can take advantage of short circuiting.</p>\n\n<p>Go does not provide XOR, but <a href=\"https://stackoverflow.com/a/23025720/6789498\">it doesn't need to</a>. I'll leave that for you to implement.</p>\n\n<p>We can define a function as such:</p>\n\n<pre><code>func match(reg *regexp.Regexp, line string) bool {\n return !fl.inverseSearch &amp;&amp; reg.Match([]byte(line)) || (fl.inverseSearch &amp;&amp; !reg.Match([]byte(line)))\n}\n</code></pre>\n\n<h2>Use <code>grepStdin()</code> in <code>grep()</code></h2>\n\n<p>As Colin says, they contain duplicate code. I'll leave that for you to implement.</p>\n\n<h2>Conclusion</h2>\n\n<p>There are many other places to clean up the code, but I think you'll get the gist. Here is the final code I ended up with:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"flag\"\n \"fmt\"\n \"io\"\n \"log\"\n \"os\"\n \"path/filepath\"\n \"regexp\"\n \"sync\"\n)\n\ntype result struct {\n Filename string\n Line string\n LineNumber int\n Error error\n}\n\ntype flags struct {\n strRex string\n recursive string\n fileFilter string\n verbose bool\n inverseSearch bool\n}\n\nvar (\n fl flags\n filenames []string\n regRex *regexp.Regexp\n rexfileFilter *regexp.Regexp\n)\n\nfunc init() {\n dfl := flags{\n strRex: \"\",\n verbose: false,\n inverseSearch: false,\n recursive: \"\",\n fileFilter: \"\",\n }\n\n var rexError error\n\n flag.StringVar(&amp;fl.strRex, \"r\", dfl.strRex,\n \"Regular expresion to match against the input files\")\n\n flag.StringVar(&amp;fl.recursive, \"R\", dfl.recursive,\n \"Recursively find all files starting from the current folder and \"+\n \"apply the given search to them\")\n\n flag.StringVar(&amp;fl.fileFilter, \"FF\", dfl.fileFilter,\n \"Filter to be applied to the filenames when used recursevily\")\n\n flag.BoolVar(&amp;fl.verbose, \"v\", dfl.verbose,\n \"It sets verbose output (Basically showing filename and line number \"+\n \"for each match)\")\n\n flag.BoolVar(&amp;fl.inverseSearch, \"i\", dfl.inverseSearch,\n \"It does what you might expect.. reverse the search\")\n\n flag.Parse()\n\n if fl.strRex == \"\" {\n log.Fatalln(\"The regular expression flag '-r' is mandatory\")\n }\n\n regRex, rexError = regexp.Compile(fl.strRex)\n\n if rexError != nil {\n log.Fatalf(\"Your regex '%s' cant compile. Error : %s\\n\", fl.strRex,\n rexError)\n }\n\n rexfileFilter, rexError = regexp.Compile(fl.fileFilter)\n\n if rexError != nil {\n log.Fatalf(\"Your regex '%s' cant compile. Error : %s\", rexfileFilter,\n rexError)\n }\n\n if fl.recursive != \"\" {\n var err error\n\n if filenames, err = walkDir(fl.recursive); err != nil {\n log.Println(err)\n }\n } else {\n filenames = flag.Args()\n }\n}\n\nfunc main() {\n stat, err := os.Stdin.Stat()\n\n if err != nil {\n log.Fatalf(\"There is an error reading from stdin: %s\", err)\n }\n\n var wait sync.WaitGroup\n\n if (stat.Mode() &amp; os.ModeNamedPipe) != 0 {\n grepStdin(os.Stdin, regRex)\n } else {\n chResults := make(chan *result, 4)\n\n wait.Add(len(filenames))\n\n for _, fn := range filenames {\n go grep(fn, regRex, &amp;wait, chResults)\n }\n\n go func(wait *sync.WaitGroup, ch chan&lt;- *result) {\n wait.Wait()\n\n close(ch)\n }(&amp;wait, chResults)\n\n for res := range chResults {\n if fl.verbose {\n formatRes(res, 1)\n } else {\n formatRes(res, 2)\n }\n }\n }\n}\n\nfunc match(reg *regexp.Regexp, line string) bool {\n return !fl.inverseSearch &amp;&amp; reg.Match([]byte(line)) || (fl.inverseSearch &amp;&amp; !reg.Match([]byte(line)))\n}\n\nfunc grepStdin(ptr io.Reader, reg *regexp.Regexp) {\n bf := bufio.NewScanner(ptr)\n\n for l := 1; bf.Scan(); l++ {\n if line := bf.Text(); match(reg, line) {\n formatRes(&amp;result{\n Line: line,\n LineNumber: l,\n Error: nil,\n }, 3)\n }\n }\n}\n\nfunc grep(file string, reg *regexp.Regexp, wait *sync.WaitGroup,\n ch chan&lt;- *result) {\n\n fd, err := os.Open(file)\n\n if err != nil {\n ch &lt;- &amp;result{\n Filename: file,\n Error: err,\n }\n }\n\n bf := bufio.NewScanner(fd)\n\n for l := 1; bf.Scan(); l++ {\n if line := bf.Text(); match(reg, line) {\n ch &lt;- &amp;result{\n Filename: file,\n Line: line,\n LineNumber: l,\n Error: nil,\n }\n }\n }\n\n wait.Done()\n}\n\nfunc formatRes(r *result, format int) {\n switch format {\n case 1:\n if r.Error == nil {\n fmt.Printf(\"%d - %s - %s\\n\", r.LineNumber, r.Filename, r.Line)\n } else {\n log.Printf(\"%s - %s\\n\", r.Filename, r.Error)\n }\n break\n case 2:\n if r.Error == nil {\n fmt.Println(r.Line)\n } else {\n log.Printf(\"%s - %s\\n\", r.Filename, r.Error)\n }\n break\n case 3:\n if r.Error == nil {\n fmt.Println(r.Line)\n } else {\n log.Println(r.Error)\n }\n }\n}\n\nfunc walkDir(path string) ([]string, error) {\n list := make([]string, 0, 50)\n\n err := filepath.Walk(\".\",\n func(path string, info os.FileInfo, err error) error {\n if err != nil {\n return err\n }\n\n if fl.fileFilter != \"\" {\n if rexfileFilter.Match([]byte(filepath.Base(path))) {\n list = append(list, path)\n }\n } else {\n list = append(list, path)\n }\n\n return nil\n })\n\n if err != nil {\n return nil, err\n }\n\n return list, nil\n}\n</code></pre>\n\n<p>In my opinion, it's far more readable and to-the-point.</p>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:39:03.270", "Id": "210605", "ParentId": "210591", "Score": "6" } } ]
{ "AcceptedAnswerId": "210601", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T07:11:33.000", "Id": "210591", "Score": "4", "Tags": [ "regex", "go", "concurrency", "search" ], "Title": "Go grep command clone" }
210591
<p>I am a beginner in the python language. I wrote a BMI calculator and I am wondering if there are any improvements I could make to the code. This is the code below:</p> <pre><code>print('Enter your weight in kilo:') weightInKilo = float(input()) print('Enter your height in feet:') heightInFeet = float(input()) heightInMeter = heightInFeet * 12 * 0.025 bodyMassIndex = weightInKilo / (heightInMeter ** 2) if bodyMassIndex &lt; 15: print('Your BMI = ' + str(bodyMassIndex) + ' You are very severely underweight.') elif bodyMassIndex &gt;= 15 and bodyMassIndex &lt;= 16 : print('Your BMI = ' + str(bodyMassIndex) + ' You are severely underweight.') elif bodyMassIndex &gt; 16 and bodyMassIndex &lt;= 18.5: print('Your BMI = ' + str(bodyMassIndex) + ' You are underweight.') elif bodyMassIndex &gt; 18.5 and bodyMassIndex &lt;= 25: print('Your BMI = ' + str(bodyMassIndex) + ' You are Normal(healthy weight).') elif bodyMassIndex &gt; 25 and bodyMassIndex &lt;= 30: print('Your BMI = ' + str(bodyMassIndex) + ' You are overweight.') elif bodyMassIndex &gt; 30 and bodyMassIndex &lt;= 35: print('Your BMI = ' + str(bodyMassIndex) + ' You are moderately obese.') elif bodyMassIndex &gt; 35 and bodyMassIndex &lt;= 40: print('Your BMI = ' + str(bodyMassIndex) + ' You are severely obese.') elif bodyMassIndex &gt; 40: print('Your BMI = ' + str(bodyMassIndex) + ' You are very severely obese.') input('Please press Enter to exit') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T23:50:52.690", "Id": "407258", "Score": "1", "body": "FYI, some [2017 research](https://www.ncbi.nlm.nih.gov/pubmed/28953680) indicates that waist-to-height ratio is a better obesity index when predicting 'metabolic syndrome' for individuals. You could extend your code to return that information as well, or at least note in the output that the code judges an 'obese' condition based only on BMI, out of multiple possible obesity indices." } ]
[ { "body": "<p>Well, you could refactor the print part and extract it to a function like this:</p>\n\n<pre><code>def printBMIMessage(bodyMassIndex, message):\n print('Your BMI = ' + str(bodyMassIndex) + ' ' + message)\n\n\nprint('Enter your weight in kilo:')\nweightInKilo = float(input())\n\nprint('Enter your height in feet:')\n\nheightInFeet = float(input())\n\nheightInMeter = heightInFeet * 12 * 0.025\n\nbodyMassIndex = weightInKilo / (heightInMeter ** 2)\n\nif bodyMassIndex &lt; 15:\n printBMIMessage(bodyMassIndex, 'You are very severely underweight.')\n\nelif bodyMassIndex &gt;= 15 and bodyMassIndex &lt;= 16 :\n printBMIMessage(bodyMassIndex, 'You are severely underweight.')\n\nelif bodyMassIndex &gt; 16 and bodyMassIndex &lt;= 18.5:\n printBMIMessage(bodyMassIndex, 'You are underweight.')\n\nelif bodyMassIndex &gt; 18.5 and bodyMassIndex &lt;= 25:\n printBMIMessage(bodyMassIndex, 'You are Normal(healthy weight).')\n\nelif bodyMassIndex &gt; 25 and bodyMassIndex &lt;= 30:\n printBMIMessage(bodyMassIndex, 'You are overweight.')\n\n\nelif bodyMassIndex &gt; 30 and bodyMassIndex &lt;= 35:\n printBMIMessage(bodyMassIndex, 'You are moderately obese.')\n\nelif bodyMassIndex &gt; 35 and bodyMassIndex &lt;= 40:\n printBMIMessage(bodyMassIndex, 'You are severely obese.')\n\nelif bodyMassIndex &gt; 40:\n printBMIMessage(bodyMassIndex, 'You are very severely obese.')\n\ninput('Please press Enter to exit')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T19:59:15.540", "Id": "407138", "Score": "0", "body": "I don't really like the control flow of the `printBMIMessage` function because it allows to do `printBMIMessage(40, 'You are underweight')`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T09:43:55.860", "Id": "210594", "ParentId": "210592", "Score": "2" } }, { "body": "<p>This kind of programming exercice, despite its apparent simplicity, is a good opportunity to learn various things.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Code Style guide called PEP 8</a>. If you begin with Python, I highly recommend reading it every now and then and trying to apply it.</p>\n\n<p>In your case, a few things could be improved regarding style:</p>\n\n<ul>\n<li>blank lines between the different branches of <code>if</code> are more an inconvenience from my point of view</li>\n<li>variables should follow the <code>snake_case</code> naming convention (instead of <code>camelCase</code>)</li>\n</ul>\n\n<p><strong>Builtin <code>input</code></strong></p>\n\n<p>As you've noticed for the end of the function, the <a href=\"https://docs.python.org/3/library/functions.html#input\" rel=\"nofollow noreferrer\"><code>input</code> builtin</a> takes an optional <code>prompt</code> parameter. This could be used at the beginning of the function as well.</p>\n\n<p><strong>Duplicated code</strong></p>\n\n<p>A lot of code looks like the same line with minimal variations. Having duplicated code makes the code more tedious to read and harder to maintain (if you need to change something, you'll need to change it in many places). One of the principles of software programming is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a> (also written DRY).</p>\n\n<p>In your case, we could store the body category in a variable and only print the ouput from a single place:</p>\n\n<p><strong>Chained comparison</strong></p>\n\n<p>This is very specific to Python but instead of <code>body_mass_index &gt; 30 and body_mass_index &lt;= 35</code>, we can write: <code>30 &lt; body_mass_index &lt;= 35</code> using chained <a href=\"https://docs.python.org/3/reference/expressions.html#comparisons\" rel=\"nofollow noreferrer\">comparisons</a>.</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a> are usually frowned upon. In our case, one needs a bit of thinking to understand where the <code>12</code> and <code>0.025</code> come from. A better way to handle this is to store them in a variable with a meaningful name.</p>\n\n<p><em>I am not quite sure about the best naming convention for names related to conversion constant. I've followed the names suggested by <a href=\"https://codereview.stackexchange.com/users/90454/solomon-ucko\">Solomon Ucko</a> in the comments.</em></p>\n\n<hr>\n\n<p>At this stage, we have the following code:</p>\n\n<pre><code>INCHES_PER_FOOT = 12\nMETERS_PER_INCH = 0.0254\n\nweight_in_kilo = float(input('Enter your weight in kilo:'))\nheight_in_feet = float(input('Enter your height in feet:'))\n\nheight_in_meter = height_in_feet * INCHES_PER_FOOT * METERS_PER_INCH\nbody_mass_index = weight_in_kilo / (height_in_meter ** 2)\n\nif body_mass_index &lt; 15:\n category = 'very severely underweight'\nelif 15 &lt;= body_mass_index &lt;= 16 :\n category = 'severely underweight'\nelif 16 &lt; body_mass_index &lt;= 18.5:\n category = 'underweight'\nelif 18.5 &lt; body_mass_index &lt;= 25:\n category = 'Normal(healthy weight)'\nelif 25 &lt; body_mass_index &lt;= 30:\n category = 'overweight'\nelif 30 &lt; body_mass_index &lt;= 35:\n category = 'moderately obese'\nelif 35 &lt; body_mass_index &lt;= 40:\n category = 'severely obese'\nelif body_mass_index &gt; 40:\n category = 'very severely obese'\n\nprint('Your BMI = ' + str(body_mass_index) + ' You are ' + category + '.')\ninput('Please press Enter to exit')\n</code></pre>\n\n<p>Which can still be improved.</p>\n\n<hr>\n\n<p><strong>Mutually exclusive conditions</strong></p>\n\n<p>Because of the way we check <code>body_mass_index</code>, if it is under 15, we get into the first case so there is no need to check <code>elif 15 &lt;= body_mass_index</code> in the <code>else</code> part. This is guaranteed to be always true. Similarly, half the checks have no effect.</p>\n\n<p><strong>Code organisation</strong></p>\n\n<p>To make the code easier to understand (and easier to reuse, to test, etc), it is a good habit to split in into smaller reusable chunks. In our case, defining functions could be a nice touch.</p>\n\n<p><em>Disclaimer: Next paragraph can be a bit overwhelming for a beginner, do not worry if you do not fully get it. It highlights how to solve problems you may not be interested in yet but it is a good chance to do things properly.</em></p>\n\n<p>Also, if we want to be able to actually reuse your functions, we want to be able to <code>import</code> the file. Currently, if we do so, we get stuck into the parts asking for user inputs. Thus, the usual strategy is the following: split your code into 2 parts:</p>\n\n<ul>\n<li><p>code defining functions/constants/classes/etc but without any side-effect or user interactions</p></li>\n<li><p>code actually doing things (input/output, etc) behind an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>. As pointed out by <a href=\"https://codereview.stackexchange.com/users/90454/solomon-ucko\">Solomon Ucko</a>, it's generally a good idea to have this performed via a <code>main()</code> function and have the last two (non-blank) lines be <code>if __name__ == '__main__': main()</code>. This allows the interactivity to be triggered as needed.</p></li>\n</ul>\n\n<hr>\n\n<p>At this stage, we have:</p>\n\n<pre><code>INCHES_PER_FOOT = 12\nMETERS_PER_INCH = 0.0254\n\ndef convert_feet_to_meter(height_in_feet):\n return height_in_feet * INCHES_PER_FOOT * METERS_PER_INCH\n\ndef get_body_mass_index(height_in_meter, weight_in_kilo):\n return weight_in_kilo / (height_in_meter ** 2)\n\ndef get_category(body_mass_index):\n if body_mass_index &lt; 15:\n return 'very severely underweight'\n elif body_mass_index &lt;= 16 :\n return 'severely underweight'\n elif body_mass_index &lt;= 18.5:\n return 'underweight'\n elif body_mass_index &lt;= 25:\n return 'Normal(healthy weight)'\n elif body_mass_index &lt;= 30:\n return 'overweight'\n elif body_mass_index &lt;= 35:\n return 'moderately obese'\n elif body_mass_index &lt;= 40:\n return 'severely obese'\n else:\n return 'very severely obese'\n\ndef main():\n weight_in_kilo = float(input('Enter your weight in kilo:'))\n height_in_feet = float(input('Enter your height in feet:'))\n height_in_meter = convert_feet_to_meter(height_in_feet)\n body_mass_index = get_body_mass_index(height_in_meter, weight_in_kilo)\n category = get_category(body_mass_index)\n print('Your BMI = ' + str(body_mass_index) + ' You are ' + category + '.')\n input('Please press Enter to exit')\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<hr>\n\n<p>Going further, a few more details could be improved.</p>\n\n<p><strong>String formatting</strong></p>\n\n<p>Python offers many tools to format strings so that you do not need to use string concatenations. You can refer to <a href=\"https://pyformat.info/\" rel=\"nofollow noreferrer\">PyFormat.info</a> for documentations and examples.</p>\n\n<p>You could write:</p>\n\n<pre><code>print('Your BMI = %f You are %s.' % (body_mass_index, category))\n</code></pre>\n\n<p>Or the newer technique:</p>\n\n<pre><code>print('Your BMI = {} You are {}.'.format(body_mass_index, category))\n</code></pre>\n\n<p>Also, in Python 3.6, yet another soution was added: <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">F-strings</a>.</p>\n\n<p><strong>Data over code</strong></p>\n\n<p>This may be a bit overkill here but sometimes a lot of code can be replaced by a small amount of code working on a properly filled data structure. In our case, the <code>get_category</code> function does the same thing for all categories: check the if we are under a given limit and if so, return the category name.</p>\n\n<p><em>Disclaimer: Next part works under the assumption that <code>body_mass_index &lt; 15</code> should actually use <code>&lt;=</code> like the other cases.</em></p>\n\n<pre><code># List of pairs (higher-limit, name) sorted\nCATEGORIES = [\n (15, 'very severely underweight'),\n (16, 'severely underweight'),\n (18.5, 'underweight'),\n (25, 'Normal(healthy weight)'),\n (30, 'overweight'),\n (35, 'moderately obese'),\n (40, 'severely obese'),\n]\n\ndef get_category(body_mass_index):\n for limit, name in CATEGORIES:\n if body_mass_index &lt;= limit:\n return name\n return 'very severely obese'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:09:54.580", "Id": "407102", "Score": "1", "body": "I haven't written python for a few years, but couldn't you only use if and return with a response function as soon as a condition is met?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T15:13:27.487", "Id": "407103", "Score": "0", "body": "@Džuris I am not quite sure what you mean. Could you write somewhere ( https://pastebin.com/ ?) what you have in mind ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T17:43:29.163", "Id": "407116", "Score": "0", "body": "sorry, I somehow misread a sample and was suggesting an idea similar to what's already there. Now that I read it properly on a computer, my question boils down to: Why do you need `elif` (instead of `if`) and `else` in the second sample? Isn't it that a later condition is only reached if none of the previous are met and just `if` (or nothing for the last case) would be enough?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:00:55.240", "Id": "407117", "Score": "0", "body": "@Džuris Indeed, it would be the same. I kept the original `elif` because it didn't bother me. Then it is just a matter of personal preference. I have no strong opinion on this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T03:26:42.177", "Id": "407164", "Score": "1", "body": "It's generally a good idea to have a `main()` function and have the last two (non-blank) lines be `if __name__ == '__main__': main()`. This allows the interactivity to be triggered as needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T10:32:27.560", "Id": "407185", "Score": "0", "body": "@SolomonUcko That's a good point. I've integrated your comment in the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T21:26:01.540", "Id": "407250", "Score": "0", "body": "Thanks Josay, some of the suggestions are a bit overwhelming, but i really appreciate it; It's been very helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T02:38:22.643", "Id": "407267", "Score": "0", "body": "Shouldn't `INCH_IN_M` be named `METERS_PER_INCH`? `INCH_PER_FOOT` should also be named `INCHES_PER_FOOT`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T11:33:18.867", "Id": "407288", "Score": "0", "body": "@Solomon Ucko I'm not a native English speaker so your solution may be more idiomatic indeed. At first I didn't realize that \"inch in meter\" was ambiguous: converting an \"inch in meter\" gives 0.025 but the number of \"inches in a meter\" is 39.3." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T10:01:09.487", "Id": "210596", "ParentId": "210592", "Score": "41" } }, { "body": "<p>One big refactoring that you could do is to remove all the if/else causes.</p>\n\n<p>For example:</p>\n\n<pre><code>def compute_bmi(weight_in_kilo, height_in_feet):\n STUPID_CONVERSION_CONSTANT = 12 * 0.025\n return weight_in_kilo / ((height_in_feet * STUPID_CONVERSION_CONSTANT) ** 2)\n\ndef find_key_from_bmi(bmi):\n keys = list(bmi_info.keys())\n mins = [k if k &lt;= bmi else 0 for k in keys]\n return keys[mins.index(min(mins))]\n\ndef print_message(bmi):\n print(f\"Your BMI is {bmi} which means you are {bmi_info[find_key_from_bmi(bmi)]}.\")\n\nbmi_info = {\n 15: 'very severely underweight',\n 16: 'severely underweight',\n 18.5: 'underweight',\n 25: 'normal (healthy weight)',\n 30: 'overweight',\n 35: 'moderately obese',\n 40: 'severely obese',\n\n}\n\nprint_message(compute_bmi(float(input(\"Enter you weight in kilo:\")), float(input(\"Enter your height in feet:\"))))\n</code></pre>\n\n<p>This scales to an arbitrary large number of categories (possibly automatically generated) without the need to write extra code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T02:33:02.790", "Id": "407266", "Score": "0", "body": "Why do you `import numpy`? Also, it's probably best to define the constant outside the loop and with a descriptive name such as `METERS_PER_FOOT`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T11:33:33.033", "Id": "407289", "Score": "0", "body": "Numpy was a leftover for no valid reason." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T20:28:41.820", "Id": "210611", "ParentId": "210592", "Score": "3" } } ]
{ "AcceptedAnswerId": "210596", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T08:01:03.303", "Id": "210592", "Score": "14", "Tags": [ "python", "calculator" ], "Title": "BMI calculator in python using if statements" }
210592
<p>I do work for a project currently, where the data is send to the server as application/x-www-form-urlencoded (which is bad, and it should be JSON, but unfortunately I am not able to change this one).</p> <p>The following code snipped will transfer the given parameters (in a loop) to a Map, which can then be transformed to json (eg. by using jackson).</p> <p>I would like to make this even better, so please post your comments and suggestions.</p> <p>Parameter-List:</p> <pre><code>_id=[5bfad95450642c333010daca], _rev=[1-9ce33949c3acd85cea6c58467e6a8144], type=[Group], user=[aUSer], default=[aDetail], store[aDetail][prop]=[5], store[aDetail][lprop1][0][time]=[00:00], store[aDetail][lprop1][0][value]=[14], store[aDetail][lprop1][0][timeAsSeconds]=[0], store[aDetail][lprop1][1][time]=[07:00], store[aDetail][lprop1][1][value]=[8], store[aDetail][lprop1][1][timeAsSeconds]=[25200], store[aDetail][anprop]=[25], store[aDetail][lprop2][0][time]=[00:00], store[aDetail][lprop2][0][value]=[61], store[aDetail][lprop2][0][timeAsSeconds]=[0], store[bDetail][prop]=[6], store[bDetail][lprop1][0][time]=[00:10], store[bDetail][lprop1][0][value]=[12], store[bDetail][lprop1][0][timeAsSeconds]=[0], store[bDetail][lprop1][1][time]=[07:10], store[bDetail][lprop1][1][value]=[9], store[bDetail][lprop1][1][timeAsSeconds]=[25200], store[bDetail][anprop]=[25], store[bDetail][lprop2][0][time]=[00:00], store[bDetail][lprop2][0][value]=[61], store[bDetail][lprop2][0][timeAsSeconds]=[0], created_at=[2018-01-11T20:48:22.574+0100], ... </code></pre> <p>Code-Snippet:</p> <pre><code>fun parseToMap(map: MutableMap&lt;String, Any&gt;, key: String, value: Any): MutableMap&lt;String, Any&gt; { val cleanedV = if (value is String) URLDecoder.decode(value, "UTF-8") else value if (!key.contains("[")) { map.putIfAbsent(key, cleanedV) } else { // mapKey is the key going to get stored in the map val mapKey = key.substring(0, key.indexOf("[")) // nextKey is the next key pushed to the next call of parseToMap var nextKey = key.removePrefix(mapKey) nextKey = nextKey.replaceFirst("[", "").replaceFirst("]", "") var isArray = false var index = -1 if (nextKey.contains("[") &amp;&amp; nextKey.substring(0, nextKey.indexOf("[")).matches(Regex("[0-9]+"))) { index = nextKey.substring(0, nextKey.indexOf("[")).toInt() isArray = true } // mapkey used for object in list val newMapKey = if (isArray) nextKey.substring(nextKey.indexOf("[") + 1, nextKey.indexOf("]")) else "" val child: Any? var childMap: MutableMap&lt;String, Any&gt; = mutableMapOf() if (map.containsKey(mapKey)) { println("key $mapKey exists already") child = map[mapKey] when (child) { is MutableList&lt;*&gt; -&gt; { if (child == null || child.isEmpty()) { childMap = mutableMapOf() val tmpList = child as MutableList&lt;Any&gt; tmpList.add(childMap) map.put(newMapKey, tmpList) } else { if (child.size &gt; index) { childMap = child.get(index) as MutableMap&lt;String, Any&gt; childMap = parseToMap(childMap, newMapKey, value) } else { childMap = parseToMap(childMap, newMapKey, value) val tmpList = child as MutableList&lt;Any&gt; tmpList.add(childMap) } } } is MutableMap&lt;*, *&gt; -&gt; childMap = map.get(mapKey) as MutableMap&lt;String, Any&gt; } } else { if (isArray) { child = mutableListOf&lt;Any&gt;() childMap = parseToMap(childMap, newMapKey, value) child.add(childMap) map.put(mapKey, child) } else { childMap = mutableMapOf&lt;String, Any&gt;() } } if (!isArray) parseToMap(childMap, nextKey, value) map.putIfAbsent(mapKey, childMap) } return map } </code></pre> <p>Calling this method:</p> <pre><code> decodedParameters.forEach { k, v -&gt; run { val cleanedV = v.toString().replace("[", "").replace("]", "") jsonMap = parseToMap(jsonMap, k, cleanedV) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T14:12:50.713", "Id": "210599", "Score": "2", "Tags": [ "parsing", "http", "hash-map", "kotlin" ], "Title": "Convert flat object hierarchy to json" }
210599
<p>So, I made a tiny (~2 KB, &lt;100 lines) library for simple flat-file data storage.</p> <p>How it works is, you define a file to be used, and then you can add/read/modify/delete objects as "keys" to/from the file.</p> <p>All the code is on <a href="https://github.com/rahuldottech/varDx" rel="nofollow noreferrer">github</a>, but I'll put it here too:</p> <p><strong><code>varDx.php</code>:</strong></p> <pre><code>&lt;?php namespace varDX; class cDX { private $dataFile; public function def($filename){ $this-&gt;dataFile = $filename; } public function write($varName, $varVal){ if(file_exists($this-&gt;dataFile)){ $foundLine = $this-&gt;check($varName); } else { $foundLine = false; } if(!$foundLine){ $writeData = $varName.'__=__'.urlencode(serialize($varVal)).PHP_EOL; file_put_contents($this-&gt;dataFile, $writeData, FILE_APPEND); } else { return "ERR_DX_KEY_ALREADY_EXISTS"; } } public function read($varName){ if(file_exists($this-&gt;dataFile)){ foreach(file($this-&gt;dataFile) as $line) { if(strpos($line, $varName) !== false) { list(, $new_str) = explode("__=__", $line); $foundLine = true; } } if($foundLine){ $val = rtrim($new_str); return unserialize(urldecode($val)); } else { return "ERR_DX_KEY_NOT_FOUND"; } } else { return "ERR_DX_FILE_DOES_NOT_EXIST"; } } public function del($varName){ if(file_exists($this-&gt;dataFile)){ $f = $this-&gt;dataFile; $term = $varName.'__=__'; $arr = file($f); foreach ($arr as $key=&gt; $line) { if(stristr($line,$term)!== false){unset($arr[$key]);break;} } //reindexing array $arr = array_values($arr); //writing to file file_put_contents($f, implode($arr)); } else { return "ERR_DX_FILE_DOES_NOT_EXIST"; } } public function modify($varName, $varVal){ if(file_exists($this-&gt;dataFile)){ if($this-&gt;check($varName)){ $this-&gt;del($varName); } } $writeData = $varName.'__=__'.urlencode(serialize($varVal)).PHP_EOL; file_put_contents($this-&gt;dataFile, $writeData, FILE_APPEND); } public function check($varName){ if(file_exists($this-&gt;dataFile)){ foreach(file($this-&gt;dataFile) as $line) { if(stripos($line, $varName.'__=__') === 0){ return true; } } return false; } else { return "ERR_DX_FILE_DOES_NOT_EXIST"; } } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>&lt;?php require 'varDx.php'; $dx = new \varDx\cDX; //create object $dx-&gt;def('file1.txt'); //define data file $a = "this is a string"; $dx-&gt;write('val1', $a); //write key to file $dx-&gt;modify('val1', "this is another string"); //modify value of key echo $dx-&gt;read('val1'); //read value of key if($dx-&gt;check('val1')){ //check if key exists del('val1'); //delete key } </code></pre> <p><strong>File storage:</strong></p> <p>All keys are stored in this format:</p> <pre><code>keyname__=__urlencode(serialize(value_of_key)) </code></pre> <p>There's more info on the functions in the README on the github page. I'm wondering if I can make this more efficient when dealing with files, and if there's anything else that I'm doing wrong?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:34:02.990", "Id": "407128", "Score": "3", "body": "Can you please explain the purpose of this storage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T18:58:04.257", "Id": "407133", "Score": "0", "body": "Your library does not adhere to PSR; it can not be installed by composer." } ]
[ { "body": "<p>Assuming this code is solely for learning purpose, there are several main issues</p>\n\n<ul>\n<li>to be honest, a function that returns ERR_DX_FILE_DOES_NOT_EXIST when I request an object looks a bit weird. I don't even know how to use it. Should I wrap every call to a function in a condition that checks the returned value? Or what else I am supposed to do with this string? Consider using errors/exceptions in case of error.</li>\n<li>a race condition issue. you can have this file malformed if two parallel processes would try to write at the same time. Consider use file locks</li>\n<li>an obvious memory issue - the bigger the file is, the more RAM does it take to process. PHP can let you to read a file line by line without memory overhead</li>\n<li>such a clumsy format as <code>keyname__=__urlencode(serialize(value_of_key))</code> doesn't seem to be very reliable. For such a toy storage I would rather use json format, to ease the search/key access.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T06:56:43.897", "Id": "407173", "Score": "0", "body": "The reason I used that weird long return value is because I can't return something like `false` or `0` because those could totally be valid values for the keys being accessed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T07:11:44.430", "Id": "407176", "Score": "0", "body": "I understand that. it desn't make sense to use such weird return value either. there are errors/exceptions to handle this situation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T07:22:03.503", "Id": "407180", "Score": "0", "body": "Cheers! Still new to this stuff, I'll figure something out." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T19:04:37.610", "Id": "210606", "ParentId": "210602", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T16:32:46.863", "Id": "210602", "Score": "1", "Tags": [ "php", "database", "library" ], "Title": "PHP flatfile storage" }
210602
<p>The Wikipedia article about the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="nofollow noreferrer">Collatz Conjecture</a> has these quotes:</p> <blockquote> <p>If the conjecture is false, it can only be because there is some starting number which gives rise to a sequence that does not contain 1. Such a sequence might enter a repeating cycle that excludes 1, or increase without bound. No such sequence has been found.</p> <p>... sometimes a conjecture's only counterexamples are found when using very large numbers.</p> </blockquote> <p>The bit about using very large numbers motivated me to write the following Collatz calculator that uses <a href="https://en.wikipedia.org/wiki/Googol" rel="nofollow noreferrer">Googol</a>-sized numbers.<br /> The program is very extensible. Just change the equates on top.</p> <p>The faster the calculation, the more numbers can be verified for compliance, silently hoping for non-compliance of course...<br /> I'm most interested in speeding up the <em>CollatzEngine</em>.<br /> I wrote this code on an Intel® Pentium® dual-core processor T2080 and that's Core™ microarchitecture. The instruction set goes up to SSE3 (not including SSSE3). Ideally improvement suggestions don't exceed these specs.</p> <p>I display a running counter on screen just to prove that the program is still alive.</p> <pre class="lang-none prettyprint-override"><code>; Never ending program to verify successive numbers ; whether they comply or not with the Collatz conjecture. ; The starting number is 10 ^ PowerOfTen. PowerOfTen = 100 ;1 Googol == 10^100 MaxDWords = 12 ;1 Googol occupies 11 dwords MaxSteps = 100000 Width = (1+MaxDWords)*4 STD_OUTPUT_HANDLE = 0FFFFFFF5h format PE console Start: mov esi, Title call PrintString mov eax, PowerOfTen call PrintNumber mov esi, Title_ call PrintString mov ebx, Slots ;Pointing at SlotA call BuildGoogol ; -&gt; (EAX ECX..EBP) Next: mov esi, [Screen] ;Update the counter on screen call PrintString call CollatzEngine ; -&gt; ECX (EAX EDX..EDI) call GoToNextNumber ; -&gt; (EAX ESI) jmp Next ; -------------------------------------- Fatal3: call Fatal ;From inside CollatzEngine db &quot;needs too many steps - Possible repetition!&quot;, 0 Fatal2: call Fatal ;From inside CollatzEngine db &quot;grows too big - Possible divergence!&quot;, 0 Fatal1: call Fatal ;From outside CollatzEngine db &quot;needs more space.&quot;, 0 Fatal: mov esi, Error call PrintString pop esi call PrintString mov al, 0 jmp TerminateProgram ; -------------------------------------- ; IN (ebx) OUT () MOD (eax,ecx..ebp) BuildGoogol: mov ecx, 1 mov [ebx], ecx ;SignificantDWords = 1 mov [ebx+4], ecx ;SlotA = 1 mov ebp, PowerOfTen jmp .c .a: lea edi, [ebx+4] ;Current value * 10 xor esi, esi mov ecx, [ebx] ;SignificantDWords .b: mov eax, 10 mul dword [edi] add eax, esi adc edx, 0 stosd mov esi, edx dec ecx jnz .b test esi, esi jz .c cmp dword [ebx], MaxDWords ;Upscale jnb Fatal1 ;&quot;needs more space&quot; mov [edi], esi inc dword [ebx] .c: dec ebp jns .a ret ;SlotA = 10 ^ #PowerOfTen ; -------------------------------------- ; IN (ebx) OUT (ecx) MOD (eax,edx..edi) CollatzEngine: mov ecx, [ebx] ;SignificantDWords [1,MaxDWords] inc ecx mov esi, ebx add ebx, Width ;(*) Within Collatz EBX points at SlotB mov edi, ebx rep movs dword [edi], [esi] ;Copy SlotA into SlotB ;;xor ecx, ecx ;StepCount mov esi, [ebx] ;Cache SignificantDWords [1,MaxDWords] jmp .Start .Cont: mov eax, [ebx+4] ;Lowest dword of current number bt eax, 0 adc ecx, 1 ;StepCount + [1,2] cmp ecx, MaxSteps ja Fatal3 ;&quot;needs too many steps&quot; bt eax, 0 jnc @f call .Odd ; -&gt; ESI CF=0 (EAX EDX EDI) @@: call .Even ; -&gt; ESI (EAX EDX EDI) .Start: cmp esi, 1 jne .Cont cmp [ebx+4], esi jne .Cont .Done: mov [ebx], esi ;Un-cache SignificantDWords sub ebx, Width ;(*) Restore EBX to point at SlotA ret ;ECX is steps taken to reach 1 ; - - - - - - - - - - - - - - - - - - - ; IN (ebx,esi,CF=1) OUT (esi,CF=0) MOD (eax,edx,edi) .Odd: lea edi, [ebx+Width+4] ;CF=1 This produces the +1 mov edx, esi @@: mov eax, [edi-Width] ;n --&gt; 2n+1 rcl eax, 1 stosd ;DST is intermediate storage (SlotC) dec edx jnz @b jnc @f cmp esi, MaxDWords ;Upscale jnb Fatal2 ;&quot;grows too big&quot; mov [edi-Width], edx ;EDX=0 inc edx ; 0 -&gt; 1 mov [edi], edx add esi, edx ; -&gt; CF=0 @@: lea edi, [ebx+4] ;CF=0 mov edx, esi @@: mov eax, [edi] ;2n+1 --&gt; 3n+1 adc eax, [edi+Width] stosd ;DST is intermediate storage (SlotB) dec edx jnz @b jnc @f cmp esi, MaxDWords ;Upscale jnb Fatal2 ;&quot;grows too big&quot; inc edx ; 0 -&gt; 1 mov [edi], edx add esi, edx ; -&gt; CF=0 @@: ret ; - - - - - - - - - - - - - - - - - - - ; IN (ebx,esi,CF=0) OUT (esi) MOD (eax,edx,edi) .Even: lea edi, [ebx+esi*4] ;CF=0 mov edx, esi std @@: mov eax, [edi] ;n --&gt; n/2 rcr eax, 1 stosd ;DST is intermediate storage (SlotB) dec edx jnz @b cld cmp [ebx+esi*4], edx ;EDX=0 sete dl ; -&gt; EDX=[0,1] sub esi, edx ;This is Downscale if EDX=1 ret ; -------------------------------------- ; IN (ebx) OUT () MOD (eax,esi) GoToNextNumber: mov esi, ebx ;Increment number in SlotA mov eax, [esi] ;SignificantDWords .a: add esi, 4 add dword [esi], 1 jnc .b dec eax jnz .a cmp dword [ebx], MaxDWords ;Upscale jnb Fatal1 ;&quot;needs more space&quot; inc eax ; 0 -&gt; 1 add [ebx], eax mov [esi+4], eax .b: lea esi, [Mirror+38] ;Increment counter in mirror jmp .d .c: sub al, 10 mov [esi], al dec esi cmp esi, [Screen] jnb .d mov [Screen], esi .d: mov al, [esi] add al, 1 cmp al, &quot;9&quot; ja .c mov [esi], al ret ; -------------------------------------- ; IN (al) TerminateProgram: movzx eax, al push eax call [ExitProcess] ; IN (esi) PrintString: push ebx push esi ;(1) push STD_OUTPUT_HANDLE call [GetStdHandle] mov ebx, eax pop esi ;(1) mov edi, esi or ecx, -1 xor al, al repne scasb neg ecx sub ecx, 2 push 0 push Bytes push ecx push esi push ebx call [WriteFile] pop ebx ret ; IN (dl) PrintCharacter: mov [OneChar], dl push STD_OUTPUT_HANDLE call [GetStdHandle] push 0 push Bytes push 1 push OneChar push eax call [WriteFile] ret ; IN (eax) PrintNumber: push ebx mov ebx, 10 ;CONST 10 push ebx ;Sentinel .a: xor edx,edx div ebx push edx test eax, eax jnz .a pop edx .b: add dl, &quot;0&quot; call PrintCharacter pop edx cmp edx, 10 jb .b pop ebx ret ; --------------------------------------------------------------------------- Title db 'Collatz Conjecture Disprover Unit - Googol Edition', 13, 10 db 10, 'Now verifying the number: 10 ^ ', 0 Title_ db ' + ...', 13, 10, 0 Error db 10, 10, 'Error: This number ', 0 Mirror db 39 dup '0', 13, 0 OneChar db 0 ALIGN 4 Screen dd Mirror+38 Bytes rd 1 Slots rd 3*(1+MaxDWords) ; ----------------------------------------------------------------------------- stack 4096 ; --------------------------------------------------------------------------- section '.idata' import data readable writeable dd 0, 0, 0, rva kernel_name, rva kernel_table dd 0, 0, 0, 0, 0 kernel_table: ExitProcess dd rva _ExitProcess WriteFile dd rva _WriteFile GetStdHandle dd rva _GetStdHandle dd 0 kernel_name db 'KERNEL32.DLL', 0 _ExitProcess dw 0 db 'ExitProcess', 0 _WriteFile dw 0 db 'WriteFile', 0 _GetStdHandle dw 0 db 'GetStdHandle', 0 ; --------------------------------------------------------------------------- section '.reloc' fixups data readable discardable </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:05:27.357", "Id": "407141", "Score": "1", "body": "0th suggestion: add a head comment what the code is about and where \"the Collatz branch and steps\" are coded. (Yes, for me, who can spot them as well as for yourself who *knows* what is what. In 2018…) `most interested in speeding up [a piece of machine code]` Specify a micro-architecture/implementation to target. Invest months of time in manufacturers instrumentation toolset." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:50:55.683", "Id": "407144", "Score": "0", "body": "(Eye-balling [this table](http://sweet.ua.pt/tos/3x+1/i0.gif) in [Computational verification of the 3x+1 conjecture](http://sweet.ua.pt/tos/3x+1.html), you'd need more than twice the length of the starting value to hold the \"maximum excursion\".)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T22:02:24.153", "Id": "407147", "Score": "3", "body": "(See also: [C++ code for testing the Collatz conjecture faster than hand-written assembly](https://stackoverflow.com/q/40354978).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:01:40.667", "Id": "407151", "Score": "1", "body": "Regarding your license comment, note that [all user contributions on this site are licensed under the cc by-sa 3.0](https://codereview.stackexchange.com/help/licensing)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T07:23:55.020", "Id": "413111", "Score": "1", "body": "@Graham That does not invalidate that Sep Roland holds the copyright on the material. He still does; CC by-SA just means that others are allowed to use and remix it, as long as they give him proper attribution. No one else can claim it as their own. The real reason you don't need to include a copyright header is that it is always implied. At least in all countries that are parties to the [Berne Convention](https://en.wikipedia.org/wiki/Berne_Convention). An explicit copyright notice like this is only useful to prevent people from claiming ignorance in court, which is never a good defense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:53:45.427", "Id": "413586", "Score": "0", "body": "@CodyGray That comment was targeted towards the \"All rights reserved\" line in the [original version](https://codereview.stackexchange.com/revisions/210608/1), which (as I understand) is explicitly not true under the CC by-SA. I was not intending to dispute the poster's copyright generally. However, the general exploration of copyright notices in your comment may be more useful to future visitors, and clarifies the situation more than my brief note." } ]
[ { "body": "<p>I don't speak x86 good :). That means, no style tips. I couldn't figure out how you're terminating in the known cycle at all...</p>\n<p>But, I know some things about how to improve your algorithm. If you write this in C, I'd be happy to give better feedback.</p>\n<p>A couple speed hints:</p>\n<ul>\n<li>You're only working with Googol sized words? That fits in 6 64-bit registers. Forget memory until you prove you need it!</li>\n<li>You can detect cycles using only two numbers worth of storage (look up cycle-finding algorithms). This is probably something you would want to run only AFTER you suspect a cycle. Then again, you may not ever hit this case, but just so you know.</li>\n<li>You can do more than one step at a time. Definitely do this for evens at least--get rid of all the zeros on the right, not just one. To do this for odds is fairly complicated, but would make it faster.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T05:09:54.057", "Id": "251584", "ParentId": "210608", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T19:29:06.520", "Id": "210608", "Score": "5", "Tags": [ "performance", "algorithm", "assembly", "collatz-sequence", "x86" ], "Title": "Collatz Conjecture Disprover Unit - Googol Edition" }
210608
<p>This is my attempt at making a class for dynamic PDO queries in PHP.</p> <p>The code works, but I would like the hear what I can improve to make it more secure and readable.</p> <pre><code>class DB { private static $connection; public static function setConnection ($connection) { static::$connection = $connection; } public static function insert($table, $data = []) { try { $columnsArray = array_keys($data); $columnsString = implode(',', $columnsArray); $valuesArray = array_values($data); $valuesCount = count($valuesArray); $valuesPlaceholder = ''; for ($i=0; $i &lt; $valuesCount; $i++) { $valuesPlaceholder .= '?,'; } $valuesPlaceholder = rtrim($valuesPlaceholder, ','); $query = "INSERT INTO $table ($columnsString) VALUES ($valuesPlaceholder)"; $statement = static::$connection-&gt;prepare($query); $statement-&gt;execute($valuesArray); } catch (\PDOException $e) { die("Insert failed: " . $e-&gt;getMessage()); } } } </code></pre> <p>Usage example</p> <pre><code>//setting the connection in app entry point $config = require_once "config.php"; $dbConnection = Connection::make($config['database']); DB::setConnection($dbConnection); //using DB class in a controller class PostController { //inserting a post to posts table with name and content columns public function create() { $name = $_POST['postName']; $content = $_POST['postContent']; DB::insert('posts', [ 'name' =&gt; $name, 'content' =&gt; $content ]); return redirect('somewhere'); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T09:29:47.613", "Id": "407184", "Score": "0", "body": "Can you please provide a use case for this function, a usage example? Kindly add it to the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T10:37:40.287", "Id": "407186", "Score": "0", "body": "Thanks for the suggestion, I've added simple usage example to the question." } ]
[ { "body": "<p>You are using the prepared statement with placeholders properly, so regarding security, I would only advise you to not display the actual error details to the end user -- you don't want naughty people getting any funny ideas.</p>\n\n<p>As for readability, I try not to declare single-use variables, though it can be good to declare a single-use variable to clarify the data being processed.</p>\n\n<p>I don't prefer the over-delimit, then <code>rtrim()</code> technique. Building a temporary array of <code>?</code> then imploding it with commas seems cleaner to me.</p>\n\n<pre><code>$columns = implode(',', array_keys($data));\n\n$placeholders = implode(',', array_fill(0, count($data), '?'));\n\n$values = array_values($data);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:47:21.440", "Id": "210822", "ParentId": "210610", "Score": "3" } }, { "body": "<p>There are several areas for improvement.</p>\n<h3>SQL injection.</h3>\n<p>There is a fair possibility for the SQL injection. You are adding variables (namely array keys) into SQL query <em>absolutely untreated</em>, which is a big red flag.</p>\n<p>Although your intended usage scenario is safe, but you cannot foresee any possible use case. There was an <a href=\"https://blog.ircmaxell.com/2014/10/a-lesson-in-security.html\" rel=\"nofollow noreferrer\">infamous SQL injection in Drupal 7</a> that used a code almost identical to yours - an array key is put into the query untreated. As you can see, it led to a severe vulnerability. Therefore, your function ought to offer a 100% safe query execution, no matter how it's called.</p>\n<p>However, the best solution you can get will question the function's existence itself. Because the best way to protect the field names is to whitelist them, but the best way to whitelist table fields is... to list them explicitly in the query. And if you list them in the query, there will be no need for such a function at all. It shouldn't be a problem, however, as you are going to list your field names right in the code this way or another. Given you can use positional placeholders, the code could be reasonably small:</p>\n<pre><code> DB::query('INSERT INTO posts (name, content) VALUES (?,?)', [\n $_POST['postName'], $_POST['postContent']\n ]);\n</code></pre>\n<p>Whereas a function like <code>DB::insert()</code> could be justified not as a free-to-use function, but as method belongs to an ORM, that operates a predefined set of object's properties only. In this case, when it's guaranteed that only predefined field names are allowed to the query, such a function could be used safely.</p>\n<p>If you are 100% determined to use this function as is, at least <strong>make sure you are <a href=\"https://phpdelusions.net/pdo#identifiers\" rel=\"nofollow noreferrer\">quoting and escaping field and table names properly</a></strong>.</p>\n<h3>Error reporting</h3>\n<p>The error reporting is completely flawed in this function. It tells everyone that you don't even consider your site to go live. Because present error reporting is only useful for the single-user dev mode, while it would be completely useless (and even harmful) on a live site. I've got a <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">comprehensive guide on PHP error reporting</a>, but in short, you must leave an error/exception alone and let it to bubble up to the site-wide handler, instead of catching it on the spot.</p>\n<h3>A generic query function.</h3>\n<p>From the code of your function it is evident that you don't have a generic query function (or you don't reuse its code which is equally bad). There should be a function that accepts a query and an array with parameters, and returns a statement:</p>\n<pre><code>public static function query($query, $data = [])\n{\n $statement = static::$connection-&gt;prepare($query);\n $statement-&gt;execute($data);\n return $statement;\n}\n</code></pre>\n<p>and then it could be used in your insert() method (as well as in many other methods):</p>\n<pre><code>$query = &quot;INSERT INTO $table ($columnsString) VALUES ($valuesPlaceholder)&quot;;\nstatic::query($query, $valuesArray);\n</code></pre>\n<p>(but again - remember that $table and values in $columnsString must be either quoted/escaped or - preferably - hardcoded in the class definition).</p>\n<h3>A proper Model</h3>\n<p>Your code hints that you are intending to follow the MVC pattern. However, the code in your controller is not reusable, it means that the pattern is broken. Imagine you are going to create a command-line utility to create posts. Or any other method like creating a post through e-mail. You will inevitably duplicate this insert call, which is against the very purpose of the MVC pattern.</p>\n<p>So, to make it proper, you must create a Post Service with a create() method in it, whic would be called in your Controller. It will make your Controller thin, and the insert code reusable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T12:21:59.877", "Id": "210933", "ParentId": "210610", "Score": "1" } }, { "body": "<blockquote>\n<pre><code> try {\n\n $columnsArray = array_keys($data);\n $columnsString = implode(',', $columnsArray);\n\n $valuesArray = array_values($data);\n $valuesCount = count($valuesArray);\n\n $valuesPlaceholder = '';\n for ($i=0; $i &lt; $valuesCount; $i++) { \n $valuesPlaceholder .= '?,';\n }\n $valuesPlaceholder = rtrim($valuesPlaceholder, ',');\n</code></pre>\n</blockquote>\n\n<p>None of this code can throw a <code>PDOException</code>. So there's no point in having it in the <code>try</code> block. It's not like it was in a separate function that included all of this function. The scope of the block is fully under your control here. </p>\n\n<pre><code> $valuesCount = count($data);\n if ($valuesCount &lt; 1) {\n return;\n }\n\n $columnsArray = array_keys($data);\n $columnsString = implode(',', $columnsArray);\n\n $valuesPlaceholder = '?';\n for ($i = 1; $i &lt; $valuesCount; $i++) { \n $valuesPlaceholder .= ',?';\n }\n\n $valuesArray = array_values($data);\n\n try {\n</code></pre>\n\n<p>Now we don't even waste time processing if there is no data. You can change the <code>return</code> to a <code>die</code> if you prefer that behavior (with no data, the SQL would have been malformed and triggered the exception). </p>\n\n<p>Having it count <code>$data</code> rather than the values is just so that we don't have to call <code>array_values</code> if it's not needed. Counting any of <code>$data</code>, the values, or the keys should return the same result. In fact, if one were different, it would break the function's behavior. </p>\n\n<p>I changed the placeholder handling to avoid the <code>rtrim</code>. With the early return, it is no longer necessary. This variant will handle any positive integer properly. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T06:01:23.543", "Id": "407813", "Score": "0", "body": "neither return or die are proper ways to handle the invalid argument error. both are rather horrible. neither pretending everything is okay (as with return) nor irrecoverably killing the script are acceptable methods to handle an error. a triggered exception is *the* only proper way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T21:20:19.770", "Id": "210948", "ParentId": "210610", "Score": "0" } } ]
{ "AcceptedAnswerId": "210933", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T20:26:34.517", "Id": "210610", "Score": "3", "Tags": [ "php", "object-oriented", "database", "pdo" ], "Title": "Dynamic PHP PDO insert method" }
210610
<p>This scrapes the titles and descriptions of trending YouTube videos and writes them to a CSV file. What improvements can I make?</p> <pre><code>from bs4 import BeautifulSoup import requests import csv source = requests.get("https://www.youtube.com/feed/trending").text soup = BeautifulSoup(source, 'lxml') csv_file = open('YouTube Trending Titles on 12-30-18.csv','w') csv_writer = csv.writer(csv_file) csv_writer.writerow(['Title', 'Description']) for content in soup.find_all('div', class_= "yt-lockup-content"): try: title = content.h3.a.text print(title) description = content.find('div', class_="yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2").text print(description) except Exception as e: description = None print('\n') csv_writer.writerow([title, description]) csv_file.close() </code></pre>
[]
[ { "body": "<p>Why web-scrape, when you can get the data properly through the YouTube Data API, <a href=\"https://developers.google.com/youtube/v3/docs/videos/list\" rel=\"noreferrer\">requesting the <code>mostpopular</code> list of videos</a>? If you make a <code>GET</code> request to <code>https://www.googleapis.com/youtube/v3/videos?key=…&amp;part=snippet&amp;chart=mostpopular</code>, you will get the same information in a documented JSON format.</p>\n\n<p>Using the <a href=\"https://developers.google.com/api-client-library/python/apis/youtube/v3\" rel=\"noreferrer\">Python client</a>, the code looks like:</p>\n\n<pre><code>import csv\nimport googleapiclient.discovery\n\ndef most_popular(yt, **kwargs):\n popular = yt.videos().list(chart='mostPopular', part='snippet', **kwargs).execute()\n for video in popular['items']:\n yield video['snippet']\n\nyt = googleapiclient.discovery.build('youtube', 'v3', developerKey=…)\nwith open('YouTube Trending Titles on 12-30-18.csv', 'w') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(['Title', 'Description'])\n csv_writer.writerows(\n [snip['title'], snip['description']]\n for snip in most_popular(yt, maxResults=20, regionCode=…)\n )\n</code></pre>\n\n<p>I've also restructured the code so that all of the CSV-writing code appears together, an inside a <code>with open(…) as f: …</code> block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:56:47.607", "Id": "407145", "Score": "0", "body": "Great suggestion! I searched but didn't find that API. Are mostpopular and trending synonyms ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T22:06:06.550", "Id": "407149", "Score": "5", "body": "@Josay When I include the `regionCode` in the API call (`'CA'` for me), then the first 20 results are identical to the list on the \"Trending\" page, which indicates that they are indeed different names for the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:55:14.007", "Id": "407154", "Score": "0", "body": "Oh, I see; I didn't know the purpose of API, but I will look more into it. Thanks for the info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T15:32:31.470", "Id": "407208", "Score": "3", "body": "Is the developerkey a thing required to be taken from Google ? If yes, then the scraping doesn't require it and scraping may be better from that point of view. why sign up for something that you don't need to ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:09:11.793", "Id": "407215", "Score": "3", "body": "@WhirlMind Because the HTML structure of the Trending page could change at any time, and is essentially an undocumented API. The YouTube Data API is guaranteed to be stable, and any changes to it will be preceded by a suitable transition period. Obtaining a developer key is a trivial process, if you already have a Google account." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:18:13.807", "Id": "429920", "Score": "0", "body": "You web scrape because the google API provides you with a ridiculously small 10k quota units per day. Some requests may use hundreds or thousands of these units. Almost no requests use only 1 of these units. Thus, using the API gives you severe limitations, so you web scrape to avoid google's nonsense. I mean, is having to design a data-getting system around a quota really the \"proper\" way to acquire data? To me it seems like unnecessary complexity." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:51:57.553", "Id": "210615", "ParentId": "210613", "Score": "40" } }, { "body": "<p><strong>Context manager</strong></p>\n\n<p>You open a file at the beginning of the program and close it explicitly at the end.</p>\n\n<p>Python provides a nice way to allocate and release resources (such as files) easily: they are called Context managers. They give you the guarantee that the cleanup is performed at the end even in case of exception.</p>\n\n<p>In your case, you could write:</p>\n\n<pre><code>with open('YouTube Trending Titles on 12-30-18.csv','w') as file:\n ....\n</code></pre>\n\n<p><strong>Exception</strong></p>\n\n<p>All exceptions are caught by <code>except Exception as e</code>. It may look like a good idea at first but this can lead to various issues:</p>\n\n<ul>\n<li>it's hard to know what types of error are actually expected here</li>\n<li>most errors are better not caught (except for special situations). For instance, if you write a typo, you'll end up with an ignored <code>NameError</code> or <code>AttributeError</code> and debugging will be more painful than it should be.</li>\n</ul>\n\n<p>Also, from the content of the <code>except</code> block, it looks like you are only expecting the logic about <code>description</code> to fail. If so, it would be clearer to put in the <code>try (...) except</code> the smallest amount of code.</p>\n\n<p>For instance:</p>\n\n<pre><code>title = content.h3.a.text\ntry:\n description = content.find('div', class_=\"yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2\").text\nexcept Exception as e:\n description = None\nprint(title)\nprint(description)\nprint('\\n')\n</code></pre>\n\n<p><strong>Proper solution</strong></p>\n\n<p>Google usually offers API to retrieve things such like trending videos. I haven't found it but I'll let you try to find something that works properly. Google is your friend...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T21:55:08.443", "Id": "210616", "ParentId": "210613", "Score": "15" } }, { "body": "<p>I'd definitely look into using an API directly <a href=\"https://codereview.stackexchange.com/a/210615/24208\">as @200_success suggested</a> to avoid any web-scraping or HTML parsing, but here are some additional suggestions to improve your current code focused mostly around HTML parsing:</p>\n\n<ul>\n<li><p>you could get some speed and memory improvements if you would use a <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-only-part-of-a-document\" rel=\"noreferrer\"><code>SoupStrainer</code></a> to allow <code>BeautifulSoup</code> parse out only the desired elements from the HTML:</p>\n\n<blockquote>\n <p>The <code>SoupStrainer</code> class allows you to choose which parts of an incoming document are parsed. </p>\n</blockquote>\n\n<pre><code>from bs4 import BeautifulSoup, SoupStrainer\n\ntrending_containers = SoupStrainer(class_=\"yt-lockup-content\")\nsoup = BeautifulSoup(source, 'lxml', parse_only=trending_containers)\n</code></pre></li>\n<li><p>instead of <code>.find_all()</code> and <code>.find()</code> you could have used more concise <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors\" rel=\"noreferrer\">CSS selectors</a>. You would have:</p>\n\n<pre><code>soup.select('.yt-lockup-content')\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>soup.find_all('div', class_= \"yt-lockup-content\")\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>content.select_one('.yt-lockup-description.yt-ui-ellipsis.yt-ui-ellipsis-2')\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>content.find('div', class_=\"yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2\")\n</code></pre></li>\n<li><p>note how I've omitted <code>div</code> tag names above - I think they are irrelevant as the class values actually define the type of an element in this case</p></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"noreferrer\">organize imports as per PEP8</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T00:45:31.780", "Id": "210622", "ParentId": "210613", "Score": "10" } }, { "body": "<p>I would separate the \"input\" (finding titles and descriptions) from the output (writing to screen or file). One good way to do that is to use a generator:</p>\n\n<pre><code>from bs4 import BeautifulSoup\nimport requests\nimport csv\n\ndef soup():\n source = requests.get(\"https://www.youtube.com/feed/trending\").text\n soup = BeautifulSoup(source, 'lxml')\n\ndef find_videos(soup):\n for content in soup.find_all('div', class_= \"yt-lockup-content\"):\n try:\n title = content.h3.a.text\n description = content.find('div', class_=\"yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2\").text\n except Exception as e:\n description = None\n yield (title, description)\n\nwith open('YouTube Trending Titles on 12-30-18.csv', 'w') as csv_file:\n\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(['Title', 'Description'])\n\n for (title, description) in find_videos(soup()):\n csv_writer.writerow([title, description])\n</code></pre>\n\n<p>Disclaimar: I haven't tested this code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T04:49:58.600", "Id": "210675", "ParentId": "210613", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T20:57:04.307", "Id": "210613", "Score": "19", "Tags": [ "python", "csv", "web-scraping", "beautifulsoup", "youtube" ], "Title": "Web scraping the titles and descriptions of trending YouTube videos" }
210613
<p>I decided to give Go a try and implemented a Game of Life Kata exercise in GOLang. I have no prior experience in Go and the majority of my experience comes from Java, C#, and Python. My code appears to be working as intended but not sure if I've implemented it in the GO way, or idiomatic Go.</p> <p>I've seen a few Go examples online where the properties of the struct were always public, but that feels foreign coming from the object-orient world. The way I've implemented it the Board struct should never be able to get into an invalid state. I don't know if that is a mindset that is shared by the Go community.</p> <p>I have a colleague who is big into Go and favors immutability and no side effects. I can see how that would be ideal for concurrency, but does the general Go community prefer avoiding mutations? As an example I could have implemented my Evolve method to return a new Board struct rather than mutate its state property.</p> <p>Is there anything else that stands out as not being Go like?</p> <pre><code>package board import ( "errors" "math/rand" "strconv" "time" ) const CellDead = 0 const CellAlive = 1 type board struct { state [][]int rows int columns int } /* Creates a new Board with the given dimensions. The dimensions, rows and columns, must be positive integers greater than 0. Returns a board populated with a random state. */ func NewRandomBoard(rows, columns int) (board, error) { if rows &lt; 1 || columns &lt; 1 { return board{}, errors.New("rows and columns must be a positive integer greater than 0") } initState := make([][]int, rows) for i := range initState { initState[i] = make([]int, columns) } rand.Seed(time.Now().UnixNano()) // Populate random state for i := range initState { for j := range initState[i] { initState[i][j] = rand.Intn((1 -0 + 1) + 0) } } return board{state: initState, rows:rows, columns:columns}, nil } func NewBoard(initialState [][]int) (board, error) { if initialState == nil { return board{}, errors.New("initialState cannot be nil") } if len(initialState) &lt; 1 || len(initialState[0]) &lt; 1 { return board{}, errors.New("initialState must contain at least 1 row and 1 column") } colSize := len(initialState[0]) for i := 0; i &lt; len(initialState); i++ { if colSize != len(initialState[i]) { return board{}, errors.New("initialState is a jagged 2D array, initialState cannot be jagged") } for j := 0; j &lt; len(initialState[i]); j++ { cellValue := initialState[i][j] if cellValue &lt; 0 || cellValue &gt; 1 { return board{}, errors.New("initialState may only contain values 0 or 1") } } } return board{state:initialState, rows: len(initialState), columns: len(initialState[0])}, nil } func (b *board) Evolve() { newState := make([][]int, b.rows) for i := range newState { newState[i] = make([]int, b.columns) for j := range newState[i] { newState[i][j] = nextStateForCell(b,i,j) } } b.state = newState } func (b *board) State() [][]int { return b.state } func (b *board) Rows() int { return b.rows } func (b *board) Columns() int { return b.columns } func (b *board) PrettyPrint() { for i := range b.state { for j := range b.state[i] { print(" " + strconv.Itoa(b.state[i][j]) + "") } println() } } func nextStateForCell(b *board, i,j int) int { neighborsAlive := 0 cellValue := b.state[i][j] for x := -1; x &lt;= 1; x++ { for y := -1; y &lt;= 1; y++ { if i + x &lt; 0 || i + x &gt; (b.rows - 1) || y + j &lt; 0 || y + j &gt; (b.columns - 1) { continue } neighborsAlive += b.state[i + x][y + j] } } neighborsAlive -= cellValue if cellValue == CellDead &amp;&amp; neighborsAlive == 3 { return CellAlive } else if cellValue == CellAlive &amp;&amp; (neighborsAlive &lt; 2 || neighborsAlive &gt; 3) { return CellDead } else { return cellValue } } </code></pre> <p>The main file</p> <pre><code>package main import ( "io.jkratz/katas/life/board" ) func main() { myBoard, err := board.NewRandomBoard(10, 10) if err != nil { panic("Failed to instantiate board") } myBoard.PrettyPrint() println() myBoard.Evolve() myBoard.PrettyPrint() } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:00:34.847", "Id": "407402", "Score": "0", "body": "package is called `board`, and there's a function called `NewBoard`. The call stutters. Writing `board.New()` communicates the exact same thing as `board.NewBoard()` without the repetition. check [the golang code review](https://github.com/golang/go/wiki/CodeReviewComments) wiki for more conventions that are widely adopted." } ]
[ { "body": "<blockquote>\n <p>Is there anything else that stands out as not being Go like?</p>\n</blockquote>\n\n<p>While reading through your code, I only noticed a few things that weren't idiomatic Go, so congrats!</p>\n\n<h2>Avoid <code>print()</code> and <code>println()</code> in favor of <code>fmt</code></h2>\n\n<pre><code>for i := range b.state {\n for j := range b.state[i] {\n print(\" \" + strconv.Itoa(b.state[i][j]) + \"\")\n }\n println()\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>for i := range b.state {\n for j := range b.state[i] {\n fmt.Printf(\" %d \", b.state[i][j])\n }\n\n fmt.Println()\n}\n</code></pre>\n\n<p>Notice that you also avoid <code>strconv.Itoa()</code>.</p>\n\n<h2><code>rand.Intn((1 -0 + 1) + 0)</code></h2>\n\n<p>You mean <code>rand.Intn(2)</code>?</p>\n\n<h2><code>log.Fatal()</code> instead of <code>panic()</code></h2>\n\n<p>In your example usage, you use <code>panic()</code> to raise an error. Unless you plan to <code>recover()</code> from that, you can use <code>log.Fatal()</code> to write to standard error and exit the program.</p>\n\n<pre><code>panic(\"Failed to instantiate board\")\n</code></pre>\n\n<p>Would be more commonly done as:</p>\n\n<pre><code>log.Fatalf(\"Failed to instantiate board: %s\", err)\n</code></pre>\n\n<p>Or whatever error grammar you prefer. If you have an error value, you might as well use it to indicate the potential problem to the user.</p>\n\n<h2>Inconsistent formatting</h2>\n\n<p>For example:</p>\n\n<pre><code>func nextStateForCell(b *board, i,j int) int {\n</code></pre>\n\n<p>Would be consistently spaced as such:</p>\n\n<pre><code>func nextStateForCell(b *board, i, j int) int {\n</code></pre>\n\n<p>It's a nitpick. If you run <code>go fmt</code> on the source code, it should fix these kinds of things. If you use vim, there's also <a href=\"https://github.com/fatih/vim-go\" rel=\"nofollow noreferrer\">vim-go</a>, which I find very helpful.</p>\n\n<hr>\n\n<blockquote>\n <p>I have a colleague who is big into Go and favors immutability and no side effects. I can see how that would be ideal for concurrency, but does the general Go community prefer avoiding mutations?</p>\n</blockquote>\n\n<p>I'm not sure if there's a consensus. Normally the answer is: \"It depends.\" I think the way you've done it is fine. By mutating the state directly, you avoid potentially-costly memory allocations. So, for example, if you want to see the state after a trillion generations, it would likely be faster than if you constantly reassign based on return values.</p>\n\n<p>Since you're new to Go, I recommend experimenting with concurrency. Here, you can concurrently read and determine the next state of the board.</p>\n\n<hr>\n\n<p><a href=\"https://golang.org/doc/play/life.go\" rel=\"nofollow noreferrer\">Here</a> is another example of a Go implementation of Conway's Game of Life, straight from the Go website.</p>\n\n<p>Notice that they use a boolean field, rather than an integer one. This is more common (and performant), given that living is boolean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T15:20:51.540", "Id": "407207", "Score": "1", "body": "I wish I could upvote this multiple times, thanks for the thorough answer and explanation!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T04:23:09.173", "Id": "210626", "ParentId": "210620", "Score": "4" } } ]
{ "AcceptedAnswerId": "210626", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-30T23:34:36.843", "Id": "210620", "Score": "2", "Tags": [ "go", "game-of-life" ], "Title": "GOLang Game of Life Implementation" }
210620
<p>For python 3.6.5 using graphene-graphql and mysql-connector</p> <p><strong>Context:</strong> I wrote an API using <a href="https://graphene-python.org/" rel="nofollow noreferrer">graphene</a>, a python <a href="https://graphql.org/learn/" rel="nofollow noreferrer">graphQL</a> implementation, this is actually my first time using the graphQL specification so I'm looking to improve my code implementation for the resolvers using a MySQL database.</p> <p>As you may know, GraphQL isn't tied to any specific database or storage engine so it specifies a <em>resolve</em> method, where you "resolve" for a field in your <em>Type</em>. eg. <strong>User</strong> has a field <strong>name</strong>, so the resolve method would be <em>how</em> you get that name.</p> <p>All my types are in a package: <strong>mytypes</strong> with modules for each type, and they all follow the same styling as the following code example.</p> <p><strong>Code:</strong> Please note how the last two functions are different implementations I've tried, more on this on my concerns down below.</p> <pre><code>import graphene from database.connection import request from mytypes.user import User from mytypes.format import Format _STUDENT_ID = 'SELECT student_id FROM Rubrics WHERE id = %s' _EVALUATOR_ID = 'SELECT evaluator_id FROM Rubrics WHERE id = %s' _PROJECT_NAME = 'SELECT project_name FROM Rubrics WHERE id = %s' class Rubric(graphene.ObjectType): uid = graphene.ID() evaluator = graphene.Field(User) student = graphene.Field(User) rubricFormat = graphene.Field(Format) projectName = graphene.String() evaluationDate = graphene.Date() isPublic = graphene.Boolean() def resolve_evaluator(self, info): evaluator_id = request(_EVALUATOR_ID, self.uid) return User(uid=evaluator_id) def resolve_student(self, info): student_id = request(_STUDENT_ID, self.uid) return User(uid=student_id) def resolve_rubricFormat(self, info): request = 'SELECT format_id FROM Rubrics WHERE id = %s' format_id = make(request, self.uid) return Format(uid=format_id) def resolve_isPublic(self, info): return rubric.is_public(self.uid) </code></pre> <p><strong>Concerns:</strong></p> <ul> <li><strong>Readability</strong></li> </ul> <p>My first concern is about readability, I'm trying to follow the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP 8 styling for Python code</a> which states that I shouldn't use or should avoid </p> <blockquote> <p>More than one space around an assignment (or other) operator to align it with another.</p> </blockquote> <p>Which I do when defining my fields (uid, evaluator, student, etc), but this way it makes scanning it better in my opinion.</p> <ul> <li><strong>Resolve Implementation</strong></li> </ul> <p>As for the two methods I mentioned, first for <strong>resolve_rubricFormat</strong> I like the way <strong>make(request, self.uid)</strong> was read, where "make" was the same request imported as <strong>make</strong> but I realized I was just over-complicating.</p> <p>Then, for <strong>resolve_isPublic</strong> I was delegating the data fetching to a package <strong>resolvers</strong> that had modules for every type and had all the logic there, but switching between both the Type and its resolvers/gets at the other package was tiring not to mention the original resolve methods would lose their significance since I was calling another method that was doing what the original resolve was intended for.</p> <ul> <li><strong>Global Variables</strong></li> </ul> <p>So I switched to global variables where I place the actual SQL query and use it as <strong>request(_WHATEVER, id)</strong> eg. request(_PROJECT_NAME, self.uid) would return the project name for the specified id, and since its on a module level its understood we are talking about the Rubric id.</p> <p>But, I'm not sure if this is a good idea, what are your thoughts on this, any way to do it better?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T01:44:59.257", "Id": "210623", "Score": "2", "Tags": [ "python", "mysql" ], "Title": "Python graphene-graphql, are global constants for SQL queries a good idea?" }
210623
<p>This is some code which prints a hexdump of a list of 16 bit numbers, at 16 bytes distance for each, after the "print data" comment:</p> <pre><code>#!/usr/bin/python3 # creating test data data = [] for i in range(500): data = data + [ i &amp; 0xff, i &gt;&gt; 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # print data c = 0 out = "" for i in range(int(len(data) / 16)): if i == 512: break low = data[i * 16] high = data[i * 16 + 1] d = low | (high &lt;&lt; 8) out = out + ("%04x " % d) if (i % 16) == 15: out = out + "\n" print(out) </code></pre> <p>It works, but I think I can write it simpler with "join" and maybe list comprehension? But shouldn't be a cryptic one-liner or something, I'm just looking for a more idiomatic Python solution. I want to print the first 512 numbers, but the data array can be shorter or longer.</p>
[]
[ { "body": "<p>Here are some comments on your code:</p>\n\n<ul>\n<li>I assume the structure of the input data is to be taken as it is: one long list where only the 1 out of 8 values contribute to the output.</li>\n<li><code>c = 0</code> is defined but never used</li>\n<li>It is not recommended to use compound statements (see <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">PEP8 - \"Other Recommendations\"</a>): use a separate line for an <code>if</code> and the statement under condition.</li>\n<li><code>/</code> performs a true division (giving a float). To avoid switching between <code>float</code> and <code>int</code>, use integer division: <code>//</code></li>\n<li><code>if i == 512: break</code> could me omitted if you would limit the range of the <code>for</code> loop immediately. Instead of <code>len(data)</code> use <code>min(512*16, len(data))</code></li>\n<li>The multiplication <code>i * 16</code> can be avoided if you use the <code>step</code> argument of <code>range()</code> so that <code>i</code> takes multiples of 16.</li>\n<li>Instead of <code>\"%04x \" % d</code> use the newer <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a></li>\n<li>Instead of calculating <code>d</code>, you could just pass <code>high</code> and <code>low</code> to the string template and format each independently.</li>\n<li>Instead of <code>if (i % 16) == 15:</code> you could use a nested loop that deals with one output line</li>\n<li>Your code produces a blank at the end of each line. That seems unnecessary. With <code>\" \".join</code> you would not have this extra blank.</li>\n<li><code>out</code> has a terminating <code>\\n</code>, but <code>print</code> also prints a newline as terminator (by default). With <code>\"\\n\".join</code>you would not have this extra newline</li>\n</ul>\n\n<p>Here is how it could look:</p>\n\n<pre><code># Set a maximum to the output\nlength = min(512*16, len(data))\n\n# Format data\nlines = []\nfor line in range(0, length, 256):\n items = []\n for i in range(line, min(line+256, length), 16):\n items.append(f\"{data[i+1]:02x}{data[i]:02x}\")\n lines.append(\" \".join(items))\nout = \"\\n\".join(lines)\n\n# Output\nprint(out)\n</code></pre>\n\n<p>Here is how the above data formatting translates when using list comprehension. You can split the expression over multiple lines to improve readability: </p>\n\n<pre><code># Format data\nout = \"\\n\".join([\n \" \".join([\n f\"{data[i+1]:02x}{data[i]:02x}\"\n for i in range(line, min(line + 256, length), 16)\n ])\n for line in range(0, length, 256)\n ])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T11:48:20.920", "Id": "210634", "ParentId": "210628", "Score": "8" } }, { "body": "<p>I like the improvements by @trincot. Another improvement would be to use constants instead of numbers, makes it easier to understand and change instead of using magic numbers scattered in the code. And the f-syntax is nice, but I don't want to install Python 3.6 on my Debian machine, it still runs Python 3.5 and might break things. And I might need the word later for other things as well, and it makes the intention more clear that it is a 16 bit word, so I kept my extra word calculation. And no need to collect all lines in a string, this was just a side product of my solution to avoid multiple lines with resetting the current line and then printing it.</p>\n\n<p>My final code:</p>\n\n<pre><code>max_lines = 32\nwords_per_line = 16\nstep = 16\nline_length = words_per_line * step\nlength = min(max_lines * line_length, len(data))\nfor line in range(0, length, line_length):\n items = []\n for i in range(line, min(line + line_length, length), step):\n d = data[i] + (data[i + 1] &lt;&lt; 8)\n items.append(\"%04x\" % d)\n print(\" \".join(items))\n</code></pre>\n\n<p>Will be used for my <a href=\"https://github.com/FrankBuss/adc4\" rel=\"nofollow noreferrer\">ADC4 project</a>, which returns 16 bytes per sample, which is the reason for the big step.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T19:05:58.437", "Id": "210661", "ParentId": "210628", "Score": "0" } }, { "body": "<p>The review by trinket has covered most, if not all, of the deficits in the code.</p>\n\n<p>The one elephant left in the room is: does <code>out</code> really need to be built up as a single string, just to be printed? Could it not be printed line by line, or even per data value, and not waste time on the string concatenation operations?</p>\n\n<p>Another question is where are these 16-bit values coming from? Are they really entering Python as a <code>list</code> of integers, or perhaps are they coming in as a <code>bytes</code> or <code>bytearray</code> memory buffer type structure? `Cause we can manipulate those to extract the data easier...</p>\n\n<pre><code>data = bytes(data) # convert from list of ints into a byte array\n\nmv = memoryview(data) # convert to a memory view...\nmv = mv.cast('H') # treat every 2-bytes as a 16-bit value\nmv = mv[:8*512] # truncate to the first 512 groups of 8 values\nmv = mv[::8] # slice off the first of every 8 values\n\n# Or as one statement...\nmv = memoryview(data).cast('H')[:8*512:8]\n\n# Print out each row of the hexdump:\nfor i in range(0, len(mv), 16):\n print(\" \".join(f\"{val:04x}\" for val in mv[i:i+16]))\n\n# Or construct the big out string, and print as one unit:\nout = \"\\n\".join(\" \".join(f\"{val:04x}\" for val in mv[i:i+16])\n for i in range(0, len(mv), 16)\nprint(out)\n</code></pre>\n\n<p><em>Note</em>: The above assumes a little-endian architecture, so that when <code>cast('H')</code> is performed, the correct values are returned. If on a big-endian architecture, the code will need to be modified. See <a href=\"https://docs.python.org/3/library/sys.html#sys.byteorder\" rel=\"nofollow noreferrer\"><code>sys.byteorder</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T22:54:34.593", "Id": "210667", "ParentId": "210628", "Score": "1" } } ]
{ "AcceptedAnswerId": "210634", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T07:13:55.817", "Id": "210628", "Score": "5", "Tags": [ "python", "formatting", "number-systems" ], "Title": "Hex dump of a list of 16-bit numbers" }
210628
<p>So I'm working on a game framework and one of the things I need are access to stateful "services" that can be accessed from all over. I was initially going to use the Singleton pattern but decided to try and come up with alternatives to avoid the short comings of that pattern.</p> <p>So here is what I've got so far.</p> <p><strong>Main.cpp</strong></p> <pre><code>#include "Engine.h" #include "Logger.h" int main(int argc, char* argv[]) { Engine engine; // old { auto logger = new Logger(); engine.provide(logger); engine.getLoggerOld().log("old TEST"); engine.provide(nullptr); delete logger; } engine.getLoggerOld().log("old TEST");//wont print, just calls empty funcs // old // new { auto splogger = std::make_shared&lt;Logger&gt;(); engine.provide(splogger); engine.getLoggerNew()-&gt;log("new TEST"); } engine.getLoggerNew()-&gt;log("new TEST");//wont print, just calls empty funcs // new return 0; } </code></pre> <p><strong>Engine.h</strong></p> <pre><code>#pragma once #include &lt;memory&gt; #include "ILogger.h" #include "NullLogger.h" class Engine { public: Engine() { //old serviceLogger = &amp;nullLogger; //new spLoggerService = std::make_shared&lt;NullLogger&gt;(); } ///////// old public: void provide(ILogger* service) { if (service) { serviceLogger = service; } else { serviceLogger = &amp;nullLogger; } } ILogger&amp; getLoggerOld() const { return *serviceLogger; } private: ILogger* serviceLogger; NullLogger nullLogger; ///////// old ///////// new public: void provide(std::shared_ptr&lt;ILogger&gt; loggerService) { wpLoggerService = loggerService; } std::shared_ptr&lt;ILogger&gt; getLoggerNew() { if (wpLoggerService.expired()) { wpLoggerService = spLoggerService; } return wpLoggerService.lock(); } private: std::shared_ptr&lt;ILogger&gt; spLoggerService; std::weak_ptr&lt;ILogger&gt; wpLoggerService; ///////// new }; </code></pre> <p>I'm a bit unsure on how I should implement the services, in the above example(s) "Engine"(The Service Locator) essentially is designed to never really "own" the services, and instead it only holds a reference to the services, it's then the externally determined if/how/when the services become invalid.</p> <p>In the example sections labeled "old", these are basically how I saw this pattern implemented elsewhere. I don't like that its left up to how its used to determine if the pointers will be valid or not.</p> <p>In the example sections labeled "new" I tried to implement the more modern smart pointers, I like the automatic cleanup of the expired references, etc. But I'm still not sure if I like the way the references are handled.</p> <p>So I guess my questions are:</p> <ol> <li>Does it make sense to give total ownership of the service to the Engine(locator) and allow its life cycle to manage cleanup?</li> <li>Should I stay with the raw pointer "old" way I found in online examples?</li> <li>Should I keep going with the "new" smart pointer way?(one thing I'm not a fan of here is needing the <code>if (wpLoggerService.expired())</code> check as well as the <code>.lock()</code> when accessing a service.(maybe there is a better smart pointer way to avoide this?)</li> </ol> <p>Also if it makes sense for the Engine(Locator) to manage the life-cycle of the services, I was thinking of maybe making the "provide" function similar to that of the <code>std::vector</code>'s <code>emplace_back</code> where you would do something like: <code>engine.provide&lt;Logger&gt;(/*ctor args*/)</code> and the <code>.provide&lt;T&gt;()</code> function would instantiate the object internally to prevent any ownership/access to it externally. (This just seems like a more reasonable way to let the Engine control its life-cycle, or is this dumb?)</p> <p>Disclaimer: New to C++, first time using smart pointers, please be gentle :3</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T11:07:40.933", "Id": "407188", "Score": "0", "body": "More context would be useful. Is there a fixed, known number of services? Do they each have a “do nothing” version? Do you really need a new object, or just runtime reconfigurations? Are there multiple engines? Can callers simply call via the engine rather than getting their own version of the logger?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T12:07:25.247", "Id": "407190", "Score": "0", "body": "@Edward In my use case, I can only imagine needing one instance of Engine. As for the Services, they will be added to overtime. Currently I have a \"do nothing\" version of each service. As far as how I'd see classes access the engine instance, I was thinking of providing it as a constructor argument to the base class of everything that requires engine access. So like `entities.emplace_back<Entity>(engine)` etc. That way I can avoid the \"evil\" global scope/singletons and everything stays relatively separate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T12:51:43.633", "Id": "407191", "Score": "0", "body": "It would be good if you could add to your question, explaining what you're trying to do. The current `main` doesn't really convey it. For instance, if the application is multi-threaded, that has a big impact on the design." } ]
[ { "body": "<p>Note that the \"old\" version should store the logger in a <code>std::unique_ptr</code> in <code>main</code>, rather than explicitly calling <code>new</code> and <code>delete</code>.</p>\n\n<hr>\n\n<p>The simplest possible thing would be something like this:</p>\n\n<pre><code>struct Services // previously `Engine`\n{\n Logger logger;\n};\n\nint main()\n{\n {\n Services services;\n services.logger.log(\"yep\");\n }\n\n //services.logger.log(\"nope\"); // obviously doesn't compile\n}\n</code></pre>\n\n<p>To use the logger \"somewhere else\" we can pass it into an object constructor by reference, (or pass the entire <code>Services</code> object by reference):</p>\n\n<pre><code>struct Object\n{\n explicit Object(Logger&amp; logger):\n logger(&amp;logger) { }\n\nprivate:\n\n Logger* logger;\n};\n</code></pre>\n\n<p>If necessary, the object can store the logger (or <code>Services</code>) by reference (which has the side-effect of preventing us defining assignment operators for <code>Object</code> as we can't re-assign a reference), or by pointer (which allows us to define assignment operators, but can also be reassigned to a <code>nullptr</code> (for better or worse)).</p>\n\n<p>Either way, we still depend on the lifetime of the <code>Logger</code> being longer than the lifetime of the <code>Object</code>. With C++, this is usually enforced simply by the implicit order of destruction of stack objects (and any child objects they contain), e.g.:</p>\n\n<pre><code>{\n Services services;\n Object object(services.logger);\n\n} // destruction in reverse order: first object, then services.\n</code></pre>\n\n<hr>\n\n<p>It might seem like we can use <code>std::shared_ptr</code> and <code>std::weak_ptr</code> to enforce the above constraint (longer service lifetime), but it adds overhead and complexity, and can lead to more serious issues. When we promote a <code>weak_ptr</code> to a <code>shared_ptr</code>, the new <code>shared_ptr</code> also \"owns\" the service. So the lifetime is no longer defined by <code>Services</code>, but by the service user as well.</p>\n\n<p>If we enforce the <code>Object</code> lifetime constraint properly ourselves, we don't need this. If we don't enforce that constraint, then the exact moment of a service being destroyed becomes very difficult to determine, which leads to similar problems as with <code>Singleton</code> objects.</p>\n\n<p><a href=\"https://seanmiddleditch.com/dangers-of-stdshared_ptr/\" rel=\"nofollow noreferrer\">This article has some more arguments against using <code>std::shared_ptr</code></a>, and points out that what we actually need is some sort of checked pointer or borrowed reference for debugging. Unfortunately, this doesn't exist in the C++ standard library.</p>\n\n<hr>\n\n<p>Note that if it's actually necessary to swap out, or destroy a service part-way through use, we can't store any pointer or reference to the service. It must be fetched from <code>Services</code> every time it's accessed. This is probably quite difficult to enforce though.</p>\n\n<hr>\n\n<p>In short:</p>\n\n<ul>\n<li>Avoid using this pattern if possible.</li>\n<li>Pass dependencies by reference in constructors (or other functions).</li>\n<li>Ensure that lifetimes are well-defined and easy to understand (i.e. avoid <code>std::shared_ptr</code>).</li>\n<li>Ensure that the lifetime of the <code>Engine</code> / <code>Services</code> exceeds the lifetime of anything that uses them.</li>\n<li>Don't move or copy the individual services, or the <code>Services</code> class.</li>\n</ul>\n\n<hr>\n\n<p>And to answer your questions:</p>\n\n<ol>\n<li>Yes.</li>\n<li>Allowing direct access to the service member, returning a raw pointer from an accessor function, or returning a reference from an accessor function are all reasonable options. The first is simplest unless you have some other constraints (enforcing access through an interface, or enforcing const correctness).</li>\n<li>I'd argue not (see above).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T04:51:19.220", "Id": "407269", "Score": "0", "body": "Back to the drawing board I go. Your post makes me thing I may have over complicated everything a bit to much, I'll see what I can do about making it simpler/following your suggestions. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T19:03:28.080", "Id": "210659", "ParentId": "210630", "Score": "1" } } ]
{ "AcceptedAnswerId": "210659", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T08:38:22.607", "Id": "210630", "Score": "2", "Tags": [ "c++", "design-patterns" ], "Title": "C++ smart pointers and the Service Locator (anti-?)pattern" }
210630
<p>The use cases I’m facing require me to have a C++ data type that can store and manipulate the state of somewhere between 400 and 500 bits. In addition it is necessary to be able to store that state within SQL server databases in an efficient manner, i.e. not wasting unnecessary space because there will be a lot of such database records eventually.</p> <p>I had a look at <code>std::bitset</code> which is capable of storing that amount of bits but lacks the capability to export its internal state in an efficient way. It offers <code>to_ulong</code> and <code>to_ullong</code> which both are too small to store up to 500 bits and <code>to_string</code> which would result in a string of 500 characters, i.e. one character per bit which seems rather inefficient.</p> <p>I figured I could pack all bits that I require into a byte array that I could store in the SQL database as a blob and hence use eight times less space compared to storing them as a 500 character string.</p> <p>First I tried to turn the output of <code>std::bitset</code> into a byte array but realized that the logic required to do so might as well be turned into its own class that directly operates with a byte array.</p> <p>The class that I’m posting here is the result of that approach. Its interface is inspired by <code>std::bitset</code> but deviates in some cases and does not offer all functionality that <code>std::bitset</code> does, simply because I have no use for that functionality.</p> <p>It does provide read-only access to the array that stores the bits and offers creating an object from such an array so that I can store to and load the state from the database.</p> <p>The class is designed to be compiled with C++14 but I will migrate my code base to C++17 within a few months.</p> <p>When reviewing, could you please consider commenting on the following topics?</p> <ul> <li>Currently, there is no overloaded <code>=</code> operator, only a copy constructor. For this particular case, is overloading <code>=</code> necessary / does make sense?</li> <li>Given that I switch to C++17: Are there any parts of the code that could be simplified using C++17?</li> <li>I’m unsure how to overload the <code>[]</code> operator so that it can be used to set/get individual bits. I assume I'll need some kind of proxy object but I'm unsure how best to do it. Hints on how to do this would be appreciated.</li> <li>I use <code>#pragma once</code> instead of the more traditional include guards because the compilers (Clang and Microsoft Visual C++) on all platforms that I build for (Android, iOS, Windows) support it. I’m unaware of any downsides of using it. Any comments regarding this?</li> <li>I’m covering the class using the unit tests that I posted. They are built on top of Microsoft’s CppUnitTestFramework that ships together with Visual Studio. Comments regarding those tests are highly appreciated.</li> <li>The method to access individual bits is named <code>get</code> while the corresponding method of <code>std::bitset</code> is named <code>test</code>. I used <code>get</code> as name because “it just makes more sense to me than <code>test</code>”. You might consider this to be a drawback because the class cannot be used as a drop-in replacement for <code>std::bitset</code> that way. However, as mentioned not all functionality is provided anyway (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>, <code>[]</code> operators are missing, etc.). Comments regarding this?</li> </ul> <p>The class:</p> <pre><code>#pragma once #include &lt;array&gt; namespace common { template&lt;std::size_t bit_count&gt; class bitpattern { public: static constexpr std::size_t BitCount = bit_count; static constexpr std::size_t ByteCount = (bit_count % CHAR_BIT) ? (bit_count / CHAR_BIT) + 1 : (bit_count / CHAR_BIT); bitpattern() { } // The string that is passed to this method is read from right to left, i.e. // the last character on the right end of the string is turned into the bit // at index 0. bitpattern(const std::string bits) { std::size_t character_count = (bits.length() &gt; bit_count) ? bit_count : bits.length(); std::size_t first_character = bits.length() - 1; for(std::size_t i = 0; i &lt; character_count; i++) { switch(bits[first_character - i]) { case '0': continue; case '1': set(i); break; default : throw std::invalid_argument("Argument string contains characters other than '0' and '1'."); } } } bitpattern(const std::array&lt;uint8_t, ByteCount&gt; bits) { _bit_container = bits; _bit_container[ByteCount - 1] &amp;= _padding_bit_mask; // Ensure that the padding bits are 0 } bitpattern(const bitpattern&lt;bit_count&gt;&amp; pattern) { _bit_container = pattern._bit_container; } bitpattern&lt;bit_count&gt;&amp; flip() { for(uint8_t&amp; byte : _bit_container) { byte = ~byte; } _bit_container[ByteCount - 1] &amp;= _padding_bit_mask; // Ensure that the padding bits stay 0 return *this; } bitpattern&lt;bit_count&gt;&amp; flip(std::size_t index) { _throw_if_too_large(index); _bit_container[index / CHAR_BIT] ^= (1u &lt;&lt; (index % CHAR_BIT)); return *this; } bool get(std::size_t index) const { _throw_if_too_large(index); return _bit_container[index / CHAR_BIT] &amp; (1u &lt;&lt; (index % CHAR_BIT)); } bitpattern&lt;bit_count&gt;&amp; set(std::size_t index) { _throw_if_too_large(index); _bit_container[index / CHAR_BIT] |= (1u &lt;&lt; (index % CHAR_BIT)); return *this; } bitpattern&lt;bit_count&gt;&amp; reset(std::size_t index) { _throw_if_too_large(index); _bit_container[index / CHAR_BIT] &amp;= ~(1u &lt;&lt; (index % CHAR_BIT)); return *this; } bitpattern&lt;bit_count&gt;&amp; reset() { _bit_container.fill(0); return *this; } bool all() const { std::size_t i = 0; for(; i &lt; (ByteCount - 1); i++) { if(_bit_container[i] != 0b1111'1111) { return false; } } // The last byte is treated separately because it could contain // padding bits that are 0. return _bit_container[i] == _padding_bit_mask; } bool any() const { for(uint8_t byte : _bit_container) { if(byte &gt; 0) { return true; } } return false; } bool none() const { for(uint8_t byte : _bit_container) { if(byte &gt; 0) { return false; } } return true; } std::size_t count() const { std::size_t count = 0; for(uint8_t byte : _bit_container) { // Implementation of the Hamming Weight algorithm for 8-bit numbers. // See https://en.wikipedia.org/wiki/Hamming_weight // and https://stackoverflow.com/a/30692782/5548098 byte = byte - ((byte &gt;&gt; 1) &amp; 0b0101'0101); byte = (byte &amp; 0b0011'0011) + ((byte &gt;&gt; 2) &amp; 0b0011'0011); count += ((byte + (byte &gt;&gt; 4)) &amp; 0b0000'1111); } return count; } bool operator==(const bitpattern&lt;bit_count&gt;&amp; right) const { for(std::size_t i = 0; i &lt; ByteCount; i++) { if(_bit_container[i] != right._bit_container[i]) { return false; } } return true; } bool operator!=(const bitpattern&lt;bit_count&gt;&amp; right) const { for(std::size_t i = 0; i &lt; ByteCount; i++) { if(_bit_container[i] == right._bit_container[i]) { return false; } } return true; } bitpattern&lt;bit_count&gt;&amp; operator&amp;=(const bitpattern&lt;bit_count&gt;&amp; right) { for(std::size_t i = 0; i &lt; ByteCount; i++) { _bit_container[i] &amp;= right._bit_container[i]; } return *this; } bitpattern&lt;bit_count&gt;&amp; operator|=(const bitpattern&lt;bit_count&gt;&amp; right) { for(std::size_t i = 0; i &lt; ByteCount; i++) { _bit_container[i] |= right._bit_container[i]; } return *this; } bitpattern&lt;bit_count&gt;&amp; operator^=(const bitpattern&lt;bit_count&gt;&amp; right) { for(std::size_t i = 0; i &lt; ByteCount; i++) { _bit_container[i] ^= right._bit_container[i]; } return *this; } bitpattern&lt;bit_count&gt; operator&amp;(const bitpattern&lt;bit_count&gt;&amp; right) { bitpattern&lt;bit_count&gt; resulting_pattern; for(std::size_t i = 0; i &lt; ByteCount; i++) { resulting_pattern._bit_container[i] = _bit_container[i] &amp; right._bit_container[i]; } return resulting_pattern; } bitpattern&lt;bit_count&gt; operator|(const bitpattern&lt;bit_count&gt;&amp; right) { bitpattern&lt;bit_count&gt; resulting_pattern; for(std::size_t i = 0; i &lt; ByteCount; i++) { resulting_pattern._bit_container[i] = _bit_container[i] | right._bit_container[i]; } return resulting_pattern; } bitpattern&lt;bit_count&gt; operator^(const bitpattern&lt;bit_count&gt;&amp; right) { bitpattern&lt;bit_count&gt; resulting_pattern; for(std::size_t i = 0; i &lt; ByteCount; i++) { resulting_pattern._bit_container[i] = _bit_container[i] ^ right._bit_container[i]; } return resulting_pattern; } bitpattern&lt;bit_count&gt; operator~() { bitpattern&lt;bit_count&gt; inverted_pattern; for(std::size_t i = 0; i &lt; ByteCount; i++) { inverted_pattern._bit_container[i] = ~_bit_container[i]; } inverted_pattern._bit_container[ByteCount - 1] &amp;= _padding_bit_mask; // Ensure that the padding bits stay 0 return inverted_pattern; } // Note that the string generated by this method must be read from // right to left, i.e. the bit with index 0 is to be found at the // right end of the string. The approach is taken from numbers where // the least significant number is found at the right end. std::string to_string() const { std::string pattern; pattern.reserve(bit_count); for(int i = (bit_count - 1); i &gt;= 0; i--) { pattern.append(get(i) ? "1" : "0"); } return pattern; } const std::array&lt;uint8_t, ByteCount&gt;&amp; array() const { return _bit_container; } private: void _throw_if_too_large(std::size_t index) const { if(index &gt;= bit_count) { throw std::out_of_range("Index is too large."); } } static constexpr uint8_t _create_padding_bit_mask() { uint8_t count = bit_count % CHAR_BIT; uint8_t bit_mask = 0b1111'1111; if(count) { for(int i = (CHAR_BIT - 1); i &gt;= count; i--) { bit_mask ^= (1 &lt;&lt; i); } } return bit_mask; } static constexpr uint8_t _padding_bit_mask = _create_padding_bit_mask(); std::array&lt;uint8_t, ByteCount&gt; _bit_container{}; }; } </code></pre> <p>Associated unit tests:</p> <pre><code>#include "CppUnitTest.h" #include "../bitpattern/bitpattern.h" #include &lt;map&gt; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace common { TEST_CLASS(bitpatterntests) { public: TEST_METHOD(ConstructionZeroInitializesArray) { bitpattern&lt;69&gt; pattern; std::array&lt;uint8_t, pattern.ByteCount&gt; actual_output = pattern.array(); std::array&lt;uint8_t, pattern.ByteCount&gt; expected_output = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(ConstructionFromStringWorksEvenIfTheStringIsTooLarge) { std::string bits = "10101110100011010101011100101"; bitpattern&lt;14&gt; pattern_from_string(bits); bitpattern&lt;14&gt; pattern_reference; Assert::IsTrue(pattern_from_string == pattern_reference.set(0).set(2).set(5).set(6).set(7).set(9).set(11).set(13)); } TEST_METHOD(ConstructionFromStringWorksEvenIfTheStringIsTooSmall) { std::string bits = "101001110101010"; bitpattern&lt;28&gt; pattern_from_string(bits); bitpattern&lt;28&gt; pattern_reference; Assert::IsTrue(pattern_from_string == pattern_reference.set(1).set(3).set(5).set(7).set(8).set(9).set(12).set(14)); } TEST_METHOD(ConstructionFromStringWorksWithStringOfSameLength) { std::string bits = "001000110011010001011"; bitpattern&lt;21&gt; pattern_from_string(bits); bitpattern&lt;21&gt; pattern_reference; Assert::IsTrue(pattern_from_string == pattern_reference.set(0).set(1).set(3).set(7).set(9).set(10).set(13).set(14).set(18)); } TEST_METHOD(ConstructionFromEmptyStringZeroInitializesArray) { std::string bits = ""; bitpattern&lt;13&gt; pattern(bits); std::array&lt;uint8_t, pattern.ByteCount&gt; actual_output = pattern.array(); std::array&lt;uint8_t, pattern.ByteCount&gt; expected_output = { 0, 0 }; Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(ConstructionFromStringContainingCharactersOtherThanOneAndZeroThrowsException) { std::string bits = "01010A0102"; auto func = [bits] { bitpattern&lt;29&gt; pattern(bits); }; Assert::ExpectException&lt;std::invalid_argument&gt;(func); } TEST_METHOD(ConstructionFromArrayZeros1PaddingBits) { bitpattern&lt;7&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0111'1111); } TEST_METHOD(ConstructionFromArrayZeros2PaddingBits) { bitpattern&lt;6&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0011'1111); } TEST_METHOD(ConstructionFromArrayZeros3PaddingBits) { bitpattern&lt;5&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0001'1111); } TEST_METHOD(ConstructionFromArrayZeros4PaddingBits) { bitpattern&lt;4&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0000'1111); } TEST_METHOD(ConstructionFromArrayZeros5PaddingBits) { bitpattern&lt;3&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0000'0111); } TEST_METHOD(ConstructionFromArrayZeros6PaddingBits) { bitpattern&lt;2&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0000'0011); } TEST_METHOD(ConstructionFromArrayZeros7PaddingBits) { bitpattern&lt;1&gt; pattern(std::array&lt;uint8_t, 1&gt; { 0b1111'1111 }); Assert::IsTrue(pattern.array()[0] == 0b0000'0001); } TEST_METHOD(CopyConstructedObjectIsEqualToOriginalObject) { bitpattern&lt;34&gt; pattern; bitpattern&lt;34&gt; pattern_copied(pattern); Assert::IsTrue(pattern == pattern_copied); } TEST_METHOD(FlipInvertsAllBitsExceptPaddingBits) { std::array&lt;uint8_t, 4&gt; input = { 0b0011'1010, 0b1111'1011, 0b0001'1011, 0b0110'1010 }; std::array&lt;uint8_t, 4&gt; expected_output = { 0b1100'0101, 0b0000'0100, 0b1110'0100, 0b0000'0101 }; bitpattern&lt;27&gt; pattern(input); pattern.flip(); std::array&lt;uint8_t, 4&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(FlipInvertsAllBitsIfThereAreNoPaddingBits) { std::array&lt;uint8_t, 3&gt; input = { 0b1010'0110, 0b1111'1111, 0b0110'1001 }; std::array&lt;uint8_t, 3&gt; expected_output = { 0b0101'1001, 0b0000'0000, 0b1001'0110 }; bitpattern&lt;24&gt; pattern(input); pattern.flip(); std::array&lt;uint8_t, 3&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(FlipInvertsTheSpecifiedBit) { std::array&lt;uint8_t, 5&gt; input = { 0b0010'0010, 0b1010'1001, 0b0110'0101, 0b1101'0000, 0b0011'1110 }; std::array&lt;uint8_t, 5&gt; expected_output = { 0b0000'1011, 0b0011'1001, 0b0110'1101, 0b0101'1000, 0b0000'0110 }; bitpattern&lt;36&gt; pattern(input); pattern.flip(0).flip(3).flip(5).flip(12).flip(15).flip(19).flip(27).flip(31).flip(35); std::array&lt;uint8_t, 5&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(FlipThrowsExceptionForIndexThatIsTooLarge) { bitpattern&lt;12&gt; pattern; auto func = [&amp;pattern] { pattern.flip(pattern.BitCount); }; Assert::ExpectException&lt;std::out_of_range&gt;(func); } TEST_METHOD(GetReturnsTheValueOfTheSpecifiedBit) { std::array&lt;uint8_t, 3&gt; input = { 0b0110'0100, 0b0010'1011 }; bitpattern&lt;23&gt; pattern(input); bool is_set = pattern.get(2) &amp;&amp; pattern.get(5) &amp;&amp; pattern.get(6) &amp;&amp; pattern.get(8) &amp;&amp; pattern.get(9) &amp;&amp; pattern.get(11) &amp;&amp; pattern.get(13); bool is_not_set = !pattern.get(0) &amp;&amp; !pattern.get(1) &amp;&amp; !pattern.get(3) &amp;&amp; !pattern.get(4) &amp;&amp; !pattern.get(7) &amp;&amp; !pattern.get(10) &amp;&amp; !pattern.get(12) &amp;&amp; !pattern.get(14) &amp;&amp; !pattern.get(15); Assert::IsTrue(is_set &amp;&amp; is_not_set); } TEST_METHOD(GetThrowsExceptionForIndexThatIsTooLarge) { bitpattern&lt;18&gt; pattern; auto func = [&amp;pattern] { pattern.get(pattern.BitCount); }; Assert::ExpectException&lt;std::out_of_range&gt;(func); } TEST_METHOD(SetChangesTheSpecifiedBitToOne) { std::array&lt;uint8_t, 3&gt; expected_output = { 0b0011'1001, 0b0100'0100, 0b0001'0110 }; bitpattern&lt;21&gt; pattern; pattern.set(0).set(3).set(4).set(5).set(10).set(14).set(17).set(18).set(20); std::array&lt;uint8_t, 3&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(SetAllowsChangingAllBits) { std::array&lt;uint8_t, 12&gt; input = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; std::array&lt;uint8_t, 12&gt; expected_output = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0b0000'0111 }; bitpattern&lt;91&gt; pattern; for(std::size_t i = 0; i &lt; pattern.BitCount; i++) { pattern.set(i); } std::array&lt;uint8_t, 12&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(SetThrowsExceptionForIndexThatIsTooLarge) { bitpattern&lt;44&gt; pattern; auto func = [&amp;pattern] { pattern.get(pattern.BitCount); }; Assert::ExpectException&lt;std::out_of_range&gt;(func); } TEST_METHOD(ResetChangesTheSpecifiedBitToZero) { std::array&lt;uint8_t, 4&gt; input = { 0b0111'1011, 0b0111'0101, 0b1101'0110, 0b0001'0111 }; std::array&lt;uint8_t, 4&gt; expected_output = { 0b0001'1001, 0b0001'0001, 0b1101'0010, 0b0000'0000 }; bitpattern&lt;25&gt; pattern(input); pattern.reset(1).reset(5).reset(6).reset(10).reset(13).reset(14).reset(16).reset(18).reset(24); std::array&lt;uint8_t, 4&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(ResetChangesAllBitsToZero) { std::array&lt;uint8_t, 12&gt; input = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0b0011'1111 }; std::array&lt;uint8_t, 12&gt; expected_output = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; bitpattern&lt;94&gt; pattern; pattern.reset(); std::array&lt;uint8_t, 12&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(ResetChangesAllBitsToZeroIndividually) { std::array&lt;uint8_t, 12&gt; input = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0b0011'1111 }; std::array&lt;uint8_t, 12&gt; expected_output = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; bitpattern&lt;94&gt; pattern; for(std::size_t i = 0; i &lt; pattern.BitCount; i++) { pattern.reset(i); } std::array&lt;uint8_t, 12&gt; actual_output = pattern.array(); Assert::IsTrue(actual_output == expected_output); } TEST_METHOD(ResetThrowsExceptionForIndexThatIsTooLarge) { bitpattern&lt;86&gt; pattern; auto func = [&amp;pattern] { pattern.get(pattern.BitCount); }; Assert::ExpectException&lt;std::out_of_range&gt;(func); } TEST_METHOD(AllReturnsTrueIfAllBitsAreOne) { std::array&lt;uint8_t, 8&gt; input = { 255, 255, 255, 255, 255, 255, 255, 255 }; bitpattern&lt;58&gt; pattern(input); Assert::IsTrue(pattern.all()); } TEST_METHOD(AllReturnsTrueIfPaddingBitsAreZero) { std::array&lt;uint8_t, 5&gt; input = { 0b1111'1111, 0b1111'1111, 0b1111'1111, 0b1111'1111, 0b0000'0001 }; bitpattern&lt;33&gt; pattern(input); Assert::IsTrue(pattern.all()); } TEST_METHOD(AllReturnsFalseIfNotAllBitsAreOne) { std::array&lt;uint8_t, 5&gt; input = { 0b0111'0111, 0b1111'1111, 0b1101'0111, 0b1111'1110, 0b0001'0000 }; bitpattern&lt;37&gt; pattern(input); Assert::IsFalse(pattern.all()); } TEST_METHOD(AnyReturnsTrueIfAnyBitIsOne) { std::array&lt;uint8_t, 3&gt; input = { 0b0000'0000, 0b0010'0000, 0b0000'0000 }; bitpattern&lt;18&gt; pattern(input); Assert::IsTrue(pattern.any()); } TEST_METHOD(AnyReturnsFalseIfAllBitAreZero) { std::array&lt;uint8_t, 3&gt; input = { 0b0000'0000, 0b0000'0000, 0b0000'0000 }; bitpattern&lt;18&gt; pattern(input); Assert::IsFalse(pattern.any()); } TEST_METHOD(NoneReturnsTrueIfNoBitsAreOne) { std::array&lt;uint8_t, 4&gt; input = { 0b0000'0000, 0b0000'0000, 0b0000'0000, 0b0000'0000 }; bitpattern&lt;29&gt; pattern(input); Assert::IsTrue(pattern.none()); } TEST_METHOD(NoneReturnsFalseIfAnyBitsAreOne) { std::array&lt;uint8_t, 4&gt; input = { 0b0100'0100, 0b0001'0000, 0b0010'0000, 0b0000'0010 }; bitpattern&lt;29&gt; pattern(input); Assert::IsFalse(pattern.none()); } TEST_METHOD(CountReturnsTheCorrectNumberOfBitsSetToOne) { const std::map&lt;std::size_t, std::array&lt;uint8_t, 4&gt;&gt; records { // Bit count (map key) does not include padding bits { 0, { 0b0000'0000, 0b0000'0000, 0b0000'0000, 0b0000'0000 } }, { 15, { 0b1010'1010, 0b1010'1010, 0b1010'1010, 0b1010'1010 } }, { 16, { 0b1111'1111, 0b0000'0000, 0b1111'1111, 0b0000'0000 } }, { 16, { 0b0000'0000, 0b1111'1111, 0b0000'0000, 0b1111'1111 } }, { 15, { 0b0010'0001, 0b1011'0011, 0b0011'0001, 0b0011'1011 } }, { 11, { 0b1000'0100, 0b0010'1000, 0b0101'0010, 0b1110'1110 } }, { 7, { 0b0011'1000, 0b0000'0010, 0b0001'1000, 0b0110'0000 } }, { 4, { 0b0000'0001, 0b0000'0001, 0b0000'0001, 0b0000'0001 } }, { 2, { 0b0000'0000, 0b0000'0001, 0b0000'0000, 0b0000'0001 } }, { 0, { 0b0000'0000, 0b0000'0000, 0b0000'0000, 0b1100'0000 } }, { 7, { 0b1111'0000, 0b0001'1000, 0b0000'0000, 0b0000'0001 } }, { 18, { 0b1011'1110, 0b0111'1110, 0b0000'0000, 0b1111'1111 } }, { 30, { 0b1111'1111, 0b1111'1111, 0b1111'1111, 0b1111'1111 } }, }; for(auto const&amp; record : records) { bitpattern&lt;30&gt; pattern(record.second); std::size_t count = pattern.count(); std::wstring message = L"Expected " + std::to_wstring(record.first) + L" ones (1) in " + wstring_from_string(pattern.to_string()) + L" but counted " + std::to_wstring(count); Assert::IsTrue(count == record.first, message.c_str()); } } TEST_METHOD(EqualOperatorReturnsTrueWhenComparingAnObjectWithItself) { bitpattern&lt;60&gt; pattern; pattern.set(48).set(12); Assert::IsTrue(pattern == pattern); } TEST_METHOD(EqualOperatorReturnsTrueWhenComparingTwoSimilarObjects) { std::array&lt;uint8_t, 3&gt; input = { 0b0010'0011, 0b0000'0001, 0b0110'0001 }; bitpattern&lt;24&gt; pattern1(input); bitpattern&lt;24&gt; pattern2(input); Assert::IsTrue(pattern1 == pattern2); } TEST_METHOD(EqualOperatorReturnsFalseWhenComparingTwoDifferentObjects) { bitpattern&lt;17&gt; pattern1(std::array&lt;uint8_t, 3&gt; { 0b0101'1010, 0b1100'0001, 0b0001'0011 }); bitpattern&lt;17&gt; pattern2(std::array&lt;uint8_t, 3&gt; { 0b1110'0110, 0b1001'0110, 0b0111'0000 }); Assert::IsFalse(pattern1 == pattern2); } TEST_METHOD(NotEqualOperatorReturnsFalseWhenComparingAnObjectWithItself) { bitpattern&lt;129&gt; pattern; pattern.set(128).set(0); Assert::IsFalse(pattern != pattern); } TEST_METHOD(NotEqualOperatorReturnsFalseWhenComparingTwoSimilarObjects) { std::array&lt;uint8_t, 3&gt; input = { 0b0010'0011, 0b0000'0001, 0b0110'0001 }; bitpattern&lt;24&gt; pattern1(input); bitpattern&lt;24&gt; pattern2(input); Assert::IsFalse(pattern1 != pattern2); } TEST_METHOD(NotEqualOperatorReturnsTrueWhenComparingTwoDifferentObjects) { bitpattern&lt;21&gt; pattern1(std::array&lt;uint8_t, 3&gt; { 0b0111'0011, 0b0101'0101, 0b0111'0100 }); bitpattern&lt;21&gt; pattern2(std::array&lt;uint8_t, 3&gt; { 0b1010'1001, 0b1010'0110, 0b1000'1111 }); Assert::IsTrue(pattern1 != pattern2); } TEST_METHOD(BitwiseAndAssignmentOperatorProducesAndResultOfTwoPatterns) { std::array&lt;uint8_t, 3&gt; left = { 0b1110'0110, 0b0101'0110, 0b1111'0100 }; std::array&lt;uint8_t, 3&gt; right = { 0b1010'1011, 0b1010'0110, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b1010'0010, 0b0000'0110, 0b0110'0100 }; bitpattern&lt;23&gt; pattern_left (left); bitpattern&lt;23&gt; pattern_right(right); pattern_left &amp;= pattern_right; std::array&lt;uint8_t, 3&gt; actual_result = pattern_left.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseOrAssignmentOperatorProducesOrResultOfTwoPatterns) { std::array&lt;uint8_t, 3&gt; left = { 0b1110'0110, 0b0101'0110, 0b1111'0100 }; std::array&lt;uint8_t, 3&gt; right = { 0b1010'1011, 0b1010'0110, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b1110'1111, 0b1111'0110, 0b0111'1111 }; bitpattern&lt;23&gt; pattern_left (left); bitpattern&lt;23&gt; pattern_right(right); pattern_left |= pattern_right; std::array&lt;uint8_t, 3&gt; actual_result = pattern_left.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseXorAssignmentOperatorProducesXorResultOfTwoPatterns) { std::array&lt;uint8_t, 3&gt; left = { 0b1110'0110, 0b0101'0110, 0b1111'0100 }; std::array&lt;uint8_t, 3&gt; right = { 0b1010'1011, 0b1010'0110, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b0100'1101, 0b1111'0000, 0b0001'1011 }; bitpattern&lt;23&gt; pattern_left (left); bitpattern&lt;23&gt; pattern_right(right); pattern_left ^= pattern_right; std::array&lt;uint8_t, 3&gt; actual_result = pattern_left.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseAndOperatorProducesAndResultOfMultiplePatterns) { std::array&lt;uint8_t, 3&gt; input1 = { 0b0011'0101, 0b0010'1111, 0b1010'1010 }; std::array&lt;uint8_t, 3&gt; input2 = { 0b1010'1100, 0b1010'0011, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; input3 = { 0b1110'1100, 0b0111'0110, 0b1011'1100 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b0010'0100, 0b0010'0010, 0b0010'1000 }; bitpattern&lt;23&gt; pattern1(input1); bitpattern&lt;23&gt; pattern2(input2); bitpattern&lt;23&gt; pattern3(input3); bitpattern&lt;23&gt; pattern_result = pattern1 &amp; pattern2 &amp; pattern3; std::array&lt;uint8_t, 3&gt; actual_result = pattern_result.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseOrOperatorProducesOrResultOfMultiplePatterns) { std::array&lt;uint8_t, 3&gt; input1 = { 0b0011'0101, 0b0010'1111, 0b1010'1010 }; std::array&lt;uint8_t, 3&gt; input2 = { 0b1010'1100, 0b1010'0011, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; input3 = { 0b1110'1100, 0b0111'0110, 0b1011'1100 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b1111'1101, 0b1111'1111, 0b0111'1111 }; bitpattern&lt;23&gt; pattern1(input1); bitpattern&lt;23&gt; pattern2(input2); bitpattern&lt;23&gt; pattern3(input3); bitpattern&lt;23&gt; pattern_result = pattern1 | pattern2 | pattern3; std::array&lt;uint8_t, 3&gt; actual_result = pattern_result.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseXorOperatorProducesXorResultOfMultiplePatterns) { std::array&lt;uint8_t, 3&gt; input1 = { 0b0011'0101, 0b0010'1111, 0b1010'1010 }; std::array&lt;uint8_t, 3&gt; input2 = { 0b1010'1100, 0b1010'0011, 0b1110'1111 }; std::array&lt;uint8_t, 3&gt; input3 = { 0b1110'1100, 0b0111'0110, 0b1011'1100 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b0111'0101, 0b1111'1010, 0b0111'1001 }; bitpattern&lt;23&gt; pattern1(input1); bitpattern&lt;23&gt; pattern2(input2); bitpattern&lt;23&gt; pattern3(input3); bitpattern&lt;23&gt; pattern_result = pattern1 ^ pattern2 ^ pattern3; std::array&lt;uint8_t, 3&gt; actual_result = pattern_result.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(BitwiseNotOperatorInvertsThePattern) { std::array&lt;uint8_t, 3&gt; input = { 0b0100'1101, 0b1111'0000, 0b0001'1011 }; std::array&lt;uint8_t, 3&gt; expected_result = { 0b1011'0010, 0b0000'1111, 0b0110'0100 }; bitpattern&lt;23&gt; pattern(input); bitpattern&lt;23&gt; pattern_inverted = ~pattern; std::array&lt;uint8_t, 3&gt; actual_result = pattern_inverted.array(); Assert::IsTrue(actual_result == expected_result); } TEST_METHOD(InvertingTwiceResultsInTheSameObject) { bitpattern&lt;24&gt; pattern1(std::array&lt;uint8_t, 3&gt; { 0b0110'0111, 0b1111'0100, 0b0111'1011 }); bitpattern&lt;24&gt; pattern2 = ~pattern1; pattern2 = ~pattern2; Assert::IsTrue(pattern1 == pattern2); } TEST_METHOD(ToStringReturnsCorrectOutput_) { const std::map&lt;std::string, std::array&lt;uint8_t, 4&gt;&gt; records { { "10101010101010101010101010101010", { 0b1010'1010, 0b1010'1010, 0b1010'1010, 0b1010'1010 } }, { "00000000111111110000000011111111", { 0b1111'1111, 0b0000'0000, 0b1111'1111, 0b0000'0000 } }, { "11111111000000001111111100000000", { 0b0000'0000, 0b1111'1111, 0b0000'0000, 0b1111'1111 } }, { "00110011001100110011001100110011", { 0b0011'0011, 0b0011'0011, 0b0011'0011, 0b0011'0011 } }, { "11101110010100100010100010000100", { 0b1000'0100, 0b0010'1000, 0b0101'0010, 0b1110'1110 } }, { "01100000000110000000001000111000", { 0b0011'1000, 0b0000'0010, 0b0001'1000, 0b0110'0000 } }, { "00000001000000010000000100000001", { 0b0000'0001, 0b0000'0001, 0b0000'0001, 0b0000'0001 } }, { "00000001000000000000000100000000", { 0b0000'0000, 0b0000'0001, 0b0000'0000, 0b0000'0001 } }, { "00011111000001110000001100001111", { 0b0000'1111, 0b0000'0011, 0b0000'0111, 0b0001'1111 } }, { "00000001000000000001100011110000", { 0b1111'0000, 0b0001'1000, 0b0000'0000, 0b0000'0001 } }, { "11111111000000000111111010111110", { 0b1011'1110, 0b0111'1110, 0b0000'0000, 0b1111'1111 } }, { "00101011001111101110000000001111", { 0b0000'1111, 0b1110'0000, 0b0011'1110, 0b0010'1011 } }, }; for(auto const&amp; record : records) { bitpattern&lt;30&gt; pattern(record.second); std::size_t substr_index = record.first.length() - pattern.BitCount; std::string expected_output = record.first.substr(substr_index); std::string actual_output = pattern.to_string(); std::wstring message = L"Expected " + wstring_from_string(expected_output) + L" but was " + wstring_from_string(actual_output); Assert::IsTrue(actual_output == expected_output, message.c_str()); } } private: std::wstring wstring_from_string(const std::string&amp; string) { std::wstring wstring; wstring.assign(string.begin(), string.end()); return wstring; } }; } </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>The templated class uses <code>CHAR_BIT</code> but is missing this line that provides the definition:</p>\n\n<pre><code>#include &lt;climits&gt;\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The variable <code>input</code> in several tests in your code is defined but never used. Since unused variables are a sign of poor code quality, you should seek to eliminate them. Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.</p>\n\n<h2>Be careful with naming</h2>\n\n<p>I'm not sure how useful it is to take care to wrap things into a namespace, but then use the name <code>common</code> for it. It isn't necessarily wrong, but it's worth pondering whether there's a better, more apt name for the namespace.</p>\n\n<h2>Keep maintaining the tests</h2>\n\n<p>The tests are quite good. I was able to translate them all into the standard, non-Microsoft <a href=\"https://sourceforge.net/projects/cppunit/\" rel=\"noreferrer\">CppUnit</a> in a few minutes. All tests passed on my 64-bit Linux box using gcc.</p>\n\n<h2>Let the compiler generate the empty constructor</h2>\n\n<p>Instead of explicitly writing the empty constructor, explicitly tell the compiler to construct it instead:</p>\n\n<pre><code>bitpattern() = default;\n</code></pre>\n\n<p>The intent is a bit more clear in my opinion.</p>\n\n<h2>Consider adding some constructors</h2>\n\n<p>At the moment this code won't compile:</p>\n\n<pre><code> std::array&lt;uint8_t, 3&gt; input = { 0b0010'0011, 0b0000'0001, 0b0110'0001 };\n bitpattern&lt;24&gt; pattern1(input);\n bitpattern&lt;22&gt; pattern2(input);\n bitpattern&lt;24&gt; pattern3(pattern2);\n</code></pre>\n\n<p>It would be nice to have the ability to create longer bit patterns from smaller ones.</p>\n\n<p>It would also be nice to provide <code>constexpr</code> constructors for patterns like this:</p>\n\n<pre><code> constexpr bitpattern&lt;23&gt; pattern{0x6423};\n</code></pre>\n\n<p>Here's a way to do that:</p>\n\n<pre><code>constexpr bitpattern(unsigned long long val) \n{\n for (std::size_t i=0; i &lt; ByteCount; ++i) {\n _bit_container[i] = val &amp; 0xff;\n val &gt;&gt;= 8;\n }\n}\n</code></pre>\n\n<p>Note that this uses <code>for</code> loop in a <code>constexpr</code> function and uses the <code>operator[]</code> on the <code>std::array</code> and so requires C++17 or later.</p>\n\n<h2>Consider adding <code>operator[]</code></h2>\n\n<p>The <code>std::bitset</code> uses <a href=\"https://en.cppreference.com/w/cpp/utility/bitset/reference\" rel=\"noreferrer\"><code>std::bitset::reference</code></a> to enable <code>operator[]</code>. You could probably do the same. Note that there are two flavors; one is <code>constexpr</code> and returns an actual <code>bool</code> and the other returns a <code>reference</code> object. Here's one way to do that. First, here's the <code>reference</code> class which is in the <code>public</code> section of the <code>bitpattern</code> class:</p>\n\n<pre><code>class reference {\nfriend class bitpattern&lt;bit_count&gt;;\npublic:\n reference&amp; operator=(bool x) { \n if (x) {\n *ptr |= mask;\n } else {\n *ptr &amp;= ~mask;\n }\n return *this;\n }\n reference(); // leave undefined\n reference&amp; operator=(const reference&amp; x) {\n bool bit{x};\n if (bit) {\n *ptr |= mask;\n } else {\n *ptr &amp;= ~mask;\n }\n return *this;\n }\n ~reference() = default;\n operator bool() const {\n return *ptr &amp; mask;\n }\n bool operator~() const {\n return !(*ptr &amp; mask);\n }\n reference&amp; flip() {\n *ptr ^= mask;\n return *this;\n }\n\nprivate:\n reference(uint8_t *ptr, uint8_t mask) :\n ptr{ptr}, mask{mask} {} \n uint8_t *ptr;\n uint8_t mask;\n};\n</code></pre>\n\n<p>Here are the two types of <code>operator[]</code>:</p>\n\n<pre><code>constexpr bool operator[](std::size_t index) const\n{\n return _bit_container[index / CHAR_BIT] &amp; (1u &lt;&lt; (index % CHAR_BIT));\n}\n\nreference operator[](std::size_t index) \n{\n _throw_if_too_large(index);\n return reference{&amp;_bit_container[index / CHAR_BIT], \n static_cast&lt;uint8_t&gt;(1 &lt;&lt; (index % CHAR_BIT))};\n}\n</code></pre>\n\n<p>Note that the <code>constexpr</code> can't throw, so providing an out-of-range index is simply <em>undefined behavior</em> as with <code>std::bitset</code>.</p>\n\n<h2>Add tests for <code>operator[]</code></h2>\n\n<p>Here are the tests I addeed for the new <code>operator[]</code>:</p>\n\n<pre><code>void ConstexprIndexOperatorReturnsTheValueOfTheSpecifiedBit()\n{\n constexpr bitpattern&lt;23&gt; pattern{0x2b64};\n constexpr bool is_set = \n pattern[2] &amp;&amp;\n pattern[5] &amp;&amp;\n pattern[6] &amp;&amp;\n pattern[8] &amp;&amp;\n pattern[9] &amp;&amp;\n pattern[11] &amp;&amp;\n pattern[13];\n constexpr bool is_not_set = \n !pattern[0] &amp;&amp;\n !pattern[1] &amp;&amp;\n !pattern[3] &amp;&amp;\n !pattern[4] &amp;&amp;\n !pattern[7] &amp;&amp;\n !pattern[10] &amp;&amp;\n !pattern[12] &amp;&amp;\n !pattern[14] &amp;&amp;\n !pattern[15];\n CPPUNIT_ASSERT(is_set &amp;&amp; is_not_set);\n}\n\nvoid IndexOperatorReturnsTheValueOfTheSpecifiedBit()\n{\n bitpattern&lt;23&gt; pattern{0x2b64};\n bool is_set = \n pattern[2] &amp;&amp;\n pattern[5] &amp;&amp;\n pattern[6] &amp;&amp;\n pattern[8] &amp;&amp;\n pattern[9] &amp;&amp;\n pattern[11] &amp;&amp;\n pattern[13];\n bool is_not_set = \n !pattern[0] &amp;&amp;\n !pattern[1] &amp;&amp;\n !pattern[3] &amp;&amp;\n !pattern[4] &amp;&amp;\n !pattern[7] &amp;&amp;\n !pattern[10] &amp;&amp;\n !pattern[12] &amp;&amp;\n !pattern[14] &amp;&amp;\n !pattern[15];\n CPPUNIT_ASSERT(is_set &amp;&amp; is_not_set);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:02:42.897", "Id": "210650", "ParentId": "210631", "Score": "7" } }, { "body": "<p>not directly answering your question, but just a notice:\nI would say the more elegant way would be just extending the <code>std::bitset</code> and add the extra methods you need, for ex. <code>to_bytes()</code>:</p>\n\n<pre><code>template &lt;size_t N&gt;\nclass bitpattern : public std::bitset&lt;N&gt;\n{\npublic:\n using byte_t = uint8_t;\n static constexpr size_t num_bytes = N/8 + ((N % 8 == 0) ? 0 : 1);\n using bytes_t = std::array&lt;byte_t, num_bytes&gt;;\n\n // declare approprite constructors and forward to the base class\n // using base class implementation\n\n // declare the extra functions you need, for ex.\n // (this is not the efficienst method, but just for demonstration)\n bytes_t to_bytes() const noexcept\n {\n bytes_t bytes;\n\n for (size_t bix = 0; bix &lt; num_bytes; bix++)\n {\n byte b = 0;\n for (size_t bitix = 0; (bitix&lt;8) &amp;&amp; (bix*8+bitix &lt; N); bitix++)\n if (this-&gt;operator[] (bix*8 + bitix))\n b |= (0x01 &lt;&lt; bitix);\n bytes[bix] = b;\n }\n\n return bytes;\n }\n};\n</code></pre>\n\n<p>Another way would be stay at <code>std::bitset</code> and using the appropriate non-class utility functions, for ex:</p>\n\n<pre><code>template &lt;size_t N&gt;\nstd::vector&lt;uint8_t&gt; to_bytes(const std::bitset&lt;N&gt;&amp;);\n</code></pre>\n\n<p>This way (1. or 2.) you can take advantage of the functionalities <code>std::bitset</code> already offers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:38:53.040", "Id": "407231", "Score": "0", "body": "Good answer. I think it would be interesting to compare the two approaches for efficiency." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:54:17.143", "Id": "210653", "ParentId": "210631", "Score": "8" } } ]
{ "AcceptedAnswerId": "210650", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T09:19:43.943", "Id": "210631", "Score": "13", "Tags": [ "c++", "array", "c++14", "c++17", "bitset" ], "Title": "C++ data type to store and manipulate individual bits" }
210631
<p><strong>Task</strong></p> <p>Write a Program that requests the user's first name and then the user's last name. Have it print the entered names on one line and the number of letters in each name on the following line. Align each letter count with the end of the corresponding name, as in the following:</p> <pre class="lang-none prettyprint-override"><code>Klaus Dieter 5 6 </code></pre> <p><strong>My Try</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; void printWhitespace(int times) { for (int i = 0; i &lt; times; i++) { printf(" "); } } int main(void) { // get names printf("first name: "); char firstName[20]; scanf("%s", &amp;firstName); printf("last name: "); char lastName[20]; scanf("%s", &amp;lastName); // display names printf("%s %s\n", firstName, lastName); // display number of characters under last character of names int numOfWhitespace = strlen(firstName) - 1; printWhitespace(numOfWhitespace); printf("%d ", strlen(firstName)); numOfWhitespace = strlen(lastName) - 1; printWhitespace(numOfWhitespace); printf("%d\n", strlen(lastName)); } </code></pre> <p>Does the author expect that from me? Or is there a better way to write that?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:20:18.937", "Id": "407224", "Score": "3", "body": "\"Does the author expect that from me?\" How would we know? Ask him." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:08:34.673", "Id": "407237", "Score": "0", "body": "Does C now allow for inline variable declarations anywhere in code like C++ does? Or does it still require the variable declarations to come at the top of a scope before any statements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:48:48.947", "Id": "407245", "Score": "1", "body": "@selbie C99 allowed object declarations in many places. As well as C11, C18." } ]
[ { "body": "<p>Small sugggestion for <code>printWhitespace()</code>. You could do <a href=\"https://ideone.com/jBGv3n\" rel=\"nofollow noreferrer\">the following</a>:</p>\n\n<pre><code>void printWhitespace(const unsigned int times) {\n printf(\"%*s\", times, \" \");\n}\n</code></pre>\n\n<p>I have made the function argument const as it probably isn't meant to be modified. it is generally a good idea to be as \"const\" as possible as this avoids the mistake of writing to a variable that should be read-only.</p>\n\n<hr>\n\n<p>I would put the array declarations at the top of the function before any of the code with a blank line between the declarations and the first line of code.</p>\n\n<hr>\n\n<p>The function <code>scanf</code> can be used with caution... it can lead to buffer overflow attacks in the way it is used in your code. If the user enters a string longer than 19 characters (last character would be filled in as a null terminator in the buffer), <code>scanf</code> will just write on past the end of the buffer.</p>\n\n<p>You could help guard against this by using <code>scanf(\"%19s\", firstName);</code> and <code>scanf(\"%19s\", lastName);</code>. As @chux points out the length is one less than the buffer size. This is because \"String input conversions store a terminating null byte ('\\0') to mark end of the input; the maximum field width does not include this terminator.\" -- quote from man page.</p>\n\n<p>Looked into this a little more and <a href=\"https://stackoverflow.com/a/1621973/1517244\">this SO answer</a>, the author says:</p>\n\n<blockquote>\n <p>Note that the POSIX 2008 (2013) version of the scanf() family of\n functions supports a format modifier m (an assignment-allocation\n character) for string inputs (%s, %c, %[). Instead of taking a char *\n argument, it takes a char ** argument, and it allocates the necessary\n space for the value it reads</p>\n</blockquote>\n\n<p>That would be a useful way of avoiding buffer overflow, but you must remember to <code>free()</code> the buffer returned.</p>\n\n<hr>\n\n<p>The variable <code>numOfWhitespace</code> can also be <code>const</code>. Might put that to top of function too.</p>\n\n<hr>\n\n<p>Your last bit of code that tries to align the numbers to the end of the words will only align properly if the string length is 9 or less. If the string length is greater then the number will be double digits so you could account for this.</p>\n\n<hr>\n\n<p>Add <code>return 0;</code> to the end of the function. You reach the end of a non-void function without returning anything...</p>\n\n<hr>\n\n<p>Hope that helps :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:09:56.110", "Id": "407196", "Score": "1", "body": "I disagree with your `const` suggestion. Have a read through this answer - https://softwareengineering.stackexchange.com/a/204720 - with which I agree on most points. `const` is not useful on arguments unless the arguments are referential." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:26:20.177", "Id": "407197", "Score": "3", "body": "As of C99, `return 0;` in main is optional, compare https://stackoverflow.com/q/4138649/1187415." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T15:50:35.893", "Id": "407212", "Score": "2", "body": "@Reinderien: Fair enough. I can see your point of view. Personally, I think it can still be useful, because if you don't indend the parameter to be written you can still get the compiler to check for a write-in-error to that var." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T15:54:02.227", "Id": "407213", "Score": "2", "body": "@MartinR Even though `return 0` is technically optional, leaving it out is still a bad idea IMO. It's a weird language non-uniformity and I don't like non-uniformity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:53:17.500", "Id": "407246", "Score": "0", "body": "`scanf(\"%20s\", &firstName);` is off by 1. `scanf(\"%19s\", firstName);` is better to limit the width of input to 19 characters to store as a _string_ in `char firstName[20]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:58:29.720", "Id": "407248", "Score": "0", "body": "@Jimbo the `const` in `foo(const int)` is useful in the _function definition_ for the reason mentioned in the answer. It is _noise_ in a function _declaration_ (as in a `.h` file) as that const-ness info is useless to the caller. It is less work to maintain the _definition_ and _declaration_ the same. As with such _style_ issues - follow your group's coding guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:32:43.437", "Id": "407323", "Score": "0", "body": "@chux: Both good points, thanks, will update answer." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T11:52:43.710", "Id": "210635", "ParentId": "210632", "Score": "5" } }, { "body": "<p>running the posted code through the compiler results in:</p>\n\n<pre><code>gcc -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c \"untitled.c\"\n\nuntitled.c: In function ‘main’:\nuntitled.c:14:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=]\n scanf(\"%s\", &amp;firstName);\n ~^ ~~~~~~~~~~\n\nuntitled.c:17:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=]\n scanf(\"%s\", &amp;lastName);\n ~^ ~~~~~~~~~\n\nuntitled.c:23:27: warning: conversion to ‘int’ from ‘size_t {aka long unsigned int}’ may alter its value [-Wconversion]\n int numOfWhitespace = strlen(firstName) - 1;\n ^~~~~~\n\nuntitled.c:25:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t {aka long unsigned int}’ [-Wformat=]\n printf(\"%d \", strlen(firstName));\n ~^ ~~~~~~~~~~~~~~~~~\n %ld\n\nuntitled.c:27:23: warning: conversion to ‘int’ from ‘size_t {aka long unsigned int}’ may alter its value [-Wconversion]\n numOfWhitespace = strlen(lastName) - 1;\n ^~~~~~\n\nuntitled.c:29:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t {aka long unsigned int}’ [-Wformat=]\n printf(\"%d\\n\", strlen(lastName));\n ~^ ~~~~~~~~~~~~~~~~\n %ld\n</code></pre>\n\n<p>strongly suggest correcting all the above problems</p>\n\n<p>regarding:</p>\n\n<pre><code>scanf(\"%s\", &amp;firstName);\n</code></pre>\n\n<p>When calling any of the <code>scanf()</code> family of functions, 1) always check the returned value (not the parameter values) to assure the operation was successful. 2) when using the input format specifier: '%s' and/or '%[...]', always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer because those specifiers always append a NUL char to the input. This avoids any possibility of a buffer overrun and the resulting undefined behavior.</p>\n\n<p>regarding:</p>\n\n<pre><code>int numOfWhitespace = strlen(firstName) - 1;`\n</code></pre>\n\n<p>the function: <code>strlen()</code> returns a <code>size_t</code>, so the variable: <code>numOfWhitespace</code> should be declared as <code>size_t</code>, not <code>int</code></p>\n\n<p>regarding:</p>\n\n<pre><code>printf(\" \");\n</code></pre>\n\n<p>the function: <code>printf()</code> is very expensive in CPU cycles. better to use:</p>\n\n<pre><code>putc( ' ', stdout );\n</code></pre>\n\n<p>regarding this kind of statement;</p>\n\n<pre><code>printf(\"%d \", strlen(firstName));\n</code></pre>\n\n<p>the function <code>strlen()</code> returns a <code>size_t</code>, so the output format specifier should be <code>%lu</code></p>\n\n<p>Note: in C, referencing an array name degrades to the address of the first byte of the array, so given the above comments, this:</p>\n\n<pre><code>scanf(\"%s\", &amp;firstName);\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>if( scanf(\"%19s\", firstName) != 1 )\n{\n fprintf( stderr, \"failed to input first name\\n\" );\n exit( EXIT_FAILURE );\n}\n</code></pre>\n\n<p>where <code>exit()</code> and <code>EXIT_FAILURE</code> are from the header file: <code>stdlib.h</code></p>\n\n<p>the above should be enough to enable you to correct the problems.</p>\n\n<p>for ease of readability and understanding: insert an appropriate space: inside parens, inside braces, inside brackets, after commas, after semicolons, around C operators</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:27:50.530", "Id": "407219", "Score": "0", "body": "Wow, you seem to be a real pro, thank you for that comment! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:37:56.690", "Id": "407242", "Score": "0", "body": "`printf(\" \");` vs. `putc( ' ', stdout );` expense. Good compilers will analyze this and emit the same efficient code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:40:31.963", "Id": "407243", "Score": "1", "body": "\"function strlen() returns a size_t, so the output format specifier should be %lu\" misleads. The matching print specifier for `size_t` is `\"%zu\"`, `\"%zx\"` ..., not `\"%lu\"`. If the platform is pre C99, best to use `printf(\"%lu \", (unsigned long) strlen(firstName));`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:19:16.267", "Id": "210646", "ParentId": "210632", "Score": "3" } }, { "body": "<blockquote>\n <p>Program that requests the user's first name and then the user's last name</p>\n</blockquote>\n\n<p><strong>Spaces can exist in names</strong></p>\n\n<p>First names: \"Betty Jo\", \"John Paul\"</p>\n\n<p>Last names: \"Van Gogh\" , <a href=\"https://answers.yahoo.com/question/index?qid=20100303075325AAlaap3\" rel=\"nofollow noreferrer\">\"Smith Davis\"</a></p>\n\n<p><code>scanf(\"%s\", &amp;lastName);</code> fails if the name contains a space. Both first and last names, independently may contain embedded spaces.</p>\n\n<p>Alternative:</p>\n\n<pre><code>size_t trim(char *s) {\n char *start = s;\n while (isspace((unsigned char) *start)) {\n start++; \n } \n size_t len = strlen(start);\n while (len &gt; 0 &amp;&amp; isspace((unsigned char) start[len-1]) {\n len--;\n }\n start[len] = '\\0';\n memmove(s, start, len + 1);\n return len;\n} \n\n// return 1 on success\n// return EOF on end-of-file/error (and no name read)\n// return 0 otherwise (name too short (0), name too long)\nsize_t getname(const char *prompt, char *name, size_t sz) {\n fputs(prompt, stdout);\n fflush(stdout);\n char buffer[sz*2 + 2]; // allow for lots of extra leading, trailing spaces\n if (fgets(buffer, sizeof buffer, stdin) == NULL) {\n return EOF;\n }\n size_t len = trim(buffer);\n if (len == 0 || len &gt;= sz) {\n return 0;\n }\n memcpy(name, buffer, len + 1); // or strcpy(name, len)\n return 1;\n}\n</code></pre>\n\n<p><strong>Names may well exceed 19 characters.</strong></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Hubert_Blaine_Wolfeschlegelsteinhausenbergerdorff_Sr.\" rel=\"nofollow noreferrer\">600+ example</a></p>\n\n<p><a href=\"https://www.npr.org/sections/thetwo-way/2013/12/31/258673819/hawaiian-woman-gets-ids-that-fit-her-36-character-last-name\" rel=\"nofollow noreferrer\">Hawaiian Woman Gets IDs That Fit Her 36-Character Last Name</a></p>\n\n<p>Avoid hard coding such a small value. Best to set as a defined constant. The key point is production code get this value from a program specification. <em>Be prepared</em> to adjust your code nimbly to handle that.</p>\n\n<pre><code>#define NAME_FIRST_N 100\n#define NAME_LAST_N 700\n\nchar firstName[NAME_FIRST_N];\nif (getname(\"first name: \", firstName, sizeof firstName) != 1) {\n ; //Handle problem.\n}\n\nchar lastName[NAME_LAST_N];\nif (getname(\"last name: \", lastName, sizeof lastName) != 1) {\n ; //Handle problem.\n}\n</code></pre>\n\n<p><strong>Alignment</strong></p>\n\n<p>Simply prepend <code>\"*\"</code> to specify the width of the integer.</p>\n\n<pre><code>//numOfWhitespace = strlen(lastName) - 1;\n//printWhitespace(numOfWhitespace);\n//printf(\"%d\\n\", strlen(lastName));\n\nint len = (int) strlen(lastName));\nprintf(\"%*d\\n\", len, len);\n// ^^^------------- Minimum print width, pad with spaces.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T15:24:39.857", "Id": "407301", "Score": "0", "body": "Why is 1 returned on success? Isn't 0 the only recommended success code as defined by the C standard (with non-zero used for all errors)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:04:45.583", "Id": "407307", "Score": "1", "body": "@Faraz it easy enough for one to amend code to your liking. The model `getname()` is like other input standard library functions such as `scanf(format, &object)` which would return 1 on success, EOF on end-of-file/error and 0 on early matching failure. This is useful in that the caller typically needs at least a 3-way distinction. Not a 2-way as suggested by 0:good, non-0:error. `EOF` is not a _error_ so much as a signal that input is done. ...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:05:13.350", "Id": "407308", "Score": "1", "body": "@Faraz ... C does not uniformly indicates error in only 1 manner. `strtol()` with its `errno, endptr` and `malloc()` with its `NULL` sometimes indicates an error are examples of other schemes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:09:00.653", "Id": "407310", "Score": "0", "body": "I appreciate the clarification @chux, this helps better understand the reasoning for that. Thank you!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:12:32.393", "Id": "210665", "ParentId": "210632", "Score": "1" } } ]
{ "AcceptedAnswerId": "210635", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T11:05:52.497", "Id": "210632", "Score": "2", "Tags": [ "c", "strings" ], "Title": "C Primer Plus - Chapter 4 - Task 6 (string output)" }
210632
<p>This is a button that changes text and icon according to a Boolean state. for example, a play / pause button or a connect / disconnect button. The icon uses Segoe MDL2 Assets as the default font, but you can edit the template to change to another!</p> <p>The code:</p> <pre><code>public class StateImageButton : Button { static StateImageButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StateImageButton), new FrameworkPropertyMetadata(typeof(StateImageButton))); } public bool State { get { return (bool)GetValue(StateProperty); } set { SetValue(StateProperty, value); } } public Orientation Orientation { get { return (Orientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } public String TextOn { get { return (String)GetValue(TextOnProperty); } set { SetValue(TextOnProperty, value); } } public String IconOn { get { return (String)GetValue(IconOnProperty); } set { SetValue(IconOnProperty, value); } } public String TextOff { get { return (String)GetValue(TextOffProperty); } set { SetValue(TextOffProperty, value); } } public String IconOff { get { return (String)GetValue(IconOffProperty); } set { SetValue(IconOffProperty, value); } } public static readonly DependencyProperty StateProperty = DependencyProperty.Register("State", typeof(bool), typeof(StateImageButton), new PropertyMetadata(false)); public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(StateImageButton), new PropertyMetadata(Orientation.Vertical)); public static readonly DependencyProperty TextOnProperty = DependencyProperty.Register("TextOn", typeof(string), typeof(StateImageButton), new PropertyMetadata("")); public static readonly DependencyProperty IconOnProperty = DependencyProperty.Register("IconOn", typeof(string), typeof(StateImageButton), new PropertyMetadata("")); public static readonly DependencyProperty TextOffProperty = DependencyProperty.Register("TextOff", typeof(string), typeof(StateImageButton), new PropertyMetadata("")); public static readonly DependencyProperty IconOffProperty = DependencyProperty.Register("IconOff", typeof(string), typeof(StateImageButton), new PropertyMetadata("")); } </code></pre> <p>The style is below. It is based on the <code>ToolBar</code> button style, as I prefer this, but you can change it to a normal button style too. Note that <code>MinWidth</code> is bound to <code>ActualHeight</code> so the button is at least as wide as it is tall.</p> <pre><code>&lt;Style TargetType="{x:Type local:StateImageButton}" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"&gt; &lt;Setter Property="MinWidth" Value="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}"/&gt; &lt;Setter Property="Padding" Value="0"/&gt; &lt;Setter Property="ContentTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate&gt; &lt;StackPanel Margin="5" Orientation="{Binding Orientation, RelativeSource={RelativeSource AncestorType=Button}}"&gt; &lt;TextBlock Name="IconOff" FontFamily="Segoe MDL2 Assets" HorizontalAlignment="Center" FontSize="18" Text="{Binding Icon, RelativeSource={RelativeSource AncestorType=Button}}" /&gt; &lt;TextBlock Name="TextOff" Text="{Binding Text, RelativeSource={RelativeSource AncestorType=Button}}" HorizontalAlignment="Center" Margin="0,5,0,0" /&gt; &lt;/StackPanel&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding State, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"&gt; &lt;Setter TargetName="Text" Property="Text" Value="{Binding TextOn, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding State, RelativeSource={RelativeSource AncestorType=Button}}" Value="False"&gt; &lt;Setter TargetName="Text" Property="Text" Value="{Binding TextOff, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding State, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"&gt; &lt;Setter TargetName="Icon" Property="Text" Value="{Binding IconOn, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding State, RelativeSource={RelativeSource AncestorType=Button}}" Value="False"&gt; &lt;Setter TargetName="Icon" Property="Text" Value="{Binding IconOff, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>and an example of use</p> <pre><code>&lt;local:StateImageButton State="{Binding TheBooleanState}" TextOff="Start" TextOn="Stop" IconOff="&amp;#xE768;" IconOn="&amp;#xE71A;" Command="{Binding TheCommand}"/&gt; </code></pre> <p>To do: Needs a few dependency properties to make it really nice, such as FontSize, FontFamily and Foreground (colour) for both the Icon and Text.</p> <p>Update 2019-01-04: fixed bug with default values</p>
[]
[ { "body": "<p><strong>General:</strong></p>\n\n<p>Creating specialized controls for each use case was necessary with Windows Forms and it is still possible with WPF. However, WPF has powerful theming, styling and data binding capabilities, that allows to use the existing controls with customized templates / style.</p>\n\n<p>If icon and text are not changing often, I would consider to use the build-in toggle button with 2 customized styles - one for the vertical and one for the horizontal aligned icon / text representation.</p>\n\n<p><strong>Review:</strong></p>\n\n<p>If you need a button where text and icon should be highly customizable, it makes sense to create a new button with additional dependency properties.</p>\n\n<p>Some points that may improve the implemenation:</p>\n\n<ul>\n<li><p>use ToggleButton as base class and replace the \"State\" property with the exiting (and known by all developers) \"IsChecked\" property.</p></li>\n<li><p>Instead of setting a \"DataTemplate\" to the \"ContentTemplate\" property, I would set a \"ControlTemplate\" to the \"Template\" property which is the right way for defining the appearance of a control.</p></li>\n<li><p>use \"TemplateBinding\" for the wrapped controls, so that fontsize, color, ... can be configured.</p>\n\n<pre><code>&lt;DataTemplate&gt;\n &lt;StackPanel Margin=\"5\"\n Orientation=\"{Binding Orientation, RelativeSource={RelativeSource AncestorType=Button}}\"&gt;\n &lt;TextBlock Name=\"IconOff\" \n FontFamily=\"{TemplateBinding FontFamily\"}\n HorizontalAlignment=\"Center\"\n FontSize=\"{TemplateBinding FontSize, Converter=FontSizeToIconSizeConverter}\"\n Text=\"{Binding Icon, RelativeSource={RelativeSource AncestorType=Button}}\" /&gt;\n &lt;TextBlock Name=\"TextOff\" \n FontFamily=\"{TemplateBinding FontFamily\"}\n HorizontalAlignment=\"Center\"\n FontSize=\"{TemplateBinding FontSize}\"\n Text=\"{Binding Text, RelativeSource={RelativeSource AncestorType=Button}}\"\n HorizontalAlignment=\"Center\"\n Margin=\"0,5,0,0\" /&gt;\n &lt;/StackPanel&gt;\n ...\n&lt;/DataTemplate&gt;\n</code></pre></li>\n<li><p>One Trigger can have mulitple setters, there is no need to define multiple DataTrigger with the same logic:</p>\n\n<pre><code> &lt;DataTemplate.Triggers&gt;\n &lt;DataTrigger Binding=\"{Binding State, RelativeSource={RelativeSource AncestorType=Button}}\" Value=\"True\"&gt;\n &lt;Setter TargetName=\"Text\" Property=\"Text\" Value=\"{Binding TextOn, RelativeSource={RelativeSource AncestorType=Button}}\"/&gt;\n &lt;Setter TargetName=\"Icon\" Property=\"Text\" Value=\"{Binding IconOn, RelativeSource={RelativeSource AncestorType=Button}}\"/&gt;\n &lt;/DataTrigger&gt;\n &lt;DataTrigger Binding=\"{Binding State, RelativeSource={RelativeSource AncestorType=Button}}\" Value=\"False\"&gt;\n &lt;Setter TargetName=\"Text\" Property=\"Text\" Value=\"{Binding TextOff, RelativeSource={RelativeSource AncestorType=Button}}\"/&gt;\n &lt;Setter TargetName=\"Icon\" Property=\"Text\" Value=\"{Binding IconOff, RelativeSource={RelativeSource AncestorType=Button}}\"/&gt;\n &lt;/DataTrigger&gt;\n&lt;/DataTemplate.Triggers&gt;\n</code></pre></li>\n</ul>\n\n<p>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:46:58.017", "Id": "407825", "Score": "0", "body": "But what about the extra dependancy properties needed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:26:08.913", "Id": "407828", "Score": "0", "body": "I have updated my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:41:02.733", "Id": "407830", "Score": "0", "body": "`FontSizeToIconSizeConverter` I like it!. For the Content vs Control template, I did it via ContentTemplate so that the inbuilt Button design and behaviours would be used by default. ToggleButton IsActive is a good idea, I guess if I go that way I will have to do a new ControlTemplate to remove the IsActive highlight anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:42:50.477", "Id": "407831", "Score": "0", "body": "By the way, I'm still not completely sure why I can use `TemplateBinding` for the default button dependancy properties, but have to use `RelativeSource={RelativeSource AncestorType=Button}` for the dependency properties in my derived class, can you shed some light?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:57:46.510", "Id": "407860", "Score": "0", "body": "TemplateBinding can be used within ControlTemplates only. However, your approach with the relative source should also work for font and font size :)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:42:27.823", "Id": "210964", "ParentId": "210639", "Score": "2" } } ]
{ "AcceptedAnswerId": "210964", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:31:35.957", "Id": "210639", "Score": "2", "Tags": [ "c#", "wpf", "xaml" ], "Title": "Vertical WPF icon button that uses Segoe MDL2 font for icon" }
210639
<p>Given an <strong>R</strong> x <strong>C</strong> grid of 1s and 0s (or <code>True</code> and <code>False</code> values), I need a function that can find the <strong>size</strong> of the largest connected component of 1s. For example, for the following grid,</p> <pre class="lang-python prettyprint-override"><code>grid = [[0, 1, 0, 1], [1, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]] </code></pre> <p>The answer is 5.</p> <hr> <p>Here is my implementation:</p> <pre class="lang-python prettyprint-override"><code>def largest_connected_component(nrows, ncols, grid): """Find largest connected component of 1s on a grid.""" def traverse_component(i, j): """Returns no. of unseen elements connected to (i,j).""" seen[i][j] = True result = 1 # Check all four neighbours if i &gt; 0 and grid[i-1][j] and not seen[i-1][j]: result += traverse_component(i-1, j) if j &gt; 0 and grid[i][j-1] and not seen[i][j-1]: result += traverse_component(i, j-1) if i &lt; len(grid)-1 and grid[i+1][j] and not seen[i+1][j]: result += traverse_component(i+1, j) if j &lt; len(grid[0])-1 and grid[i][j+1] and not seen[i][j+1]: result += traverse_component(i, j+1) return result seen = [[False] * ncols for _ in range(nrows)] # Tracks size of largest connected component found component_size = 0 for i in range(nrows): for j in range(ncols): if grid[i][j] and not seen[i][j]: temp = traverse_component(i, j) if temp &gt; component_size: component_size = temp return component_size </code></pre> <p>Feel free to use the following code to generate random grids to test the function,</p> <pre class="lang-python prettyprint-override"><code>from random import randint N = 20 grid = [[randint(0,1) for _ in range(N)] for _ in range(N)] </code></pre> <hr> <p><strong>Problem:</strong> My implementation runs too slow (by about a factor of 3). Since I wrote this as a naive approach by myself, I am guessing there are clever optimizations that can be made.</p> <p><strong>Context:</strong> This is for solving the <a href="https://codejam.withgoogle.com/2018/challenges/0000000000007706/dashboard/00000000000459f4" rel="nofollow noreferrer">Gridception</a> problem from Round 2 of Google Codejam 2018. My goal is to solve the problem in Python 3. <strong>As a result, there is a hard constraint of using only the Python 3 standard library.</strong></p> <p>I have figured out that this particular portion of the full solution is my performance bottleneck and thus, my solution fails to clear the <em>Large Input</em> due to being too slow.</p> <p>Thank you so much!</p> <hr> <p>Edit: <strong>Adding some <code>timeit</code> benchmarks</strong></p> <p>For a randomly generated 20 x 20 grid, my implementation takes <strong>219 +/- 41 μs</strong> (a grid of 0s takes 30 μs, and a grid of 1s takes 380 μs).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:49:18.690", "Id": "407233", "Score": "1", "body": "This question is very similar to [counting the connected components](https://codereview.stackexchange.com/q/157394/84718). Maybe the approach using a `set` can help speed it up a little." } ]
[ { "body": "<p>In programming challenges, proper performances improvement usually come from a smarter algorithm. Unfortunately, I have no algorithm better than the one you have implemented.</p>\n\n<p>I have found a single trick to shave off some time.</p>\n\n<p><strong>Remove all the logic around <code>seen</code></strong></p>\n\n<p>In all places where you access elements from <code>grid</code> and <code>seen</code>, we have basically: <code>if grid[pos] and not seen[pos]</code>.</p>\n\n<p>An idea could be to update <code>grid</code> in place to remove seen elements from it. From an engineering point of view, it is not very nice: I would not expect an function computing the size of the biggest connected components to update the provided input. For a programming challenge, we can probably accept such a thing...</p>\n\n<p>We'd get:</p>\n\n<pre><code>def largest_connected_component(nrows, ncols, grid):\n \"\"\"Find largest connected component of 1s on a grid.\"\"\"\n\n def traverse_component(i, j):\n \"\"\"Returns no. of unseen elements connected to (i,j).\"\"\"\n grid[i][j] = False\n result = 1\n\n # Check all four neighbours\n if i &gt; 0 and grid[i-1][j]:\n result += traverse_component(i-1, j)\n if j &gt; 0 and grid[i][j-1]:\n result += traverse_component(i, j-1)\n if i &lt; len(grid)-1 and grid[i+1][j]:\n result += traverse_component(i+1, j)\n if j &lt; len(grid[0])-1 and grid[i][j+1]:\n result += traverse_component(i, j+1)\n return result\n\n # Tracks size of largest connected component found\n component_size = 0\n\n for i in range(nrows):\n for j in range(ncols):\n if grid[i][j]:\n temp = traverse_component(i, j)\n if temp &gt; component_size:\n component_size = temp\n\n return component_size\n</code></pre>\n\n<hr>\n\n<p>Another idea in order to do the same type of things without changing <code>grid</code> could be to store \"positive\" elements in a set. This also remove the need to check for edge cases of the grid. The great thing is that we can populate that set with less array accesses. This is still pretty hackish:</p>\n\n<pre><code>def largest_connected_component(nrows, ncols, grid):\n \"\"\"Find largest connected component of 1s on a grid.\"\"\"\n\n def traverse_component(pos):\n \"\"\"Returns no. of unseen elements connected to (i,j).\"\"\"\n elements.remove(pos)\n i, j = pos\n result = 1\n\n # Check all four neighbours\n for new_pos in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:\n if new_pos in elements:\n result += traverse_component(new_pos)\n return result\n\n # Tracks size of largest connected component found\n elements = set()\n\n for i, line in enumerate(grid):\n for j, cell in enumerate(line):\n if cell:\n elements.add((i, j))\n\n return max(traverse_component(pos) for pos in set(elements) if pos in elements)\n</code></pre>\n\n<p><strong>Edit</strong>: rewriting the solution to avoid the copy of <code>elements</code>, we have a slightly faster solution:</p>\n\n<pre><code>def largest_connected_component(nrows, ncols, grid):\n \"\"\"Find largest connected component of 1s on a grid.\"\"\"\n\n def traverse_component(pos):\n \"\"\"Returns no. of unseen elements connected to (i,j).\"\"\"\n i, j = pos\n result = 1\n\n # Check all four neighbours\n for new_pos in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:\n if new_pos in elements:\n elements.remove(new_pos)\n result += traverse_component(new_pos)\n return result\n\n # Tracks size of largest connected component found\n elements = set((i, j) for i, line in enumerate(grid) for j, cell in enumerate(line) if cell)\n largest = 0\n while elements:\n pos = elements.pop()\n largest = max(largest, traverse_component(pos))\n return largest\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:11:26.253", "Id": "407217", "Score": "0", "body": "Clever! Regarding the thought about a smarter algorithm, I think there may be a smarter algorithm for the overall program, given that this is only one part of a larger program. Speaking of which, you should also note that the list will need to be copied when passed to the function if the list is going to be used later, because of the way lists references work in Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:50:27.410", "Id": "407221", "Score": "1", "body": "@Graham yes, that's the whole issue with updating the structure in place. I tried to add a call to copy.deepcopy but we (obviously) lose all the benefits we had from not defining a seen matrix. Also I've updated my answer to add a quick alternative but I didn't get a chance to perform full benchmarks before I left my computer. We'll see next year! Have a good evening!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T21:49:25.683", "Id": "407252", "Score": "2", "body": "I can assure you, given the rest of my code, that none of the mutable variables here are used again, so they can be sacrificed in place if needed!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T23:44:09.690", "Id": "407257", "Score": "1", "body": "@Josay Is there a particular reason you import `itertools` in the last code snippet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T11:27:40.350", "Id": "407286", "Score": "0", "body": "@XYZT just a leftover from things I tried. I've edited my code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:00:42.307", "Id": "210645", "ParentId": "210641", "Score": "6" } }, { "body": "<p>Are you absolutely sure this is the bottleneck? Looking at the linked problem and the <a href=\"https://codejam.withgoogle.com/2018/challenges/0000000000007706/analysis/00000000000459f4\" rel=\"nofollow noreferrer\">solution analysis</a>, I'm not sure if this component is even needed to solve the given problem. It's possible your overall algorithm is inefficient in some way, but obviously I couldn't really tell unless I saw the whole program that this is part of.</p>\n\n<p>@Josay's already given a <a href=\"https://codereview.stackexchange.com/a/210645/140921\">good improvement</a>, but in the grand scheme of things, this doesn't really shave off that much measurable time for larger grids. The original solution was a pretty good algorithm for solving the problem of largest connected subsections.</p>\n\n<h2>General comments</h2>\n\n<p>Having three lines here is unnecessary:</p>\n\n<pre><code>temp = traverse_component(i, j)\nif temp &gt; component_size:\n component_size = temp\n</code></pre>\n\n<p>because of one nice Python built-in, <code>max</code>:</p>\n\n<pre><code>component_size = max(component_size, traverse_component(i,j))\n</code></pre>\n\n<hr>\n\n<p><code>component_size</code> could be named more descriptively as <code>largest_size</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T21:36:23.513", "Id": "407251", "Score": "0", "body": "The analysis for the problem says, \"For each quadrant center and combination of colors, we want to get the largest connected component where each cell in this connected component has the same color as the color assigned to the quadrant it belongs to.\" Is this not what I am trying to do? Or did I misunderstand?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T22:02:39.953", "Id": "407255", "Score": "0", "body": "@XYZT How do you connect the four quadrants to measure the overall component size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T23:08:40.100", "Id": "407256", "Score": "0", "body": "I hope it's appropriate to link my whole code here: https://gist.github.com/theXYZT/f13ac490e842552a2f470afac1001b7b" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T10:03:24.833", "Id": "407283", "Score": "2", "body": "@XYZT: For that it would probably be better to ask a new question with the whole code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:49:14.510", "Id": "210649", "ParentId": "210641", "Score": "2" } }, { "body": "<p>As an alternative, I will suggest a solution that instead of iterating through all of the grid's nodes in search of a component that was not visited in the main loop, it avoids visiting a visited node in this loop via a modified BFS.</p>\n\n<p>The gist of this algorithm is to perform an explorative BFS, which triggers a DFS (like your algorithm) to measure the size of the group.</p>\n\n<p>Difference being that during the DFS step, it adds empty (non-visited) slots to the BFS queue, thus avoiding the need to re-check the component group.</p>\n\n<p>The time complexity for this algorithm is O(nm), but it comes at an added space complexity cost of O(nm), due to the BFS queue growth on the regular BFS algorithm and the added DFS items</p>\n\n<pre><code>from collections import deque\n\nEMPTY = 0\nFILLED = 1\nVISITED = 2\n\n\ndef largest_connected_component(grid):\n\n def is_valid(x, y):\n return (0 &lt;= x &lt; len(grid) and 0 &lt;= y &lt; len(grid[0]) and\n grid[x][y] != VISITED)\n\n def traverse_component(x, y):\n grid[x][y] = VISITED\n result = 1\n for adjacent in ((x + 1, y),\n (x - 1, y),\n (x, y + 1),\n (x, y - 1)):\n if (is_valid(*adjacent)):\n if (grid[adjacent[0]][adjacent[1]] == EMPTY):\n q.append(adjacent)\n grid[adjacent[0]][adjacent[1]] = VISITED\n else:\n result += traverse_component(*adjacent)\n\n return result\n\n max_filled_size = 0\n q = deque()\n\n if (grid[0][0] == EMPTY):\n q.append((0, 0))\n grid[0][0] = VISITED\n else:\n max_filled_size = max(max_filled_size, traverse_component(0, 0))\n\n while q:\n x, y = q.popleft()\n\n for adjacent in ((x + 1, y),\n (x - 1, y),\n (x, y + 1),\n (x, y - 1)):\n if (is_valid(*adjacent)):\n if (grid[adjacent[0]][adjacent[1]] == EMPTY):\n q.append(adjacent)\n grid[adjacent[0]][adjacent[1]] = VISITED\n else: # FILLED\n max_filled_size = max(max_filled_size, traverse_component(*adjacent))\n\n return max_filled_size\n\n# Examples\nprint(largest_connected_component([[0, 1, 0], [1, 0, 1], [0, 1, 1]]))\nprint(largest_connected_component([[1, 1, 1], [0, 1, 0], [1, 0, 1]]))\nprint(largest_connected_component([[1, 0, 0, 1, 1, 1, 1, 0],\n [1, 0, 1, 0, 0, 0, 0, 1],\n [1, 0, 1, 0, 0, 1, 0, 1],\n [1, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 1, 1, 1, 0],\n [1, 0, 1, 1, 0, 0, 1, 0],\n ]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:54:26.170", "Id": "220860", "ParentId": "210641", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T14:54:17.873", "Id": "210641", "Score": "7", "Tags": [ "python", "performance", "algorithm", "python-3.x", "programming-challenge" ], "Title": "Size of the largest connected component in a grid in Python" }
210641
<p>I have implemented a DialogueBox class which can be static, singleton, service locator, etc. I have written it as a singleton pattern and implemented it in Unity3d engine. It is a part of a game. I have ShowDialogueBox method with many parameters. How can I handle it? The parameters are message, ok button label, cancel button label, has the cancel button or not, actions to be invoked when users click on ok or cancel button.</p> <p>Is it more suitable to apply Builder pattern for it?</p> <p>Because the method is not sometimes flexible and I have to provide all parameters.</p> <p>In addition, my messages are not static and sometimes I need to display a message with parameters like cost value, etc. Therefore, I should add another parameter like params to the method or create the message with params before calling the method? Also, It is appropriate to pull out Localizer from DialogueBox class?</p> <pre><code>//DialogueBox.GetInstance().ShowDialogueBox("BuyMessage",()=&gt;{}, // ()=&gt;{}, "Buy", "Cancel",true) using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DialogueBox : MonoBehaviour { [SerializeField] private Text _cancelButtonText; [SerializeField] private Text _okButtonText; [SerializeField] private GameObject _cancelButtonObj; [SerializeField] private GameObject _okButtonObj; [SerializeField] private Text _messageText; [SerializeField] private GameObject _dialogueBoxObj; //DialogueBox GameObject(Panel) private static DialogueBox _instance; private Action OKButtonPressedAction = delegate { }; private Action CancelButtonPressedAction = delegate { }; public static DialogueBox GetInstance() { return _instance; } private void Awake() { if (_instance == null) { _instance = this; } else { Destroy(gameObject); } } public void ShowDialogueBox(string messageKey, Action okButtonPressed, Action cancelButtonPressed = null, string okKey = "OK", string cancelKey = "Cancel", bool hasCancelButton = true) { //Localizer manages languages with key/message pair for example: //Localizer.GetInstance().Dictionary[key]---&gt; returns message for the current language _messageText.text = Localizer.GetInstance().Dictionary[messageKey]; _okButtonText.text = Localizer.GetInstance().Dictionary[okKey]; if (hasCancelButton) { _cancelButtonObj.SetActive(true); //Show the cancel button _cancelButtonText.text = Localizer.GetInstance().Dictionary[cancelKey]; } else _cancelButtonObj.SetActive(false); OKButtonPressedAction = okButtonPressed; CancelButtonPressedAction = cancelButtonPressed; } public void OnOKButtonPressed() //It is called when a user clicks on OK button { _dialogueBoxObj.SetActive(false); if( OKButtonPressedAction!=null) OKButtonPressedAction(); } public void OnCancelButtonPressed() //It is called when a user clicks on OK button { _dialogueBoxObj.SetActive(false); if(CancelButtonPressedAction!=null) CancelButtonPressedAction(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T21:25:03.720", "Id": "407249", "Score": "0", "body": "Where is `gameObject` coming from and where is `Destroy()` coming from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T22:01:22.133", "Id": "407254", "Score": "0", "body": "MonoBehaviour. It is a built in field referred to the game object owning the script.\nIt is related to Unity game engine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:18:47.220", "Id": "407262", "Score": "0", "body": "Is there a reason the existing `MessageBox` in the .net library won't work for you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T17:37:34.820", "Id": "407318", "Score": "0", "body": "I said it is a game with custom UI and art. It is not a win app" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:25:44.360", "Id": "407330", "Score": "1", "body": "This code looks incomplete. You are not creating the `DialogueBox` anywhere..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T21:38:06.247", "Id": "407338", "Score": "1", "body": "@ t3chb0t. I said, it is related to unity3d. Have you ever worked with unity3d?\nIn unity, you do not call constructors when objects inherit from monobehaviour. You can create it in the editor(like my way) or in the script(Instantiate).\nThe code is complete and clear. I do not know where it is unclear.\nI have different parameters for Show method that can be default or not. I finally used builder design pattern to handle it. Why -1?! I selected unity3d tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T21:46:19.727", "Id": "407339", "Score": "1", "body": "I see that all ask about monobehaviours. Like that I ask about where TcpClient is.\nIf you are a unity developer, you know about monobeaviour, destroy and other parts of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T07:06:20.133", "Id": "407361", "Score": "0", "body": "So, you're saying that mono is magically initializing this field: `private static DialogueBox _instance;`? If this is really the case then I'm ignoring this tag in future because this seems to be one of the stupidest frameworks I've ever seen. Nothing works here as expected. No properties, public fields... no constructor... oh boy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:35:47.747", "Id": "407392", "Score": "0", "body": "@t3chb0t: `_instance` is set in `Awake`, which is a special method in Unity3D." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T18:48:23.877", "Id": "407417", "Score": "0", "body": "@t3chb0t: It is not magical. It is about unity game engine! It creates gameobjects and calls constructors internally. Also, you can create gameobjects in scripts with Instantiate() method. You access to some specific methods like Awake, Start, OnEnable,Update, etc. fired in specific situations like when a gameobject is activated or deactivated or in every frame.\nIt is not a framework. It is a game engine. My question was not about creating and instantiating at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T19:31:12.563", "Id": "407422", "Score": "0", "body": "I understand and I've retracted both my DV and VTC. I also won't comment on [tag:unity3d] anymore. Sorry, my bad - I don't want to see this monstrosity ever again so I'll just ignore this tag in future ;-]" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T15:46:22.740", "Id": "210644", "Score": "2", "Tags": [ "c#", "singleton", "unity3d", "user-interface" ], "Title": "Generic DialogueBox class with different parameters" }
210644
<p>There are some exercises about islands and water. I have seen other solutions in Java, but they are developed in procedural style in one-two methods. I tried to develop an object-oriented solution with code reuse. I have never got code reviews before, so I would happy to see <strong>any</strong> suggestions to improve my code.</p> <hr> <h2>Exercise 1.</h2> <blockquote> <p>There is a beach with a ground configuration like</p> <pre><code>[ 1, 2, 3, 2, 3, 4, 5, 1, 4, 6, 7, 6, 7, 2, 3, 1 ] </code></pre> <p>A wave come from a sea to the left of the beach. Its height is 5, for example. Then the wave come back to the sea. In the beach's hollows we find trapped water. If the wave is higher than beach it covers the full beach and goes away to both directions.</p> <p>Task: write a program for counting all trapped water on the whole beach.</p> </blockquote> <hr> <h2>Exercise 2.</h2> <blockquote> <p>There is an island with a ground configuration like</p> <pre><code> [ [ 5, 3, 4, 5 ], [ 6, 2, 1, 4 ], [ 3, 1, 1, 4 ], [ 8, 5, 4, 3 ] ] </code></pre> <p>A rain was many days. It filled by water every hollow in the island. Water can go away only to 4 directions: north, south, west, east.</p> <p>Task: write a program for counting all trapped water in whole island. For example, the answer for a given configuration is 7.</p> </blockquote> <hr> <p>At first, I developed the common class for a single column of land with water on it:</p> <pre><code>package trappedwater; import java.util.Arrays; public class LithosphereSection { /* Height is above mean sea level in each case */ public final int groundHeight; private int waterHeight; public LithosphereSection(int _groundHeight) { this.groundHeight = _groundHeight; this.waterHeight = 0; } public void setWaterHeight(int _waterHeight) { this.waterHeight = _waterHeight; } public void extraWaterPourOff(LithosphereSection... neighborSections) { if (hasPrecipiceForWater(neighborSections)) { this.waterHeight = 0; } else { for (LithosphereSection neighbor : neighborSections) { int support = Integer.max(neighbor.waterHeight, neighbor.groundHeight); this.waterHeight = Integer.min(this.waterHeight, support); } } } private boolean hasPrecipiceForWater(LithosphereSection... neighborSections) { return neighborSections == null || neighborSections.length == 0 || Arrays.asList(neighborSections).contains(null); } public int getTrappedWater() { int trappedWater = this.waterHeight - this.groundHeight; return (trappedWater &gt; 0) ? trappedWater : 0; } } </code></pre> <hr> <p>Then I solved the first exercise.</p> <pre><code>package trappedwater; public class Beach { private final LithosphereSection[] litSections; private final int m; // alias to litSections.length public Beach(int[] _groundScheme) { this.m = _groundScheme.length; this.litSections = new LithosphereSection[this.m]; for (int i = 0; i &lt; this.m; i++) { this.litSections[i] = new LithosphereSection(_groundScheme[i]); } } public void takeWaveFromLeft(int _waveHeight) { boolean waveStillMoves = true; for (int i = 0; i &lt; this.m; i++) { if (waveStillMoves) { if (_waveHeight &gt; this.litSections[i].groundHeight) { this.litSections[i].setWaterHeight(_waveHeight); } else { waveStillMoves = false; } } } } public void extraWaterPourOff() { // Pour water on boarders this.litSections[0].extraWaterPourOff(); this.litSections[this.m - 1].extraWaterPourOff(); // Pour water to the left for (int i = 1; i &lt; this.m - 1; i++) { this.litSections[i].extraWaterPourOff(this.litSections[i - 1]); } // Pour water to the right for (int i = this.m - 2; i &gt; 0; i--) { this.litSections[i].extraWaterPourOff(this.litSections[i + 1]); } } public int getTrappedWater() { int sumWater = 0; for (LithosphereSection litSection : this.litSections) { sumWater += litSection.getTrappedWater(); } return sumWater; } public void dry() { for (int i = 0; i &lt; this.m; i++) { this.litSections[i].setWaterHeight(0); } } } </code></pre> <hr> <p>And the second one</p> <pre><code>package trappedwater; public class Island { private final LithosphereSection[][] litSections; private final int n; // rows private final int m; // columns private int highestGround; public Island(int[][] _groundScheme) { this.n = _groundScheme.length; this.m = _groundScheme[0].length; this.litSections = new LithosphereSection[this.n][this.m]; this.highestGround = _groundScheme[0][0]; for (int i = 0; i &lt; this.n; i++) { for (int j = 0; j &lt; this.m; j++) { this.litSections[i][j] = new LithosphereSection(_groundScheme[i][j]); this.highestGround = Integer.max(this.highestGround, _groundScheme[i][j]); } } } public void overfillByWater() { for (int i = 0; i &lt; this.n; i++) { for (int j = 0; j &lt; this.m; j++) { this.litSections[i][j].setWaterHeight(this.highestGround); } } } public void extraWaterPourOff() { pourOffBoarders(); boolean countOfPuddlesChanges = true; while (countOfPuddlesChanges) { int countOfPuddlesBefore = getTrappedWater(); pourOffToNorthLeft(); pourOffToSouthRight(); countOfPuddlesChanges = (getTrappedWater() != countOfPuddlesBefore); } } private void pourOffBoarders() { for (int i = 0; i &lt; this.n; i++) { for (int j = 0; j &lt; this.m; j++) { boolean isBorder = (i == 0) || (i == this.n - 1) || (j == 0) || (j == this.m - 1); if (isBorder) { this.litSections[i][j].extraWaterPourOff(); } } } } private void pourOffToNorthLeft() { for (int i = 1; i &lt; this.n - 1; i++) { for (int j = 1; j &lt; this.m - 1; j++) { this.litSections[i][j].extraWaterPourOff( this.litSections[i][j - 1], this.litSections[i - 1][j] ); } } } private void pourOffToSouthRight() { for (int i = this.n - 2; i &gt; 0; i--) { for (int j = this.m - 2; j &gt; 0; j--) { this.litSections[i][j].extraWaterPourOff( this.litSections[i][j + 1], this.litSections[i + 1][j] ); } } } public int getTrappedWater() { int sumWater = 0; for (int i = 0; i &lt; this.n; i++) { for (int j = 0; j &lt; this.m; j++) { sumWater += this.litSections[i][j].getTrappedWater(); } } return sumWater; } } </code></pre> <hr> <p>Finally I made 3 classes with JUnit5 tests:</p> <pre><code>package trappedwater; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class LithosphereSectionTest { static LithosphereSection testLitSection; @BeforeAll static void setUpBeforeClass() throws Exception { testLitSection = new LithosphereSection(5); } @BeforeEach void setUp() throws Exception { testLitSection.setWaterHeight(10); } @Test void test01() { assertEquals(5, testLitSection.getTrappedWater()); } @Test void test02() { LithosphereSection litSection2 = new LithosphereSection(7); LithosphereSection litSection3 = new LithosphereSection(8); LithosphereSection litSection4 = new LithosphereSection(6); litSection4.setWaterHeight(7); testLitSection.extraWaterPourOff(litSection2, litSection3, litSection4); assertEquals(2, testLitSection.getTrappedWater()); } @Test void test03() { testLitSection.extraWaterPourOff(); assertEquals(0, testLitSection.getTrappedWater()); } @Test void test04() { LithosphereSection[] sections = null; testLitSection.extraWaterPourOff(sections); assertEquals(0, testLitSection.getTrappedWater()); } @Test void test05() { LithosphereSection litSection2 = null; testLitSection.extraWaterPourOff(litSection2); assertEquals(0, testLitSection.getTrappedWater()); } } </code></pre> <hr> <pre><code>package trappedwater; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class BeachTest { static Beach beach; @BeforeAll static void setUpBeforeClass() throws Exception { int[] groundScheme = new int[] { 1, 2, 3, 2, 3, 4, 5, 1, 4, 6, 7, 6, 7, 2, 3, 1 }; beach = new Beach(groundScheme); } private int run(int waveHeight) { beach.dry(); beach.takeWaveFromLeft(waveHeight); beach.extraWaterPourOff(); return beach.getTrappedWater(); } @Test void test() { assertEquals(0, run(1)); assertEquals(0, run(2)); assertEquals(0, run(3)); assertEquals(1, run(4)); assertEquals(1, run(5)); assertEquals(6, run(6)); assertEquals(6, run(7)); assertEquals(8, run(8)); assertEquals(8, run(9)); } } </code></pre> <hr> <pre><code>package trappedwater; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class IslandTest { private int run(int[][] _groundScheme) { Island island = new Island(_groundScheme); island.overfillByWater(); island.extraWaterPourOff(); return island.getTrappedWater(); } @Test void test01() { int[][] groundScheme = new int[][] { { 5, 3, 4, 5 }, { 6, 2, 1, 4 }, { 3, 1, 1, 4 }, { 8, 5, 4, 3 } }; assertEquals(7, run(groundScheme)); } @Test void test02() { int[][] groundScheme = new int[][] { { 8, 6, 8, 8 }, { 8, 2, 2, 4 }, { 8, 2, 2, 8 }, { 8, 8, 8, 8 } }; assertEquals(8, run(groundScheme)); } } </code></pre> <h1>Edited</h1> <p>These are 2 different challenges. Someone can offer to make 2 different questions. But I think I found a universal solution for family of problems. The challenges seems to be different, but solutions are identical for me. For example, here is a new challenge. </p> <hr> <blockquote> <p>We have an island:</p> <pre><code>[ [ 3, 3, 4, 5, 2 ], [ 6, 2, 1, 4, 4 ], [ 3, 1, 7, 4, 6 ], [ 4, 5, 4, 3, 2 ], [ 2, 3, 5, 2, 3 ] ] </code></pre> <p>Winter was cold. The island is covered by snow layers:</p> <pre><code>[ [ 0, 0, 0, 0, 0 ], [ 0, 1, 2, 0, 0 ], [ 0, 1, 4, 0, 0 ], [ 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0 ] ] </code></pre> <p>Summer come. Will melt water reach the ocean?</p> </blockquote> <hr> <p>I would not change class LithosphereSection to solve this new challenge.</p> <p>Or, we have a hexagonically divided map of island. Each lithosphere section can have up to 6 neighbors in this challenge. I would not change class LithosphereSection. LithosphereSection can have any amount of neighbors: 2 for 2D challenge, 4 for 3D quadratic challenge, 6 for 3D hexagonic challenge, 8 for 3D quadratic challenge with additional diagonal directions for water pouring. So, I think class LithosphereSection solves a family of similar problems, I wanted to show this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:03:37.547", "Id": "407222", "Score": "0", "body": "Tests help reviewers tremendously when reviewing your code. If you have them you should definitely provide them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-08T07:09:14.410", "Id": "443317", "Score": "0", "body": "These are 2 different challenges. Perhaps it would have been better to have asked 2 separate questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-09T19:59:23.540", "Id": "443488", "Score": "1", "body": "@dfhwze, I've answered to you in footer of the question. It's just my own opinion, you may be right." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:21:55.183", "Id": "210647", "Score": "3", "Tags": [ "java", "programming-challenge" ], "Title": "Solutions for counting trapped water on islands" }
210647
<p>Here is my improved version of my Magic square program from <a href="https://codereview.stackexchange.com/q/209272/120114">following this earlier version</a>. I also added a few comments.</p> <p>Any help for improvements would be really appreciated.</p> <pre><code>import java.util.HashSet; import java.util.Scanner; public class MagicSquare { private int[] square; private int[] row_sum; private int[] col_sum; private int magicNumber; private int size; private boolean[] usedNumbers; private int solutions=0; private int squareSize; public MagicSquare(int size) { this.size = size; this.usedNumbers = new boolean[size * size + 1]; this.square = new int[size * size]; this.row_sum = new int[size]; this.col_sum = new int[size]; this.magicNumber = ((size * size * size + size) / 2); this.squareSize = size * size; } private boolean solve(int x) { if (x == squareSize &amp;&amp; checkDiagonals()) { for (int i = 0; i &lt; size; i++) { if (row_sum[i] != magicNumber || col_sum[i] != magicNumber) { return false; // no solution, backtrack } } solutions++; System.out.println("Solution: "+solutions); printSquare(); return false; // serach for next solution } // the 1d square is mapped to 2d square HashSet&lt;Integer&gt; validNumbers = new HashSet&lt;Integer&gt;(); // all valid Numbers from one position if(x%size == size-1 &amp;&amp; magicNumber-row_sum[(x/size)] &lt;= squareSize &amp;&amp; usedNumbers[magicNumber-row_sum[x/size]] == false) { validNumbers.add(magicNumber-row_sum[(x/size)]); // All values ​​in a row, except for the last one were set } if(x/size == size-1 &amp;&amp; magicNumber-col_sum[(x%size)] &lt;= squareSize &amp;&amp; // usedNumbers[magicNumber-col_sum[x%size]] == false) { validNumbers.add(magicNumber-col_sum[x%size]); // // All values ​​in a col, except for the last one were set } if(x%size != size-1 &amp;&amp; x/size != size-1) { // for all other positions for(int i=1; i&lt;usedNumbers.length; i++) { if (usedNumbers[i]== false) validNumbers.add(i); } } if(validNumbers.size()==0) { return false; // no valid numbers, backtrack } for (int v : validNumbers) { row_sum[x/size] += v; col_sum[x%size] += v; if (row_sum[x/size] &lt;= magicNumber &amp;&amp; col_sum[x%size] &lt;= magicNumber) { square[x] = v; usedNumbers[v] = true; if (solve(x + 1) == true) { return true; } usedNumbers[v] = false; square[x] = 0; } row_sum[x/size] -= v; col_sum[x%size] -= v; } return false; } private boolean checkDiagonals() { int diagonal1 = 0; int diagonal2 = 0; for(int i=0; i&lt;squareSize; i=i+size+1) { diagonal1 = diagonal1 + square[i]; } for(int i=size-1; i&lt;squareSize-size+1; i = i+size-1) { diagonal2 = diagonal2 + square[i]; } return diagonal1==magicNumber &amp;&amp; diagonal2==magicNumber; } private void printSquare() { for (int i = 0; i &lt; squareSize; i++) { if(i%size ==0) { System.out.println(); } System.out.print(square[i] + " "); } System.out.println(); } public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int size = sc.nextInt(); MagicSquare m = new MagicSquare(size); sc.close(); long start = System.currentTimeMillis(); m.solve(0); long duration = System.currentTimeMillis() - start; System.out.println("Runtime in ms : " + duration+" = "+duration/1000 + "sec"); System.out.println("There are "+m.solutions+" solutions with mirroring"); } catch (Exception ex) { ex.printStackTrace(); } } } </code></pre>
[]
[ { "body": "<p>It looks like you have incorporated much of the feedback from <a href=\"https://codereview.stackexchange.com/a/209298/120114\">AJNeufeld's answer to your previous question</a> and the code looks better. The indentation is a little inconsistent though - for example, some lines are indented with two spaces, some four (or one tab), and then in some spots eight spaces/two tabs (e.g. the 10th line of <code>solve()</code>). Make the indentation consistent for the sake of anyone reading your code (including yourself in the future).</p>\n\n<p>I <a href=\"https://onlinegdb.com/B189w0wWN\" rel=\"nofollow noreferrer\">tried running the code on on onlinegdb.com</a>. In order to run the code there, I had to put the class definition for <code>MagicSquare</code> in a separate file (i.e. <code>MagicSquare.java</code>). Then in the <code>main</code> method, the code calls the <code>solve</code> method, which is a private method, like all methods except for the constructor. In order for a non-abstract class to be useful, usually it will need to have at least one method other than the constructor. The same is true for the member/instance variable/property <code>solutions</code> - it is referenced from the <code>main</code> method. </p>\n\n<p>Perhaps you are simply running the code in a single file but in larger projects you will likely need to use multiple files.</p>\n\n<hr>\n\n<p>The following block can be simplified:</p>\n\n<blockquote>\n<pre><code>for(int i=0; i&lt;squareSize; i=i+size+1) {\n diagonal1 = diagonal1 + square[i];\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of assigning the value to <code>diagonal1 + square[i]</code>, use the compound operator <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html#PageContent\" rel=\"nofollow noreferrer\"><code>+=</code></a> <sub>(just as it was used in the last <code>for</code> loop of the <code>solve()</code> method for <code>row_sum</code> and <code>col_sum</code>)</sub>:</p>\n\n<pre><code>for(int i=0; i&lt;squareSize; i+=size+1) {\n diagonal1 += square[i];\n}\n</code></pre>\n\n<p>The same is true for the <code>for</code> loop after that to add to <code>diagonal2</code>.</p>\n\n<hr>\n\n<p>One last comment about the UI: <a href=\"https://codereview.stackexchange.com/q/209272/120114\">Your original post</a> doesn't appear to contain any formal requirements but it might be wise to print explanatory text to prompt the user to enter the number to be used for the magic number.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:56:32.180", "Id": "210658", "ParentId": "210648", "Score": "4" } }, { "body": "<h2>Don't repeat yourself</h2>\n\n<p>You use <code>x/size</code> and <code>x%size</code> a lot. You can easily assign them to local variables, and your code becomes much better readable. <code>x</code> is not the best name for an index, consider using <code>i</code>.</p>\n\n<pre><code> int x = i % size;\n int y = i / size;\n\n if(x == size-1 &amp;&amp; magicNumber-row_sum[y] &lt;= squareSize &amp;&amp; \n usedNumbers[magicNumber - row_sum[y]] == false) { \n validNumbers.add(magicNumber - row_sum[y]); // All values ​​in a row, except for the last one were set\n }\n\n if(y == size-1 &amp;&amp; magicNumber - col_sum[x] &lt;= squareSize &amp;&amp; // \n usedNumbers[magicNumber - col_sum[x]] == false) { \n validNumbers.add(magicNumber - col_sum[x]); // // All values ​​in a col, except for the last one were set \n }\n\n ....\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T12:41:36.187", "Id": "210865", "ParentId": "210648", "Score": "5" } }, { "body": "<p>You aren’t using <code>try-with-resources</code>, so you are having to A) manually close the <code>Scanner</code> yourself, and B) catch an exception just to print the stack-trace, which would happen automatically if you didn’t explicitly catch any exceptions. Additionally, you aren’t closing the scanner if an exception happens before you manually close the scanner, since execution directly jumps to your <code>catch</code> statement. You’d need a <code>finally</code> clause to close the scanner no matter how the <code>try</code> block is exited, and then you’d have to be worried about a possible exception in the <code>finally</code> clause, but all this is exactly what <code>try-with-resources</code> is designed for.</p>\n\n<p>You should write your main function like:</p>\n\n<pre><code>public static void main(String[] args) throws Exception {\n try (Scanner sc = new Scanner(System.in)) {\n int size = sc.nextInt();\n MagicSquare m = new MagicSquare(size);\n m.solve(0);\n }\n}\n</code></pre>\n\n<p>Note you don’t need to call <code>sc.close()</code>, nor do you need a <code>catch ()</code> clause. Of course, you should add your timing and print statements to the above; they were omitted for brevity.</p>\n\n<hr>\n\n<h2>Algorithm</h2>\n\n<p>You’re original code tried 16 different values for the first cell, then 15 for the next cell, 14 for the next, 13 for the next, and so on, down to the last cell where one number remained. This gave <code>16!</code> possible squares to check for “magicness”.</p>\n\n<p>This new algorithm tries 16 different values for the first cell, 15 for the second, 14 for the third, and computes the value for the fourth cell. On the next row, it repeats this with 12 values for the fifth cell, 11 for the next, 10 for the next, and computes the value for the eighth cell. Ditto for the 3rd row, and finally the last row is computed. This gives:</p>\n\n<pre><code>16*15*14 * 12*11*10 * 8*7*6 = 1,490,227,200 possible squares\n</code></pre>\n\n<p>which is an improvement of 14,040 times over <code>16!</code> possible squares. We can further improve this. After exploring the row 0 solution space, instead of exploring the row 1 solution space (where you again have 4 unknowns and must pick 3 values and compute the fourth), explore the column 0 solution space. Here, we already have 1 known value (from row 0), so only need to explore 3 unknowns by picking 2 and computing the 3rd. After that, you continue with row 1, followed by column 1, then row 2 and column 2, and so on alternating between rows and columns. In the case of a 4x4 magic square, these are the number of possibilities you end up with each cell (<code>1</code> cells being directly computed):</p>\n\n<pre><code>16 15 14 1\n12 9 8 1\n11 6 4 1\n 1 1 1 1\n</code></pre>\n\n<p>Total possibilities = <code>16*15*14 * 12*11 * 9*8 * 6 * 4 = 766,402,560</code> which is half as many possibilities, so can run in approximately half the time!</p>\n\n<p>We can do even better, at the expense of determining a more complicated exploration path. After exploring row 0 and column 0, you have 2 knowns on one of the diagonals. This means if you can explore the diagonal next, with only 2 remaining unknowns, by picking 1 value for one diagonal cell (say, row 2, col 1), and computing the other (row 1, col 2). Then continue exploration of the rows and columns, alternating between rows and columns as you go. The 4x4 magic square exploration possibility space becomes:</p>\n\n<pre><code>16 15 14 1\n12 7 1 1\n11 9 4 1\n 1 1 1 1\n</code></pre>\n\n<p>Total possibilities = <code>16*15*14 * 12*11 * 9 * 7 * 4 = 111,767,040</code>, which is approximately 1/13th of your current solution’s exploration space, and so could run in just 8% of your current time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T00:02:52.743", "Id": "211400", "ParentId": "210648", "Score": "2" } } ]
{ "AcceptedAnswerId": "210865", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T16:36:37.843", "Id": "210648", "Score": "4", "Tags": [ "java", "performance", "recursion", "iteration", "backtracking" ], "Title": "Java Magic square program" }
210648
<p>I'm somewhat new to python and wrote this piece of code to do a string comparison of accounts that are being requested for import into our data base against accounts that are already present. The issue is that the accounts currently in our DB is over 65K and I'm comparing over 5K accounts for import causing this code to take over 5 hours to run. I suspect this has to do with the loop I'm using but I'm not certain how to improve it.</p> <p>TLDR; I need help optimizing this code so it has a shorter run time. </p> <pre><code>from fuzzywuzzy import fuzz from fuzzywuzzy import process accounts_DB = pd.read_csv("file.csv") #65,000 rows and 15 columns accounts_SF = pd.read_csv("Requested Import.csv") #5,000 rows and 30 columns def NameComparison(DB_account, choices): """Function uses fuzzywuzzy module to perform Levenshtein distance string comparison""" return(process.extractBests(DB_account, choices, score_cutoff= 95)) options = accounts_sf["Account Name"] a_list = [] for i in range(len(accounts_db)): a_list.append(NameComparison(accounts_db.at[i,"Company Name"], options)) b_list = pd.DataFrame(a_list) b_list.to_csv("Matched Accounts.csv") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:24:53.467", "Id": "407230", "Score": "0", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T19:26:05.863", "Id": "407234", "Score": "1", "body": "Thank you, I've gone ahead and adjusted my title. My codes main goal is to compare two strings using fuzzy string comparison" } ]
[ { "body": "<p>To apply the same function to each row of a dataframe column, you usually use <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html\" rel=\"nofollow noreferrer\"><code>pd.Series.map</code></a> or <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html\" rel=\"nofollow noreferrer\"><code>pd.Series.apply</code></a>. You can thus simplify your code to:</p>\n\n<pre><code>from functools import partial\nfrom fuzzywuzzy import process\n\n\naccounts_DB = pd.read_csv(\"file.csv\") #65,000 rows and 15 columns\naccounts_SF = pd.read_csv(\"Requested Import.csv\") #5,000 rows and 30 columns\n\nbest_matches = partial(process.extractBests, choices=accounts_SF['Account Name'], score_cutoff=95)\naccounts_DB['Company Name'].map(best_matches).to_csv(\"Matched Accounts.csv\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T22:42:33.147", "Id": "210666", "ParentId": "210651", "Score": "3" } } ]
{ "AcceptedAnswerId": "210666", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T17:05:26.373", "Id": "210651", "Score": "3", "Tags": [ "python", "performance" ], "Title": "Name comparison using fuzzy string matching" }
210651
<p>In a past course one of the assignments was to write a program that can compress files using Huffman Tree algorithm, and uncompress the files that the program generates.</p> <p>My design is to count the byte occurrences first, then construct a HT based on the counted byte frequency.</p> <p>My compressed file format is 256*4 bytes of "header" that stores the counted frequency, so it can be used to construct the tree when decompressing the file. Then there's a 4-byte integer that indicates how many bits of the last byte is real data. The rest is the real (compressed) data.</p> <p>Here is <a href="https://github.com/iBug/CGadgets/blob/a30d0ef0af335335f18d01cceaba6ee5090a1258/Huffman/huffman.c" rel="noreferrer">this specific version</a>* of code that I want some feedback. Later versions introduced many messy changes (like GUI and buffered I/O) that is not necessary.</p> <p>Specifically, I'm looking for feedback on my algorithm and data structure implementation, including but not limited to code style, best practices, potential flaws and defects (see below).</p> <ul> <li>An exception is the last two functions <code>print_help</code> and <code>main</code>. They're intended to be as simple as possible, so they contain the bare minimum amount of code to work in a reasonable way. Data validation and error checking etc. are omitted on purpose.</li> </ul> <p>In order to simplify the idea, during designing and coding, I have assumed that</p> <ul> <li>the program will not be told to uncompress an invalid file, so there's no file validity check in the code</li> <li>file availability is ensured by the environment. It will always be a regular file, with no chance of generating a read error mid-way</li> <li>C library functions does not fail for environmental reasons (e.g. host is short of RAM for <code>malloc(3)</code>, target disk out of space for <code>fwrite(3)</code> and consequently <code>write(2)</code>, or <code>fread(3)</code> as said above)</li> <li>reading/writing byte-by-byte is fine, because <a href="https://github.com/iBug/CGadgets/commit/338fe886b5999618bd33090bc6b804b97f31894b" rel="noreferrer">a later version</a> of this code introduced chunk I/O and got a bit messier (I think). Suggestions on making the code run faster without implementing chunk I/O is welcome</li> </ul> <p>so I'm also not looking for feedbacks regarding the above things that I have assumed / intentionally ignored.</p> <p>I have ensured that the code is working properly, with no warnings when compiled with this command (taken from <code>make</code> output)</p> <pre><code>gcc -O3 -std=c11 -Wall -Wno-unused-result -o huffman huffman.c </code></pre> <p>The last option is to suppress the warning about unused result from <code>fread(3)</code>.</p> <p>During my coding process, I run <code>clang-format</code> occasionally and <code>diff</code> the output and my written code to check for potentially bad indentation / styling issues. I am not confident if it can solve everything.</p> <p>* The link points to my GitHub repo. The code on that page is identical to the code submitted below verbatim.</p> <pre><code>// File: huffman.c // Author: iBug #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdint.h&gt; typedef unsigned char byte; typedef struct _HuffNode { unsigned data; struct _HuffNode *left, *right, *parent; } HuffNode; void count_frequency(FILE* fp, unsigned* freq) { size_t orig_pos = ftell(fp); int ch; while (1) { ch = fgetc(fp); if (ch &lt; 0) break; freq[ch]++; } fseek(fp, orig_pos, SEEK_SET); } void construct_huffman(unsigned* freq_in, HuffNode* tree) { int count = 256; unsigned freq[256]; HuffNode *node[256]; // Initialize data for (int i = 0; i &lt; 256; i++) { freq[i] = freq_in[i]; tree[i].data = i; tree[i].left = tree[i].right = NULL; node[i] = &amp;tree[i]; } // Sort by frequency, decreasing order /* WARNING: Although this Quick Sort is an unstable sort, * it should at least give the same result for the same input frequency table, * therefore I'm leaving this code here */ { unsigned lower[256], upper[256], top = 1; lower[0] = 0, upper[0] = 256; while (top &gt; 0) { top--; int left = lower[top], right = upper[top]; int i = left, j = right - 1, flag = 0; if (i &gt;= j) // Nothing to sort continue; while (i &lt; j) { if (freq[i] &lt; freq[j]) { unsigned t = freq[i]; freq[i] = freq[j]; freq[j] = t; HuffNode *p = node[i]; node[i] = node[j]; node[j] = p; flag = !flag; } flag ? i++ : j--; } lower[top] = left, upper[top] = i; lower[top + 1] = i + 1, upper[top + 1] = right; top += 2; } } // Construct tree while (count &gt; 1) { int pos = 512 - count; HuffNode *parent = &amp;tree[pos]; // Select lowest 2 by freq int i = count - 2, j = count - 1; // Create tree, lower freq left parent-&gt;left = node[j]; parent-&gt;right = node[i]; node[j]-&gt;parent = node[i]-&gt;parent = parent; node[i] = parent; freq[i] += freq[j]; // Insert for (; i &gt; 0 &amp;&amp; freq[i] &gt; freq[i - 1]; i--) { unsigned t = freq[i]; freq[i] = freq[i - 1]; freq[i - 1] = t; HuffNode *p = node[i]; node[i] = node[i - 1]; node[i - 1] = p; } count--; } // Now HEAD = node[0] = tree[511] node[0]-&gt;parent = NULL; } void encode_stream(FILE* fin, FILE* fout, HuffNode* tree, unsigned* padding) { int n; byte ch; byte buf = 0, nbuf = 0; HuffNode *p; byte code[256]; while (1) { n = fgetc(fin); if (n &lt; 0) break; ch = n; // Encode p = &amp;tree[ch]; n = 0; while (p-&gt;parent) { if (p == p-&gt;parent-&gt;left) { // Left is 0 code[n] = 0; } else if (p == p-&gt;parent-&gt;right) { code[n] = 1; } p = p-&gt;parent; n++; } // Write for (int i = n - 1; i &gt;= 0; i--) { buf |= code[i] &lt;&lt; nbuf; nbuf++; if (nbuf == 8) { fputc(buf, fout); nbuf = buf = 0; } } } fputc(buf, fout); *padding = 8 - nbuf; } void decode_stream(FILE* fin, FILE* fout, HuffNode* tree, unsigned padding) { size_t startpos = ftell(fin); // should be 1028 fseek(fin, 0L, SEEK_END); size_t endpos = ftell(fin); // last byte handling fseek(fin, startpos, SEEK_SET); int count = endpos - startpos; byte buf = 0, nbuf = 0, bit; HuffNode *p; while (count &gt; 0 || nbuf &gt; 0) { // Start from tree top p = tree + 510; while (p-&gt;left || p-&gt;right) { // Prepare next bit if needed if (nbuf == 0) { if (count &lt;= 0) return; buf = fgetc(fin); if (count == 1) { // Last bit nbuf = 8 - padding; if (nbuf == 0) { return; } } else { nbuf = 8; } count--; } // p has child bit = buf &amp; 1; buf &gt;&gt;= 1; nbuf--; if (bit == 0) p = p-&gt;left; else p = p-&gt;right; } fputc(p-&gt;data, fout); } } void compress_file(const char* filename, const char* newname) { FILE *fin = fopen(filename, "rb"), *fout = fopen(newname, "wb"); unsigned freq[256], padding; HuffNode tree[512]; size_t padding_pos; count_frequency(fin, freq); construct_huffman(freq, tree); rewind(fin); for (int i = 0; i &lt; 256; i++) fwrite(freq + i, 4, 1, fout); // Write a placeholder for the padding padding_pos = ftell(fout); fwrite(&amp;padding, 4, 1, fout); encode_stream(fin, fout, tree, &amp;padding); // Write the padding to the placeholder fseek(fout, padding_pos, SEEK_SET); fwrite(&amp;padding, 4, 1, fout); fclose(fin); fclose(fout); } void uncompress_file(const char* filename, const char* newname) { FILE *fin = fopen(filename, "rb"), *fout = fopen(newname, "wb"); unsigned freq[256], padding; HuffNode tree[512]; for (int i = 0; i &lt; 256; i++) { fread(&amp;padding, 4, 1, fin); freq[i] = padding; } fread(&amp;padding, 4, 1, fin); construct_huffman(freq, tree); decode_stream(fin, fout, tree, padding); fclose(fin); fclose(fout); } void print_help(void) { puts("Usage: huffman (-c|-d) input output"); puts(" -c Compress file from input to output"); puts(" -d Uncompress file from input to output"); puts("\nCreated by iBug"); } int main(int argc, char** argv) { if (argc != 4) { print_help(); return 1; } if (!strcmp(argv[1], "-c")) { compress_file(argv[2], argv[3]); } else if (!strcmp(argv[1], "-d")) { uncompress_file(argv[2], argv[3]); } else { print_help(); return 1; } return 0; } </code></pre> <p>In addition to the mandatory CC BY-SA 3.0 license by posting on Stack Exchange, the code itself also has a MIT license.</p> <p>On a side note: Although the course has ended and this code is not maintained anymore, it's still one of the programs that I have written with maximum attention and carefulness, so I believe that any feedback to this code is highly valuable and I will remember them in my future C-coding times.</p>
[]
[ { "body": "<h1>Header size</h1>\n<p>256*4 bytes is very big for a header. The size could be reduced substantially by using one or several of these common techniques:</p>\n<ul>\n<li>Store the <em>code length</em> instead of symbol frequency. These definitely won't need 32 bits each, 8 would already be a lot. You can pack them in 4 bits each if you set a length limit of 15. Storing lengths is not ambiguous because you can use <a href=\"https://en.wikipedia.org/wiki/Canonical_Huffman_code\" rel=\"noreferrer\">canonical Huffman codes</a> (there is an easy algorithm to generate them from your table of code lengths, discarding the code itself).</li>\n<li>Compress the header with delta encoding: storing the length difference between subsequent codes, using a variable-length encoding. Small differences tend to be more common. (seen in eg DEFLATE)</li>\n<li>Remove most zero-lengths from the header, by first storing a sparse bitmap that indicates which symbols occur in the file. (seen in eg bzip2)</li>\n</ul>\n<h1>Encoding process</h1>\n<p>Walking up the tree for every byte of the file is needlessly inefficient. You could precompute an array of codes and lengths once in advance and then use the array during encoding. The code could be represented as a single unsigned integer, no array necessary (it won't be that long, and you will want to limit the code lengths anyway for decoding and header reasons). It can be prepended to <code>buf</code> in a couple of simple bitwise operations, similar to how you currently add a single bit, but <code>nbuf++</code> turns into <code>nbuf += codelength</code>. Together this lets the encoding process take a constant number of operations instead of scaling linearly with the code length.</p>\n<h1>Decoding process</h1>\n<p>Currently your code implements bit-by-bit tree walking, which is (as one <a href=\"http://www.compressconsult.com/huffman/#decoding\" rel=\"noreferrer\">source</a> puts it) dead slow. The alternative is decoding several bits at the same time by using an array lookup. There are a lot of subtly different ways to do that, but the basis of all of them is that part of the buffer is used to index into a table. Limiting the maximum length of the codes is very useful, because with a limited length you can guarantee that decoding is a <em>single-step process</em>, resolving one symbol from the buffer in a constant number of operations, with no looping.</p>\n<p>Some possible relevant sources for these techniques are the one in the previous paragraph and:</p>\n<ul>\n<li><a href=\"https://github.com/IJzerbaard/shortarticles/blob/master/huffmantable.md\" rel=\"noreferrer\">Introduction to table based Huffman decoding</a></li>\n<li><a href=\"https://www.researchgate.net/publication/262283882_An_efficient_algorithm_of_Huffman_decoder_with_nearly_constant_decoding_time\" rel=\"noreferrer\">An efficient algorithm of Huffman decoder with nearly constant decoding time</a></li>\n<li><a href=\"http://fastcompression.blogspot.com/2015/07/huffman-revisited-part-2-decoder.html\" rel=\"noreferrer\">Huffman revisited - Part 2 : the Decoder</a></li>\n<li><a href=\"https://www.researchgate.net/publication/221544036_A_Fast_and_Space_-_Economical_Algorithm_for_Length_-_Limited_Coding\" rel=\"noreferrer\">A Fast and Space - Economical Algorithm for Length - Limited Coding</a> (for a way to generate the code lengths with a length limit)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T19:05:08.257", "Id": "210660", "ParentId": "210654", "Score": "6" } }, { "body": "<h2>Use standard types</h2>\n\n<p>You define this:</p>\n\n<pre><code>typedef unsigned char byte;\n</code></pre>\n\n<p>But you also already <code>#include &lt;stdint.h&gt;</code>. As such, you have access to <code>uint8_t</code>, which is more explicit about its size than <code>char</code>.</p>\n\n<h2>Identify local functions</h2>\n\n<p>If all of your functions are in the same translation unit (which seems to be the case), make them <code>static</code>.</p>\n\n<h2>Forever loops</h2>\n\n<p>This is quite minor, but <code>while (1)</code> isn't my favourite way of defining a forever loop. You can either do <code>for (;;)</code> or <code>while (true)</code>, after having included <code>stdbool.h</code>. <code>1</code> is less expressive than <code>true</code>.</p>\n\n<h2>Unite declaration and initialization</h2>\n\n<pre><code>int ch;\nwhile (1) {\n ch = fgetc(fp);\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>while (true) {\n int ch = fgetc(fp);\n</code></pre>\n\n<h2>Define magic numbers</h2>\n\n<p>Make a <code>#define</code> or a global <code>const int</code> for 256. It's used all over your code, and it'd be good to replace that with a symbol for legibility and maintainability.</p>\n\n<h2>Do one thing at a time</h2>\n\n<pre><code>lower[0] = 0, upper[0] = 256;\n// ...\nunsigned t = freq[i]; freq[i] = freq[j]; freq[j] = t;\n</code></pre>\n\n<p>It's rarely an improvement to the legibility of code to do multi-statement lines. Just put these on separate lines.</p>\n\n<h2>Sanitize loop counters</h2>\n\n<p>You have:</p>\n\n<pre><code>unsigned top = 1;\n// ...\nwhile (top &gt; 0) {\n top--;\n // ...`continue`s under certain conditions...\n top += 2;\n}\n</code></pre>\n\n<p>This is a little wacky. Just do:</p>\n\n<pre><code>for (int top = 0; top &gt;= 0; top--) {\n // ... continue under certain conditions...\n top += 2;\n}\n</code></pre>\n\n<p>I <em>think</em> those are equivalent.</p>\n\n<h2>Sanitize logic</h2>\n\n<pre><code> int flag = 0;\n while (...) {\n if (freq[i] &lt; freq[j]) {\n //...\n flag = !flag;\n }\n flag ? i++ : j--;\n }\n</code></pre>\n\n<p>This is ternary abuse. The flag should be a <code>bool</code> (from <code>stdbool.h</code>). Rewrite this as:</p>\n\n<pre><code>bool flag = false;\nwhile (...) {\n if (freq[i] &lt; freq[j]) {\n //...\n flag = !flag;\n }\n if (flag) i++;\n else j--;\n}\n</code></pre>\n\n<h2>Choose a pointer spacing standard</h2>\n\n<p>You do:</p>\n\n<pre><code>void compress_file(const char* filename, const char* newname) {\n</code></pre>\n\n<p>but you also do:</p>\n\n<pre><code>FILE *fin = fopen(filename, \"rb\"),\n *fout = fopen(newname, \"wb\");\n</code></pre>\n\n<p>Personally I like the latter; either way, you should pick a standard and apply it everywhere.</p>\n\n<h2>Let <code>fwrite</code> do the iteration</h2>\n\n<p>This:</p>\n\n<pre><code>for (int i = 0; i &lt; 256; i++)\n fwrite(freq + i, 4, 1, fout);\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>fwrite(freq, 4, 256, fout);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T00:34:47.197", "Id": "210669", "ParentId": "210654", "Score": "6" } }, { "body": "<p>Harold has given a pretty comprehensive answer. I thought your code for building the Huffman tree was a little obscure, the usual approach is to use a \"heap\" which efficiently maintains the smallest element of a array in position zero. </p>\n\n<p>I have been working on an implementation of RFC 1951 in C#, so far I have found that it's fairly unusual for the bit length limits to be exceeded in practice ( I am using it to write PDF files ), so my approach was simply to try a smaller block size if the limits were exceeded.</p>\n\n<p>Here's my C# \"deflate\" code for comparison ( hope it's alright to post code as part of a reply, I am new here ):</p>\n\n<pre><code>using G = System.Collections.Generic; \nusing U = System.UInt16; // Could also be UInt32 or UInt64, not sure what is best.\n\nclass Encoder : G.List&lt;byte&gt; // Compression per RFC1950, RFC1951.\n{\n public G.List&lt;byte&gt; Deflate( byte [] inp )\n {\n Clear();\n Add( 0x78); Add( 0x9C ); // RFC 1950 bytes\n ReadInp( inp );\n while ( DoOutput( 1 ) == 0 );\n FlushBitBuf();\n Put32( Adler32( inp ) ); // RFC 1950 checksum\n // System.Console.WriteLine( \"Encoder.Deflate, input size=\" + inp.Length + \" output size=\" + this.Count );\n return this; \n }\n\n class OffsetList{ public uint Offset; public OffsetList Next; } // List of 3-byte match offsets.\n\n void ReadInp( byte [] inp ) // LZ77 compression, per RFC1951\n { \n G.Dictionary &lt;uint,OffsetList&gt; lookup = new G.Dictionary&lt;uint,OffsetList&gt;(); // Note: could reduce storage requirement by removing entries outside 32k window\n uint n = (uint)inp.Length;\n SetIBufSize( n ); \n\n uint w = 0; // holds last 3 bytes of input\n int todo = 0; // number of bytes in w that have not yet been output to IBuf, can be negative when a match is found\n uint pendingMatchLen=0, pendingDist=0;\n\n for ( uint i = 0; i &lt;= 1 &amp;&amp; i &lt; n; i += 1 ) { w = ( ( w &lt;&lt; 8 ) | inp[i] ); todo += 1; }\n\n for ( uint i = 2; i &lt; n; i += 1 )\n {\n w = ( ( w &lt;&lt; 8 ) | inp[i] ) &amp; 0xffffffu; todo += 1;\n OffsetList e, x = new OffsetList(); x.Offset = i;\n uint bestMatchLen = 0, bestDist = 0;\n if ( lookup.TryGetValue( w, out e ) )\n {\n x.Next = e;\n OffsetList p = x;\n if ( todo &gt;= 3 ) while ( e != null )\n {\n uint dist = i - e.Offset; if ( dist &gt; 32768 ) { p.Next = null; break; }\n uint matchLen = MatchLen( inp, dist, i );\n if ( matchLen &gt; bestMatchLen ) { bestMatchLen = matchLen; bestDist = dist; } \n p = e; e = e.Next; \n }\n }\n lookup[ w ] = x; ISpace();\n\n // \"Lazy matching\" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use.\n // Example: abc012bc345.... abc345 : abc345 can be encoded as either [abc][345] or as a[bc345].\n // Since a range needs more bits to encode than a literal the latter is better.\n\n if ( pendingMatchLen &gt; 0 )\n {\n if ( bestMatchLen &gt; pendingMatchLen || bestMatchLen == pendingMatchLen &amp;&amp; bestDist &lt; pendingDist )\n { IPut( inp[i-3] ); todo -= 1; }\n else // Save the pending match, suppress bestMatch if any.\n {\n IPut( (ushort)(257 + pendingMatchLen) );\n IPut( (ushort) pendingDist );\n todo -= (int)pendingMatchLen;\n bestMatchLen = 0;\n }\n pendingMatchLen = 0;\n }\n if ( bestMatchLen &gt; 0 ) { pendingMatchLen = bestMatchLen; pendingDist = bestDist; }\n else if ( todo == 3 ) { IPut( (byte)(w &gt;&gt; 16) ); todo = 2; } \n } // end for loop\n if ( pendingMatchLen &gt; 0 )\n {\n IPut( (ushort)(257 + pendingMatchLen) );\n IPut( (ushort) pendingDist );\n todo -= (int)pendingMatchLen;\n }\n while ( todo &gt; 0 ){ todo -= 1; IPut( (byte)( w &gt;&gt; (todo*8) ) ); }\n } // end ReadInp\n\n uint MatchLen( byte [] inp, uint dist, uint i )\n {\n // From lookup, we already have a match of 3 bytes, this function computes how many more bytes match.\n uint x = i+1;\n ulong end = (ulong)inp.Length;\n if ( end - i &gt; 256 ) end = i + 256; // Maximum match is 258\n while ( x &lt; end &amp;&amp; inp[x] == inp[x-dist] ) x += 1;\n return x - i + 2; \n }\n\n ushort [] IBuf; // Intermediate buffer, holds output from LZ99 algorithm.\n const uint IBufSizeMax = 0x40000;\n uint IBufSize, IBufI, IBufJ;\n void IPut( ushort x ) { IBuf[IBufI++] = x; if ( IBufI == IBufSize ) IBufI = 0; }\n ushort IGet(){ ushort result = IBuf[IBufJ++]; if ( IBufJ == IBufSize ) IBufJ = 0; return result; }\n uint ICount(){ if ( IBufI &gt;= IBufJ ) return IBufI - IBufJ; else return IBufI + IBufSize - IBufJ; } // Number of values in IBuf\n void ISpace(){ while ( ICount() &gt; IBufSize - 10 ) DoOutput( 0 ); } // Ensure IBuf has space for at least 10 values.\n void SetIBufSize( uint x ) { x += 20; if ( x &gt; IBufSizeMax ) x = IBufSizeMax; if ( IBufSize &lt; x ) { IBufSize = x; IBuf = new ushort[x]; } }\n\n U DoOutput( U last ) // while DoBlock fails, retry with a smaller amount of input\n {\n uint n = ICount();\n while ( !DoBlock( n, last ) ) { last = 0; n -= n / 20; }\n return last;\n }\n\n ///////////////////////////////////////////////////////////////////////////////\n // RFC 1951 encoding constants.\n\n static readonly byte [] ClenAlphabet = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; // size = 19\n static readonly byte [] MatchExtra = { 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 }; // size = 29\n static readonly ushort [] MatchOff = { 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, 131,163,195,227, 258, 0xffff };\n static readonly byte [] DistExtra = { 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 }; // size = 30\n static readonly ushort [] DistOff = { 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, 1025,1537,2049,3073,\n 4097,6145,8193,12289, 16385,24577, 0xffff };\n\n readonly U [] LitFreq = new U[288], LitLen = new U[288], LitCode = new U[288];\n readonly U [] DistFreq = new U[32], DistLen = new U[32], DistCode = new U[32];\n readonly U [] LenFreq = new U[19], LenLen = new U[19], LenCode = new U[19];\n\n bool DoBlock( uint n, U last )\n {\n Clear( LitFreq ); Clear( DistFreq ); Clear( LenFreq );\n uint saveI = IBufI, saveJ = IBufJ;\n int got = 0; while ( got &lt; n )\n {\n ushort x = IGet(); got += 1;\n if ( x &lt; 256 ) LitFreq[ x ] += 1;\n else\n { \n x -= 257;\n uint dist = IGet(); got += 1;\n uint mc=0; while ( x &gt;= MatchOff[mc] ) mc += 1; mc -= 1;\n uint dc=0; while ( dist &gt;= DistOff[dc] ) dc += 1; dc -= 1;\n LitFreq[ 257+mc ] += 1;\n DistFreq[ dc ] += 1;\n }\n }\n LitFreq[256] += 1; // end of block code\n IBufI = saveI; IBufJ = saveJ;\n\n int nLitCode = HE.ComputeCode( 15, LitFreq, LitLen, LitCode ); if ( nLitCode &lt; 0 ) return false;\n int nDistCode = HE.ComputeCode( 15, DistFreq, DistLen, DistCode ); if ( nDistCode &lt; 0 ) return false;\n\n if ( nDistCode == 0 ) nDistCode = 1;\n LenPass = 1; DoLengths( nLitCode, LitLen, true ); DoLengths( nDistCode, DistLen, false );\n\n if ( HE.ComputeCode( 7, LenFreq, LenLen, LenCode ) &lt; 0 ) return false;\n\n int nLenCode = 19;\n while ( nLenCode &gt; 0 &amp;&amp; LenLen[ ClenAlphabet[nLenCode-1] ] == 0 ) nLenCode -= 1;\n\n PutBit( last ); // Last block flag\n PutBits( 2, 2 ); // Dynamic Huffman ( for small blocks fixed coding may work better, not implemented )\n\n PutBits( 5, (U)( nLitCode - 257 ) ); PutBits( 5, (U)( nDistCode - 1 ) ); PutBits( 4, (U)( nLenCode - 4 ) );\n for ( int i=0; i &lt; nLenCode; i += 1 ) PutBits( 3, LenLen[ ClenAlphabet[i] ] );\n LenPass = 2; DoLengths( nLitCode, LitLen, true ); DoLengths( nDistCode, DistLen, false ); \n\n got = 0; while ( got &lt; n )\n {\n U x = IGet(); got += 1;\n if ( x &lt; 256 ) PutBits( LitLen[x], LitCode[x] );\n else\n { \n x -= 257;\n ushort dist = IGet(); got += 1;\n uint mc=0; while ( x &gt;= MatchOff[mc] ) mc += 1; mc -= 1;\n uint dc=0; while ( dist &gt;= DistOff[dc] ) dc += 1; dc -= 1;\n PutBits( LitLen[257+mc], LitCode[257+mc] );\n PutBits( MatchExtra[mc], (U)(x-MatchOff[mc]) );\n PutBits( DistLen[dc], DistCode[dc] );\n PutBits( DistExtra[dc], (U)(dist-DistOff[dc]) );\n }\n }\n PutBits( LitLen[256], LitCode[256] ); // block end code\n return true;\n } // end DoBlock\n\n // Encoding of code lengths ( RFC 1951, page 13 ).\n\n U LenPass, Plen, ZeroRun, Repeat;\n\n void PutLenCode( U code ) { if ( LenPass == 1 ) LenFreq[code] += 1; else PutBits( LenLen[code], LenCode[code] ); }\n\n void DoLengths( int n, U [] a, bool isLit )\n {\n if ( isLit ) { Plen = 0; ZeroRun = 0; Repeat = 0; }\n for ( int i=0; i&lt;n; i += 1 )\n {\n U len = a[i];\n if ( len == 0 ){ EncRepeat(); ZeroRun += 1; Plen = 0; }\n else if ( len == Plen ) { Repeat += 1; }\n else { EncZeroRun(); EncRepeat(); PutLenCode( len ); Plen = len; }\n } \n if ( !isLit ) { EncZeroRun(); EncRepeat(); }\n }\n\n void EncRepeat()\n {\n while ( Repeat &gt; 0 )\n {\n if ( Repeat &lt; 3 ) { PutLenCode( Plen ); Repeat -= 1; }\n else { U x = Repeat; if ( x &gt; 6 ) x = 6; PutLenCode( 16 ); if ( LenPass == 2 ) PutBits( 2,(U)(x-3) ); Repeat -= x; }\n }\n }\n\n void EncZeroRun()\n {\n while ( ZeroRun &gt; 0 )\n {\n if ( ZeroRun &lt; 3 ) { PutLenCode( 0 ); ZeroRun -= 1; }\n else if ( ZeroRun &lt; 11 ) { PutLenCode( 17 ); if ( LenPass == 2 ) PutBits( 3, (U)(ZeroRun-3) ); ZeroRun = 0; }\n else { U x = ZeroRun; if ( x &gt; 138 ) x = 138; PutLenCode( 18 ); if ( LenPass == 2 ) PutBits( 7,(U)(x-11) ); ZeroRun -= x; }\n }\n }\n\n static void Clear( U [] a ){ System.Array.Clear( a, 0, a.Length ); /*for ( int i=0; i &lt; a.Length; i += 1 ) a[i] = 0;*/ }\n\n public static uint Adler32( byte [] b ) // per RFC1950\n {\n uint s1=1, s2=0;\n for ( int i=0; i&lt;b.Length; i+= 1 )\n {\n s1 = ( s1 + b[i] ) % 65521;\n s2 = ( s2 + s1 ) % 65521;\n }\n return s2*65536 + s1; \n }\n\n // Output bitstream\n byte Buf = 0, M = 1;\n public void PutBit( U b ) { if ( b != 0 ) Buf |= M; M &lt;&lt;= 1; if ( M == 0 ) { Add(Buf); Buf = 0; M = 1; } }\n public void PutBits( U n, U x ) { for ( int i = 0; i &lt; n; i += 1 ) { PutBit( (U)(x &amp; 1u) ); x &gt;&gt;= 1; } }\n public void FlushBitBuf(){ while ( M != 1 ) PutBit( 0 ); }\n public void Put32( uint x ) { Add( (byte)( x &gt;&gt; 24 ) ); Add( (byte)( x &gt;&gt; 16 ) ); Add( (byte)( x &gt;&gt; 8 ) ); Add( (byte) x ); } \n} // end class Encoder\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\nclass HE // Given a list of frequencies (freq), compute Huffman code lengths (nbits) and codes (tree_code).\n{\n public static int ComputeCode( int limit, U [] freq, U [] nbits, U [] tree_code )\n {\n int ncode = freq.Length;\n Node [] heap = new Node[ncode];\n int hn = 0;\n for ( int i = 0; i &lt; ncode; i += 1 )\n {\n U f = freq[i];\n if ( f &gt; 0 )\n {\n Node n = new Node();\n n.Freq = f;\n n.Code = (U)i;\n HeapInsert( heap, hn, n );\n hn += 1;\n }\n }\n\n for ( int i = 0; i &lt; nbits.Length; i += 1 ) nbits[i] = 0;\n if ( hn &lt;= 1 ) // Special case\n { if ( hn == 1 ) nbits[ heap[0].Code ] = 1; }\n else\n {\n while ( hn &gt; 1 )\n {\n Node n = new Node();\n hn -= 1; n.Left = HeapRemove( heap, hn );\n hn -= 1; n.Right = HeapRemove( heap, hn );\n n.Freq = (U) ( n.Left.Freq + n.Right.Freq ); \n n.Depth = (U) ( 1 + ( n.Left.Depth &gt; n.Right.Depth ? n.Left.Depth : n.Right.Depth ) ); \n HeapInsert( heap, hn, n );\n hn += 1;\n }\n Walk( nbits, heap[0], 0 ); // Walk the tree to find the code lengths (nbits).\n }\n\n for ( int i = 0; i &lt; ncode; i += 1 ) if ( nbits[i] &gt; limit ) return -1;\n\n // Now compute codes, code below is from rfc1951 page 7\n\n uint maxBits = 0;\n for ( int i = 0; i &lt; ncode; i += 1 ) if ( nbits[i] &gt; maxBits ) maxBits = nbits[i];\n\n U [] bl_count = new U[maxBits+1];\n for ( int i=0; i &lt; ncode; i += 1 ) bl_count[ nbits[i] ] += 1;\n\n U [] next_code = new U[maxBits+1];\n U code = 0; bl_count[0] = 0;\n for ( int i = 0; i &lt; maxBits; i += 1 ) \n {\n code = (U)( ( code + bl_count[i] ) &lt;&lt; 1 );\n next_code[i+1] = code;\n }\n\n for ( int i = 0; i &lt; ncode; i += 1 ) \n {\n uint len = nbits[i];\n if (len != 0) \n {\n tree_code[i] = Reverse( next_code[len], len );\n next_code[len] += 1;\n }\n }\n\n //System.Console.WriteLine( \"Huff Code\" );\n // for ( uint i=0; i &lt; ncode; i += 1 ) if ( nbits[i] &gt; 0 )\n // System.Console.WriteLine( \"i=\" + i + \" len=\" + nbits[i] + \" tc=\" + tree_code[i].ToString(\"X\") + \" freq=\" + freq[i] );\n\n while ( ncode &gt; 0 &amp;&amp; nbits[ ncode-1 ] == 0 ) ncode -= 1;\n return ncode;\n }\n\n class Node{ public U Freq; public U Code, Depth; public Node Left, Right; }\n\n static U Reverse( U x, uint bits )\n { U result = 0; for ( int i = 0; i &lt; bits; i += 1 ) { result &lt;&lt;= 1; result |= (U)(x &amp; 1u); x &gt;&gt;= 1; } return result; } \n\n static void Walk( U [] a, Node n,U len )\n { if ( n.Left == null ) a[n.Code] = len; else { Walk( a, n.Left, (U)(len+1) ); Walk( a, n.Right, (U)(len+1) ); } }\n\n static bool LessThan( Node a, Node b )\n { return a.Freq &lt; b.Freq || a.Freq == b.Freq &amp;&amp; a.Depth &lt; b.Depth; }\n\n static void HeapInsert( Node [] heap, int h, Node n ) // h is size of heap before insertion\n {\n int j = h;\n while ( j &gt; 0 )\n {\n int p = ( j - 1 ) / 2; // parent\n Node pn = heap[p];\n if ( !LessThan(n,pn) ) break;\n heap[j] = pn; // move parent down\n j = p;\n } \n heap[j] = n;\n }\n\n static Node HeapRemove( Node [] heap, int h ) // h is size of heap after removal\n {\n Node result = heap[0];\n Node n = heap[h];\n int j = 0;\n while ( true )\n {\n int c = j * 2 + 1; if ( c &gt;= h ) break;\n Node cn = heap[c];\n if ( c+1 &lt; h )\n {\n Node cn2 = heap[c+1];\n if ( LessThan(cn2,cn) ) { c += 1; cn = cn2; }\n } \n if ( !LessThan(cn,n) ) break;\n heap[j] = cn; j = c; \n }\n heap[j] = n;\n return result;\n }\n} // end class HE\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:40:18.503", "Id": "407325", "Score": "0", "body": "(Welcome to Code Review!) (`hope it's alright to […], I am new here` [there you go](https://codereview.stackexchange.com/help/how-to-answer)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:09:15.740", "Id": "210699", "ParentId": "210654", "Score": "0" } } ]
{ "AcceptedAnswerId": "210669", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:00:39.887", "Id": "210654", "Score": "12", "Tags": [ "algorithm", "c", "tree", "compression" ], "Title": "Huffman tree compressing/decompressing in C" }
210654
<p>I have implemented a program in C to crack passwords by generating all possible combinations of words ([A-Z][a-z]) up to the length of 5. While the program works, I would like to receive comments on the efficiency of the algorithm and other design decisions that would improve the code. The exercise is part of the course CS50 by Harvard. </p> <p>I timed the program using unix's <strong>time</strong> and the time the program took to print all the combinations was </p> <pre><code>**real** 14m39.433s; **user** 0m10.040s; **sys** 0m36.356s. </code></pre> <p><code>CS50.h</code> is a library developed for the course as training wheels for students. <code>String</code> (<code>char*</code>) and <code>Bool</code> are types defined in this library.</p> <pre><code>#define _XOPEN_SOURCE #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;cs50.h&gt; int main(int argc, char *argv[]) { if(argc != 2) { printf("Usage: ./crack hash\n"); return 1; } string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char password[6] = "\0\0\0\0\0\0"; string hash = argv[1]; char salt[3]; memcpy(salt, hash, 2); salt[2] = '\0'; bool flag = false; int alphabet_len = 52; for(int i = 0; i &lt; alphabet_len; i++) { password[0] = alphabet[i]; password[1] = password[2] = password[3] = password[4] = '\0'; if(!strcmp(hash, crypt(password, salt))) { flag = true; break; } for(int j = 0; j &lt; alphabet_len; j++) { password[1] = alphabet[j]; password[2] = password[3] = password[4] = '\0'; if(!strcmp(hash, crypt(password, salt))) { flag = true; break; } for(int k = 0; k &lt; alphabet_len; k++) { password[2] = alphabet[k]; password[3] = password[4] = '\0'; if(!strcmp(hash, crypt(password, salt))) { flag = true; break; } for(int l = 0; l &lt; alphabet_len; l++) { password[3] = alphabet[l]; password[4] = '\0'; if(!strcmp(hash, crypt(password, salt))) { flag = true; break; } for(int m = 0; m &lt; alphabet_len; m++) { password[4] = alphabet[m]; if(!strcmp(hash, crypt(password, salt))) { flag = true; break; } } if(flag) break; } if(flag) break; } if(flag) break; } if(flag) break; } if(flag) printf("Password: %s\n", password); else printf("Password not found\n"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:33:34.060", "Id": "407263", "Score": "0", "body": "Post the declaration of `crypt()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:35:21.493", "Id": "407264", "Score": "0", "body": "@chux http://pubs.opengroup.org/onlinepubs/007904975/functions/crypt.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:37:09.377", "Id": "407265", "Score": "0", "body": "Oar, \"`CS50.h` is a library ... `Bool` are types defined in this library.\" Why mention `Bool` is it is not used in code? Or is that a typo and you meant `bool`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T22:16:04.360", "Id": "475763", "Score": "0", "body": "regarding: `char password[6] = \"\\0\\0\\0\\0\\0\\0\";` This is actually 7 characters long due to the `\"...\"` literal automatically being terminated with a NUL character" } ]
[ { "body": "<h2>cs50.h?</h2>\n\n<p>This seems less like a set of \"training wheels\" and more like a bicycle for fish. It's potentially confusing, opaque, and doesn't seem all that useful. If I were you, I'd be learning how to code in real C - using <code>char*</code>, and <code>bool</code> from <code>stdbool.h</code>.</p>\n\n<h2>Don't store things that should be computed</h2>\n\n<p>Your <code>string alphabet</code> shouldn't exist. Just iterate a <code>char</code> between a-z and A-Z. Characters can be incremented the same way that integers can.</p>\n\n<h2>Input validation</h2>\n\n<p>It seems like you expect <code>hash</code> to be two characters long, but you don't check that. You should be checking it with <code>strlen</code>; then you can issue <code>memcpy</code> without later setting a null terminator, as it'll be null-terminated already.</p>\n\n<h2>DRY</h2>\n\n<p>Don't repeat yourself. This is the most important aspect of the program that needs improvement. This block:</p>\n\n<pre><code> for(int m = 0; m &lt; alphabet_len; m++)\n {\n password[4] = alphabet[m];\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n }\n if(flag)\n break;\n</code></pre>\n\n<p>is repeated nearly verbatim five times. There are many different ways to condense this. The easiest is probably a recursive function that calls itself with an increasing depth integer. This may actually decrease the performance of the application, but that's up to you to test. There are also ways to rewrite this loop to have state so that neither copy-and-paste nor recursion are necessary; you'll probably want to compare such a method against a recursive method to see which is more performant and clean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T22:04:15.303", "Id": "475762", "Score": "1", "body": "In C, you cannot increment characters to iterate from A to Z. That's possible in ASCII and related encodings, but not in EBCDIC. C does not guarantee ASCII." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:24:47.693", "Id": "210671", "ParentId": "210656", "Score": "5" } }, { "body": "<p>regarding: </p>\n\n<pre><code> printf(\"Usage: ./crack hash\\n\");\n</code></pre>\n\n<ol>\n<li>Error messages should be output to <code>stderr</code>, not <code>stdout</code>.</li>\n<li>an executable can be renamed, so 'crack' is not a good thing to use.</li>\n</ol>\n\n<p>Suggest:</p>\n\n<pre><code> fprintf( stderr, \"USAGE: %s hash\\n\", argv[0] );\n</code></pre>\n\n<p>Note: <code>argv[0]</code> always contains the executable name</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T01:36:15.797", "Id": "210672", "ParentId": "210656", "Score": "3" } }, { "body": "<h3>A function</h3>\n\n<blockquote>\n<pre><code> bool flag = false;\n int alphabet_len = 52;\n\n for(int i = 0; i &lt; alphabet_len; i++)\n {\n password[0] = alphabet[i];\n password[1] = password[2] = password[3] = password[4] = '\\0';\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n for(int j = 0; j &lt; alphabet_len; j++)\n {\n password[1] = alphabet[j];\n password[2] = password[3] = password[4] = '\\0';\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n for(int k = 0; k &lt; alphabet_len; k++)\n {\n password[2] = alphabet[k];\n password[3] = password[4] = '\\0';\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n for(int l = 0; l &lt; alphabet_len; l++)\n {\n password[3] = alphabet[l];\n password[4] = '\\0';\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n for(int m = 0; m &lt; alphabet_len; m++)\n {\n password[4] = alphabet[m];\n if(!strcmp(hash, crypt(password, salt)))\n {\n flag = true;\n break;\n }\n }\n if(flag)\n break;\n }\n if(flag)\n break;\n }\n if(flag)\n break;\n }\n if(flag)\n break;\n }\n\n if(flag)\n</code></pre>\n</blockquote>\n\n<p>If you define a function, you could get rid of <code>flag</code>. E.g. </p>\n\n<pre><code>bool find_password(string alphabet, int alphabet_len, char salt[]) {\n for(int i = 0; i &lt; alphabet_len; i++)\n {\n password[0] = alphabet[i];\n password[1] = password[2] = password[3] = password[4] = '\\0';\n\n if (!strcmp(hash, crypt(password, salt)))\n {\n return true;\n }\n\n for (int j = 0; j &lt; alphabet_len; j++)\n {\n password[1] = alphabet[j];\n password[2] = password[3] = password[4] = '\\0';\n\n if (!strcmp(hash, crypt(password, salt)))\n {\n return true;\n }\n\n for (int k = 0; k &lt; alphabet_len; k++)\n {\n password[2] = alphabet[k];\n password[3] = password[4] = '\\0';\n\n if (!strcmp(hash, crypt(password, salt)))\n {\n return true;\n }\n\n for (int l = 0; l &lt; alphabet_len; l++)\n {\n password[3] = alphabet[l];\n password[4] = '\\0';\n\n if (!strcmp(hash, crypt(password, salt)))\n {\n return true;\n }\n\n for (int m = 0; m &lt; alphabet_len; m++)\n {\n password[4] = alphabet[m];\n\n if (!strcmp(hash, crypt(password, salt)))\n {\n return true;\n }\n }\n }\n }\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>Which you'd use like </p>\n\n<pre><code> if (find_password(alphabet, strlen(alphabet), make_salt(argv[1]), password))\n</code></pre>\n\n<h3>Recursive</h3>\n\n<p>Now, if you automate the increasing length, you could have </p>\n\n<pre><code>bool find_password(string alphabet, int alphabet_len, string salt, char password[])\n{\n return find_password(alphabet, alphabet_len, salt, password, 0, 5);\n}\n\nbool find_password_recursive(string alphabet, int len, string salt, char password[], int i, int n) {\n if (i &gt;= n)\n {\n return false;\n }\n\n for (int j = 0; j &lt; len; j++)\n {\n password[i] = alphabet[j];\n\n if (!strcmp(hash, crypt(password, salt))\n || find_password(alphabet, len, salt, password, i + 1, n)\n )\n {\n return true;\n }\n }\n\n password[i] = '\\0';\n\n return false;\n}\n</code></pre>\n\n<p>Short variable names used to avoid scrolling. </p>\n\n<p>We can clear <code>password[i]</code> exactly once here. In the loop, we keep changing it. We only have to clear once after finishing the loop. We don't have to clear later characters, as we already cleared those. </p>\n\n<h3>Static globals</h3>\n\n<p>C allows file scoped variables through the use of the static keyword. E.g. </p>\n\n<pre><code>static string alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n</code></pre>\n\n<p>These would be defined outside of any function and be accessible to functions in the same file. </p>\n\n<p>Now we don't have to keep passing <code>alphabet</code> and <code>alphabet_len</code> around everywhere. </p>\n\n<h3>A useful return</h3>\n\n<p>But do we really want our function to return a Boolean value and modify one of the inputs? A general rule is to only do one of those things. So we'd really prefer to use the function like </p>\n\n<pre><code> char *password = find_password(make_salt(argv[1]), 5);\n if (password)\n {\n printf(\"Password: %s\\n\", password);\n\n free(password);\n }\n else\n {\n printf(\"Password not found\\n\");\n }\n</code></pre>\n\n<p>And with the proper helper function, we can. </p>\n\n<pre><code>char *find_password(char *salt, int maximum_length)\n{\n char *password = calloc(maximum_length + 1, sizeof password[0]);\n if (!password)\n {\n /* Panic: perhaps output or log an error message, but certainly */\n exit(-1);\n }\n\n char *result = find_password_recursive(salt, password, 0, maximum_length);\n if (!result)\n {\n free(password);\n }\n\n return result;\n}\n</code></pre>\n\n<p>And </p>\n\n<pre><code>char * find_password_recursive(char * salt, char *password, int index, int maximum_length) {\n if (index &gt;= maximum_length)\n {\n return NULL;\n }\n\n for (int i = 0; alphabet[i]; i++)\n {\n password[index] = alphabet[i];\n\n if (!strcmp(hash, crypt(password, salt))\n || find_password(salt, password, index + 1, maximum_length)\n )\n {\n return password;\n }\n }\n\n password[index] = '\\0';\n\n return NULL;\n}\n</code></pre>\n\n<p>A downside of this approach is that the allocation for the password is implicit but the <code>free</code> needs to be explicit. An alternative would be to allocate the password explicitly and pass it into the function. Then both would be explicit. C doesn't have good support for making both implicit while allowing the results to be used by the caller. </p>\n\n<p>Both <code>calloc</code> and <code>free</code> are from <code>stdlib.h</code>, as is <code>NULL</code>. </p>\n\n<p>This time, I used the native C names rather than the <code>cs50.h</code> names. Remember to include <code>bool.h</code> if you drop <code>cs50.h</code> and continue using true and false. </p>\n\n<p>Now if we want to lengthen (or shorten) the potential passwords, we just have to call <code>find_password</code> with a larger <code>maximum_length</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T20:01:20.560", "Id": "210708", "ParentId": "210656", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T18:49:20.737", "Id": "210656", "Score": "3", "Tags": [ "performance", "c" ], "Title": "C program to crack passwords" }
210656