body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've solved test task for job vacancy. Need your feedback about my solution.</p> <h2>Task</h2> <p>The image below shows the puzzle in the solved state. The puzzle consists of 10 cells. Among the cells one is empty, the rest are numbered from 1 to 9. An empty cell is used for permutations of numbers along the allowed paths shown as lines connecting the cells. Puzzle is considered solved if all cells are ordered as shown in the image.</p> <p><a href="https://i.stack.imgur.com/ZRV3O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZRV3O.png" alt="Solved puzzle"></a></p> <p>Create console program in C# that partially or completely resolves puzzle on the specified figure. The program interface of implementation should be written in the form of:</p> <pre><code>public interface IResolver { int[] Solve(int[] input); } </code></pre> <p>where the input cell array <code>int[] input</code> are written left-to-right and top-to-bottom, blank cell indicates number 0. (the initial state can be written as <code>[1,2,3,0,4,5,6,7,8,9]</code>.) The output array must contain a sequence of moves – the numbers from 1 to 9, which must be moved at the next step in free cell.</p> <h2>Example</h2> <p>Let the input value of the method <code>Solve (int[] input)</code> be input <code>[1,2,3,4,6,5,0,7,8,9]</code>, then the optimal solution of the problem will consist of two steps, in the figure below:</p> <p><a href="https://i.stack.imgur.com/U7JxW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U7JxW.png" alt="Solution example"></a></p> <p>At the first step 6 ↔ 0 are exchanged, <code>6</code> is written to the output array. In the second step, 4 ↔ 0 are exchanged, while in the output the array <code>4</code> is written. The result of the program will be <code>[6,4]</code>.</p> <h2>Solution</h2> <p><code>Resolver.cs</code></p> <pre><code>public class Resolver { // Available indexes for move public static ReadOnlyDictionary&lt;int, int[]&gt; AvailableMoveIndexes =&gt; new ReadOnlyDictionary&lt;int, int[]&gt; ( new Dictionary&lt;int, int[]&gt; { [0] = new[] { 1, 2 }, [1] = new[] { 0, 4 }, [2] = new[] { 0, 3, 5 }, [3] = new[] { 2, 4 }, [4] = new[] { 1, 3, 6 }, [5] = new[] { 2, 7 }, [6] = new[] { 4, 8 }, [7] = new[] { 5, 8, 9 }, [8] = new[] { 6, 7, 9 }, [9] = new[] { 7, 8 } } ); private static bool IsSolved(IList&lt;int&gt; input) =&gt; input.SequenceEqual(new[] { 1, 2, 3, 0, 4, 5, 6, 7, 8, 9 }); private static void ValidateInput(IList&lt;int&gt; input) { if (input == null) throw new ArgumentNullException(nameof(input)); // Input must consist only from numbers from 0 to 9 if (!input.OrderBy(x =&gt; x).SequenceEqual(Enumerable.Range(0, 10))) throw new ArgumentException("Invalid input.", nameof(input)); } private readonly ReadOnlyCollection&lt;int&gt; _input; private IEnumerable&lt;int[]&gt; _indexMovesCollection; public Resolver(IList&lt;int&gt; input) { ValidateInput(input); _input = new ReadOnlyCollection&lt;int&gt;(input); } private int GetZeroIndex() =&gt; _input.IndexOf(0); public int[] Solve() { // Minimum number of moves based on distance from empty cell to target cell Dictionary&lt;int, int&gt; minimumNumberOfMovesDictionary = new Dictionary&lt;int, int&gt; { [0] = 2, [1] = 2, [2] = 1, [3] = 0, [4] = 1, [5] = 2, [6] = 2, [7] = 3, [8] = 3, [9] = 4 }; int minimumNumberOfMoves = minimumNumberOfMovesDictionary[GetZeroIndex()]; if (minimumNumberOfMoves == 0 &amp;&amp; IsSolved(_input)) return new int[0]; const int maximumNumberOfMoves = 100; int zeroIndex = GetZeroIndex(); // Get all move combinations _indexMovesCollection = AvailableMoveIndexes[zeroIndex].Select(index =&gt; new[] { index }); for (int moveCount = 1; moveCount &lt; maximumNumberOfMoves; moveCount++) { if (moveCount &gt;= minimumNumberOfMoves) { foreach (int[] indexMoves in _indexMovesCollection) { if (TrySolution(indexMoves, out int[] moveHistory)) return moveHistory; } } _indexMovesCollection = _indexMovesCollection .SelectMany(indexMoves =&gt; AvailableMoveIndexes[indexMoves.Last()] // Remove combinations where subsequent move can undo previous move .Except(new[] { indexMoves.Length &lt; 2 ? zeroIndex : indexMoves[indexMoves.Length - 2] }) .Select(indexMove =&gt; indexMoves.Append(indexMove).ToArray())) .ToArray(); } // Too many moves throw new Exception("Unsolvable puzzle."); } private bool TrySolution(int[] indexMoves, out int[] moveHistory) { int[] transformedPuzzle = _input.ToArray(); List&lt;int&gt; moveHistoryList = new List&lt;int&gt;(indexMoves.Length); foreach (int indexMove in indexMoves) { int move = transformedPuzzle[indexMove]; // swap cell values to simulate move transformedPuzzle[Array.IndexOf(transformedPuzzle, 0)] = move; transformedPuzzle[indexMove] = 0; moveHistoryList.Add(move); } moveHistory = moveHistoryList.ToArray(); return IsSolved(transformedPuzzle); } } </code></pre> <p><code>ResolverImplementation.cs</code></p> <pre><code>public class ResolverImplementation : IResolver { public int[] Solve(int[] input) =&gt; new Resolver(input).Solve(); } </code></pre> <h2>Unit tests</h2> <p>I've added NUnit tests to ensure my solution works.</p> <pre><code>public class ResolverTests { [Test] public void ShouldThrowArgumentNullException_WhenNullPassed() { // Arrange // Act // Assert Assert.Throws&lt;ArgumentNullException&gt;(() =&gt; new Resolver(null)); } [Test] public void ShouldThrowArgumentException_WhenWrongInputPassed() { // Arrange // Act // Assert Assert.Throws&lt;ArgumentException&gt;(() =&gt; new Resolver(new[] { -1, 2, 3, 0, 4, 5, 6, 7, 8, 9 }), "Invalid input."); } [Test] public void ShouldThrowArgumentException_WhenDuplicateElementsPassed() { // Arrange // Act // Assert Assert.Throws&lt;ArgumentException&gt;(() =&gt; new Resolver(new[] { 1, 2, 3, 0, 4, 5, 6, 7, 8, 9, 1 }), "Invalid input."); } [Test] public void ShouldReturnEmptyArray_WhenSolvedPuzzlePassed() { // Arrange Resolver resolver = new Resolver(new[] { 1, 2, 3, 0, 4, 5, 6, 7, 8, 9 }); // Act int[] solution = resolver.Solve(); // Assert Assert.AreEqual(solution, new int[0]); } [Test] public void ShouldReturnSolution_WhenSimplestSolutionPassed() { // Arrange Resolver resolver = new Resolver(new[] { 1, 2, 3, 4, 0, 5, 6, 7, 8, 9 }); // Act int[] solution = resolver.Solve(); // Assert Assert.AreEqual(solution, new[] { 4 }); } [Test] public void ShouldReturnSolution_WhenSimpleSolutionPassed() { // Arrange Resolver resolver = new Resolver(new[] { 1, 2, 3, 4, 6, 5, 0, 7, 8, 9 }); // Act int[] solution = resolver.Solve(); // Assert Assert.AreEqual(solution, new[] { 6, 4 }); } [Test] public void ShouldReturnSolution_WhenAverageSolutionPassed() { // Arrange Resolver resolver = new Resolver(new[] { 1, 2, 3, 4, 6, 5, 8, 9, 7, 0 }); // Act int[] solution = resolver.Solve(); // Assert Assert.AreEqual(solution, new[] { 9, 7, 8, 6, 4 }); } [Test] public void ShouldReturnSolution_WhenHardSolutionPassed() { // Arrange Resolver resolver = new Resolver(new[] { 8, 7, 9, 6, 5, 4, 1, 2, 0, 3 }); // Act int[] solution = resolver.Solve(); // Assert Assert.AreEqual(solution, new[] { 2, 4, 9, 6, 5, 1, 2, 3, 4, 9, 6, 8, 7, 1, 2, 3, 4, 9, 6, 8, 7, 1, 2, 3, 4, 6, 8, 7, 5, 3, 4, 6, 8, 7, 5, 3 }); } } </code></pre> <h2>Notes</h2> <p>I'm using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append" rel="nofollow noreferrer"><code>Append</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend" rel="nofollow noreferrer"><code>Prepend</code></a> LINQ methods in solution which are available in .NET Core, .NET Standard 1.6+, .NET Framework 4.7.1+. If you don't have specified versions of .NET you can add them manually like own extenstion methods like this.</p> <pre><code>public static class EnumerableExtensions { public static IEnumerable&lt;TSource&gt; Append&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, TSource element) =&gt; source.Concat(new[] { element }); public static IEnumerable&lt;TSource&gt; Prepend&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, TSource element) =&gt; new[] { element }.Concat(source); } </code></pre> <h2>Testing</h2> <p>For generating puzzle sequences and testing solutions I've added separate WPF application with single window where click on allowed cells near empty one swaps them.</p> <p><code>MainWindow.xaml</code></p> <pre><code>&lt;Window x:Class="Puzzle9.Game.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"&gt; &lt;Viewbox&gt; &lt;Canvas Width="150" Height="160"&gt; &lt;Canvas.Resources&gt; &lt;Style TargetType="Button"&gt; &lt;Setter Property="Foreground" Value="#5680a7" /&gt; &lt;Setter Property="HorizontalContentAlignment" Value="Center" /&gt; &lt;Setter Property="VerticalContentAlignment" Value="Center" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;Border x:Name="border" Width="20" Height="20" BorderThickness="1" BorderBrush="#5680a7" Background="{TemplateBinding Background}" SnapsToDevicePixels="true" CornerRadius="10"&gt; &lt;ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;Style TargetType="Line"&gt; &lt;Setter Property="Stroke" Value="#5680a7" /&gt; &lt;Setter Property="StrokeThickness" Value="1" /&gt; &lt;Setter Property="Panel.ZIndex" Value="-1" /&gt; &lt;/Style&gt; &lt;/Canvas.Resources&gt; &lt;Button Name="Button0" Canvas.Left="45" Canvas.Top="10" Click="Button_Click"&gt;1&lt;/Button&gt; &lt;Button Name="Button1" Canvas.Left="95" Canvas.Top="10" Click="Button_Click"&gt;2&lt;/Button&gt; &lt;Button Name="Button2" Canvas.Left="20" Canvas.Top="40" Click="Button_Click"&gt;3&lt;/Button&gt; &lt;Button Name="Button3" Canvas.Left="70" Canvas.Top="40" Click="Button_Click"&gt;&lt;/Button&gt; &lt;Button Name="Button4" Canvas.Left="120" Canvas.Top="40" Click="Button_Click"&gt;4&lt;/Button&gt; &lt;Button Name="Button5" Canvas.Left="20" Canvas.Top="70" Click="Button_Click"&gt;5&lt;/Button&gt; &lt;Button Name="Button6" Canvas.Left="120" Canvas.Top="70" Click="Button_Click"&gt;6&lt;/Button&gt; &lt;Button Name="Button7" Canvas.Left="45" Canvas.Top="100" Click="Button_Click"&gt;7&lt;/Button&gt; &lt;Button Name="Button8" Canvas.Left="95" Canvas.Top="100" Click="Button_Click"&gt;8&lt;/Button&gt; &lt;Button Name="Button9" Canvas.Left="70" Canvas.Top="130" Click="Button_Click"&gt;9&lt;/Button&gt; &lt;Line X1="55" Y1="20" X2="105" Y2="20" /&gt; &lt;Line X1="55" Y1="20" X2="30" Y2="50" /&gt; &lt;Line X1="105" Y1="20" X2="130" Y2="50"/&gt; &lt;Line X1="30" Y1="50" X2="130" Y2="50" /&gt; &lt;Line X1="30" Y1="50" X2="30" Y2="80" /&gt; &lt;Line X1="130" Y1="50" X2="130" Y2="80" /&gt; &lt;Line X1="30" Y1="80" X2="55" Y2="110" /&gt; &lt;Line X1="130" Y1="80" X2="105" Y2="110" /&gt; &lt;Line X1="55" Y1="110" X2="80" Y2="140" /&gt; &lt;Line X1="55" Y1="110" X2="105" Y2="110" /&gt; &lt;Line X1="105" Y1="110" X2="80" Y2="140" /&gt; &lt;/Canvas&gt; &lt;/Viewbox&gt; &lt;/Window&gt; </code></pre> <p><code>MainWindow.xaml.cs</code></p> <pre><code>using System.Linq; using System.Windows; using System.Windows.Controls; using Puzzle9.Core; namespace Puzzle9.Game { public partial class MainWindow : Window { public MainWindow() =&gt; InitializeComponent(); private void Button_Click(object sender, RoutedEventArgs e) { Button button = sender as Button; Canvas parent = button.Parent as Canvas; int currentIndex = parent.Children.IndexOf(button); Button zeroButton = parent.Children.OfType&lt;Button&gt;().First(b =&gt; b.Content == null); int zeroIndex = parent.Children.IndexOf(zeroButton); if (Resolver.AvailableMoveIndexes[zeroIndex].Contains(currentIndex)) { zeroButton.Content = button.Content; button.Content = null; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T07:46:22.530", "Id": "413204", "Score": "0", "body": "For the output array to record what happened, don't you need to add two numbers to the output array at each step?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T08:10:01.243", "Id": "413206", "Score": "1", "body": "@GeorgeBarwood No, swapping cells will always be with empty cell (shown with zero), so only one number per step will be enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T11:33:34.727", "Id": "413214", "Score": "0", "body": "I get it. One thing I would question is the use of \"Collection\" in names, e.g. GetIndexMovesCollection. IMO that is an awkward name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:49:08.047", "Id": "413267", "Score": "0", "body": "This is a silly job-interview question. I would refuse solvig it for being pointless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:50:17.817", "Id": "413268", "Score": "0", "body": "@t3chb0t I found solving this puzzle rather interesting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:53:09.267", "Id": "413270", "Score": "0", "body": "Maybe it's good as a _I can solve this puzzle game_ but it doesn't have any practical value and I have no idea what solving it in an inteview should prove." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:58:00.407", "Id": "413271", "Score": "1", "body": "@t3chb0t Maybe it can show how I can practically create algorithms, how maintainable and readable my code is and so on." } ]
[ { "body": "<blockquote>\n<pre><code> public static ReadOnlyDictionary&lt;int, int[]&gt; AvailableMoveIndexes =&gt; new ReadOnlyDictionary&lt;int, int[]&gt;\n (\n new Dictionary&lt;int, int[]&gt;\n {\n [0] = new[] { 1, 2 },\n ...\n</code></pre>\n</blockquote>\n\n<p>Nice clean representation, but why <code>public</code>? I would expect <code>private</code> or (perhaps better) <code>internal</code> with an <code>InternalsVisibleTo</code> attribute to allow a unit test to validate that the possible moves are bidirectional (i.e. <code>AvailableMoveIndexes[i].Contains(j)</code> if and only if <code>AvailableMoveIndexes[j].Contains(i)</code>).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private readonly ReadOnlyCollection&lt;int&gt; _input;\n</code></pre>\n</blockquote>\n\n<p>Why the name? I don't tend to think of objects as having input: programs and processes have input.</p>\n\n<p>Also, would <code>IReadOnlyList&lt;int&gt;</code> be a better type to use? It makes it explicit that the order is relevant.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Dictionary&lt;int, int&gt; minimumNumberOfMovesDictionary = new Dictionary&lt;int, int&gt;\n {\n [0] = 2,\n ...\n</code></pre>\n</blockquote>\n\n<p>For a dense lookup like this, IMO an <code>int[]</code> makes more sense.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (minimumNumberOfMoves == 0 &amp;&amp; IsSolved(_input)) return new int[0];\n</code></pre>\n</blockquote>\n\n<p>Is <code>minimumNumberOfMoves != 0 &amp;&amp; IsSolved(_input)</code> possible?</p>\n\n<p>Answer: no, so this could be simplified to <code>if (IsSolved(_input)) return new int[0];</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> const int maximumNumberOfMoves = 100;\n</code></pre>\n</blockquote>\n\n<p>Where does this number come from? Do you have a mathematical proof that it's exactly the maximum number required? Do you have a mathematical proof that the it's a valid upper bound? Or is it just a conservative guess?</p>\n\n<p>The answer to that question should be in a comment in the code.</p>\n\n<hr>\n\n<p>Here follow rhetorical questions, and to distinguish my answers / comments from the questions themselves I'm using spoiler blocks. These are the questions I would ask in an interview. I'd probably ask similar questions in a non-interview code review as well, if the person who wrote the code was a junior programmer, but I might give more hints up front in that case.</p>\n\n<blockquote>\n<pre><code> for (int moveCount = 1; moveCount &lt; maximumNumberOfMoves; moveCount++)\n {\n ...\n }\n</code></pre>\n</blockquote>\n\n<p>Since this is an interview question, you can expect to be asked what type of search you're doing. I would put a comment above the loop to answer that question.</p>\n\n<p>If I asked you why you chose that type of search, do you have an answer? If it was because you didn't have time to implement a better one, what would you have liked to implement?</p>\n\n<blockquote class=\"spoiler\">\n <p> Your response in comments was \"<em>Loop is used for solving puzzle from minimum to maximum moves.</em>\" The response I was hoping for was \"Breadth-first search\". I personally would have chosen to implement Dijkstra's algorithm or A*. It seems likely that one of the main reasons for setting this particular task is to see (a) whether you know standard algorithms; (b) whether you recognise when they're applicable.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code> // Remove combinations where subsequent move can undo previous move\n .Except(new[] { indexMoves.Length &lt; 2 ? zeroIndex : indexMoves[indexMoves.Length - 2] })\n</code></pre>\n</blockquote>\n\n<p>That gives a bit of optimisation by detecting and skipping loops of length 2, but loops of length 3 around positions 7,8,9 are still possible. How would you detect and skip loops of any length?</p>\n\n<blockquote class=\"spoiler\">\n <p> The straightforward way of doing that is to use a representation which supports hashcode and equality testing, and then to use a <code>HashMap&lt;&gt;</code> to track the positions which you've already seen.</p>\n</blockquote>\n\n<hr>\n\n<p>The memory usage is quite high. How could you change your data structure to minimise memory usage?</p>\n\n<blockquote class=\"spoiler\">\n <p> The reason that the memory usage is quite high is the copying of arrays to add an element to the end. You could instead use a linked list where each node points backwards instead of forwards; it would be necessary to reverse the list for output, but each element of <code>_indexMovesCollection</code> would require just one <code>int</code> (or even <code>byte</code>) for the last element and one reference to the previous element.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:38:04.537", "Id": "413350", "Score": "0", "body": "1) `AvailableMoveIndexes` is `public` because it is used in WPF application for manual puzzle generation and manual solving. 2) I don't understand why `IReadOnlyList<int>` would be better for private field `_input`. 3) `minimumNumberOfMoves != 0 && IsSolved(_input)` is not possible because `0` should reside only in index #3. 4) `100` is my guess, I don't have a clue how to calculate maximum number of moves or understand that puzzle is unsolvable. 5) Loop is used for solving puzzle from minimum to maximum moves. I don't have better idea to implement. 6) No idea about reducing memory usage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T11:15:30.963", "Id": "413353", "Score": "0", "body": "1) Good answer. 2) Because it makes it clear that the order matters. `ReadOnlyCollection` is not inherently ordered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:16:05.587", "Id": "213711", "ParentId": "213629", "Score": "9" } } ]
{ "AcceptedAnswerId": "213711", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T23:57:26.607", "Id": "213629", "Score": "5", "Tags": [ "c#", "interview-questions", "graph", "pathfinding" ], "Title": "Graph puzzle resolver" }
213629
<p>I have recently created an esoteric programming language called <strong>01</strong> and I will be grateful for a code review and any opinions or suggestions about the future of this language.</p> <p><a href="https://github.com/DeBos99/01" rel="nofollow noreferrer">GitHub</a></p> <pre><code>require 'securerandom' require 'optparse' COMMANDS=['&gt;','&lt;','+','-','.',',','[',']','0','1'] ERROR_NOT_IMPLEMENTED='Command "%s" not implemented in "%s".' ERROR_NOT_SUPPORTED='Language "%s" is not supported.' def error(e) puts 'Error: %s'%e exit end def _012c(lang,id,count) case lang when 'raw' return id*count when 'brainfuck' case id when '&gt;','&lt;','+','-','.',',','[',']' return id*count when '0' return '[-]' else error(ERROR_NOT_IMPLEMENTED%[id,lang]) end when 'c' case id when 'START' return "#include&lt;stdio.h&gt;\nmain(){char d[30000],*p=d;" when '&gt;' if count==1 then return 'p++;' else return "p+=#{count};" end when '&lt;' if count==1 then return 'p--;' else return "p-=#{count};" end when '+' if count==1 then return '(*p)++;' else return "(*p)+=#{count};" end when '-' if count==1 then return '(*p)--;' else return "(*p)-=#{count};" end when '.' return 'putchar(*p);'*count when ',' if count&lt;=2 then return 'scanf(\" %c\",&amp;p);'*count else return "for(int i=0;i&lt;#{count};i++)scanf(\" %c\",p);" end when '[' return 'while(*p){'*count when ']' return '}'*count when '0' return '*p=0;' when '1' return 'p=d[0];' when 'END' return '}' else error(ERROR_NOT_IMPLEMENTED%[id,lang]) end when 'c++' case id when 'START' return "#include &lt;iostream&gt;\nmain(){char d[30000],*p=d;" when '&gt;' if count==1 then return 'p++;' else return "p+=#{count};" end when '&lt;' if count==1 then return 'p--;' else return "p-=#{count};" end when '+' if count==1 then return '(*p)++;' else return "(*p)+=#{count};" end when '-' if count==1 then return '(*p)--;' else return "(*p)-=#{count};" end when '.' if count==1 then return "std::cout&lt;&lt;*p;" else return "std::cout&lt;&lt;std::string(#{count},*p);" end when ',' if count&lt;=2 then return 'std::cin&gt;&gt;*p;'*count else return "for(int i=0;i&lt;#{count};i++)std::cin&gt;&gt;*p;" end when '[' return 'while(*p){'*count when ']' return '}'*count when '0' return '*p=0;' when '1' return 'p=d[0];' when 'END' return '}' else error(ERROR_NOT_IMPLEMENTED%[id,lang]) end when 'ruby' case id when 'START' return 'd=[0]*30000;p=0;' when '&gt;' return "p+=#{count};" when '&lt;' return "p-=#{count};" when '+' return "d[p]+=#{count};" when '-' return "d[p]-=#{count};" when '.' if count==1 then return 'print d[p].chr;' else return "print d[p].chr*#{count};" end when ',' if count==1 then return 'd[p]=gets.ord;' elsif count==2 then return 'gets;d[p]=gets.ord;' else return "#{count-1}.times{gets};d[p]=gets.ord;" end when '[' return 'while d[p]&gt;0;'*count when ']' return 'end;'*count when '0' return 'd[p]=0;' when '1' return 'p=0;' when 'END' return '' end else error(ERROR_NOT_SUPPORTED%lang) end end def _012(input,output,lang) id=0 last='' count=0 File.open(output,'w') do |f2| f2&lt;&lt;_012c(lang,'START',0) File.open(input,'r') do |f| while not f.eof? c=f.read(1) if c=='0' then if last=='1' then f2&lt;&lt;_012c(lang,COMMANDS[id],count) count=1 end id+=id==COMMANDS.length-1?-id:1 elsif c=='1' then if c==last or count==0 then count+=1 end end last=c end if last=='1' then f2&lt;&lt;_012c(lang,COMMANDS[id],count) count=1 end end f2&lt;&lt;_012c(lang,'END',0) end end def _201(input,output) last=0 File.open(input,'r') do |f| File.open(output,'w') do |f2| while not f.eof? c=f.read(1) if not COMMANDS.include?(c) then next end i=COMMANDS.index(c) if last&lt;=i then f2&lt;&lt;'0'*(i-last) else f2&lt;&lt;'0'*(COMMANDS.length-last+i) end f2&lt;&lt;'1' last=i end end end end def minify(input,output) pipe=SecureRandom.hex(32) _012(input,pipe,'raw') _201(pipe,output) File.delete(pipe) end OptionParser.new do |parser| options={} parser.on('-i','--input INPUT','Set INPUT file for program'){|x|options[:input]=x} parser.on('-o','--output OUTPUT','Set OUTPUT file for program'){|x|options[:output]=x} parser.on('-m', '--minify', 'Minify INPUT and get result in OUTPUT') do |x| if not options[:input] or not options[:output] then raise OptionParser::MissingArgument end minify(options[:input],options[:output]) end parser.on('-c', '--convert LANG', 'Convert *.zo file to other LANG file') do |x| if not options[:input] or not options[:output] then raise OptionParser::MissingArgument end _012(options[:input],options[:output],x) end parser.on('-g', '--generate', 'Convert *.tzo to *.zo file') do |x| if not options[:input] or not options[:output] then raise OptionParser::MissingArgument end _201(options[:input],options[:output]) end end.parse! </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T00:31:00.563", "Id": "213633", "Score": "2", "Tags": [ "ruby", "parsing" ], "Title": "Esoteric programming language in Ruby" }
213633
<p>I am trying to print out numbers by increasing positive and negative values around a center number, and I don't think I've found the best way. For example, say I want to find what number in a list my center value is closest to. I do that by adding one, see if it matches, then subtracting one from the original number and see if that matches, then add two from the original number and so on. I know there are other ways of finding the closest match but I'm not looking for that - I'm looking for the best way to print out numbers steadily getting farther from a center value. Here's my code:</p> <pre><code>def inc_val(center, i, neg_toggle): mult = 1 if neg_toggle: neg_toggle = False mult = -1 else: neg_toggle = True mult = 1 i += 1 val = center + (i * mult) return val, i, neg_toggle i = 0 center = 24 val = center neg_toggle = False my_set = {30, 50, 90} while val not in my_set: print(val) val, i, neg_toggle = inc_val(center, i, neg_toggle) </code></pre> <p>This prints out the following list, as desired:</p> <pre><code>24 25 23 26 22 27 21 28 20 29 19 </code></pre> <p>To be clear, I'm interested in the incrementing numbers. The <code>while not in my_set</code> part is just to illustrate. I am not intentionally trying to re-invent anything, so if there's a built-in or simpler way to do this, please let me know.</p>
[]
[ { "body": "<p>Rather than maintaining the state of the iteration using three variables <code>val</code>, <code>i</code>, and <code>neg_toggle</code>, it would be more elegant to write a <a href=\"https://docs.python.org/3/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">generator</a>. Then, the state of the iteration would be maintained by the flow of the execution of the generator itself.</p>\n\n<pre><code>def zoom_out(center):\n decr = center\n incr = center + 1\n while True:\n yield decr\n decr -= 1\n yield incr\n incr += 1\n\nfor n in zoom_out(24):\n if n in (30, 50, 90):\n break\n print(n)\n</code></pre>\n\n<p>Furthermore, fancy iteration can often be expressed more elegantly using <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a>. Here, I'd take advantage of <code>itertools.count()</code> to implement the generator, and <code>itertools.takewhile()</code> to detect when to stop executing the infinite generator.</p>\n\n<pre><code>from itertools import count, takewhile\n\ndef zoom_out(center):\n decr = count(center, -1)\n incr = count(center + 1)\n while True:\n yield next(decr)\n yield next(incr)\n\nfor n in takewhile(lambda n: n not in (30, 50, 90), zoom_out(24)):\n print(n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T06:26:27.957", "Id": "213639", "ParentId": "213635", "Score": "1" } } ]
{ "AcceptedAnswerId": "213639", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T02:44:19.010", "Id": "213635", "Score": "2", "Tags": [ "python" ], "Title": "Print out numbers of increasing distance from center value in Python" }
213635
<p>I would like feedback on the correctness and performance of this code.</p> <p>My priorities are also are readability, simplicity and self-documenting code - but I'm happy with those as they are.</p> <p>I still need to do some factoring of common code between the two input lines - but I'm brushing up my C and will do that.</p> <p>RA2 and RA3 are the two digital input lines. My algorithm is not dissimilar to how debouncing would be done with a low pass capacitor and resistor followed by a schmitt trigger. This function is called by the ISR every 0.5ms, and the rotary switch produces transitions as short as 5-10ms.</p> <p>I am curious how to deal with situations where the rotary switch is turned a bit faster than the algorithm can process. Can further information be deduced from the Gray encoding, even when a step is missed because of the low pass delay and limited sample rate? I suppose this could be taken as far as using neural networks?!</p> <p>I'm mainly asking this question because I think the running time and the amount of code of the below can both be reduced by a factor of two at least. And I'd just prefer not to get out the logic analyzer and completely reinvent the wheel.</p> <p><strong><em>rotsw.h</em></strong></p> <pre><code>#define ROTSW_AVG_SIZE 8 #define ROTSW_MAX 7 #define ROTSW_UPPER 5 #define ROTSW_LOWER 2 #define ROTSW_MIN 0 void rotsw_sample_avg_schmitt_count(); extern volatile int rotsw_count_steps; </code></pre> <p><strong><em>rotsw.c</em></strong></p> <pre><code>unsigned int rotsw_samples[ROTSW_AVG_SIZE]; unsigned char rotsw_write_idx = 0; int rotsw_avg_ra2 = 0; int rotsw_avg_ra3 = 0; int ra2 = 0; int ra3 = 0; volatile int rotsw_count = 0; void rotsw_sample_avg_schmitt_count() { int sample, old_sample, ra2_changed, ra3_changed, count = rotsw_count; // Sample RA2 and RA3 old_sample = rotsw_samples[rotsw_write_idx]; rotsw_samples[rotsw_write_idx] = sample = PORTA &amp; 0b00001100; if (++rotsw_write_idx &gt;= ROTSW_AVG_SIZE) rotsw_write_idx = 0; // Moving average, turning digital sample to "analogue" if (old_sample &amp; 0x04) rotsw_avg_ra2--; if (old_sample &amp; 0x08) rotsw_avg_ra3--; if (sample &amp; 0x04) rotsw_avg_ra2++; if (sample &amp; 0x08) rotsw_avg_ra3++; // 3. Do limit for Schmitt trigger if (rotsw_avg_ra2 &lt; ROTSW_MIN) rotsw_avg_ra2 = ROTSW_MIN; else if (rotsw_avg_ra2 &gt; ROTSW_MAX) rotsw_avg_ra2 = ROTSW_MAX; if (rotsw_avg_ra3 &lt; ROTSW_MIN) rotsw_avg_ra3 = ROTSW_MIN; else if (rotsw_avg_ra3 &gt; ROTSW_MAX) rotsw_avg_ra3 = ROTSW_MAX; // Do Schmitt trigger if (rotsw_avg_ra2 &gt; ROTSW_UPPER){ ra2_changed = !ra2; ra2 = 1; } else if (rotsw_avg_ra2 &lt; ROTSW_LOWER){ ra2_changed = ra2; ra2 = 0; } if (rotsw_avg_ra3 &gt; ROTSW_UPPER){ ra3_changed = !ra3; ra3 = 1; } else if (rotsw_avg_ra3 &lt; ROTSW_LOWER){ ra3_changed = ra3; ra3 = 0; } // Do rotsw state change count. if (ra2_changed){ if (ra2 == ra3) count++; else count--; } if (ra3_changed){ if(ra2 == ra3) count--; else count++; } rotsw_count = count; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>I don't see why bother with clipping averages. If something was less than <code>ROTSW_MIN</code>, it is also less than <code>ROTSW_LOWER</code>.</p></li>\n<li><p><code>count</code> is useless, you may operate directly on <code>rotsw_count</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>The moving averages <em>could</em> be computed a bit faster in assembly. The <code>rotsw_samples</code> array effectively contains 8 2-bit entries, and hence could be stored in a 16-bit register, say <code>R</code>. Now consider something along the lines of</p>\n\n<pre><code> rlc R ; Shift the ra2 of the \"old sample\" into carry\n sbc avg_ra2, $0 ; Subtract carry\n rlc R ; Same for ra3\n sbc avg_ra3, $0\n\n or R, sample ; New sample is added to the \"array\"\n\n rrc sample ; Shift ra3 of the \"new sample\" into carry\n adc avg_ra3, $0 ; Add carry\n rrc sample ; Same for ra2\n adc avg_ra2, $0 \n</code></pre>\n\n<p>The exact syntax depends on the architecture and an assembler; it also assumes that the sample is already shifted right by 2.</p>\n\n<p>Your target architecture may allow even faster variants.</p>\n\n<p>Note that the similar tricks could be used to speed up the final <code>rotsw_count</code> computation.</p>\n\n<hr>\n\n<p>There is not enough context to address your worries about the switch being too speedy. In any case, the code is already quite fast. If doesn't keep up with the peripheral, the best answer is to upgrade the CPU. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T07:05:41.470", "Id": "213642", "ParentId": "213636", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T04:24:51.760", "Id": "213636", "Score": "2", "Tags": [ "performance", "algorithm", "c", "event-handling", "device-driver" ], "Title": "De-bouncing a (Gray) Rotary Encoder Switch in C" }
213636
<p>I'm new to Go and wanted to implement a web server using system calls to get a better feel for how everything works.</p> <p>I'm looking for feedback on idiomatic go especially error handling and using pointers.</p> <p>I'm not particularly concerned about the completeness of the code. The primary goal was to learn syscalls in go.</p> <pre><code>package main // Simple, single-threaded server using system calls instead of the net library. // // Omitted features from the go net package: // // - TLS // - Most error checking // - Only supports bodies that close, no persistent or chunked connections // - Redirects // - Deadlines and cancellation // - Non-blocking sockets import ( "bufio" "errors" "flag" "io" "log" "net" "net/textproto" "os" "strconv" "strings" "syscall" ) // netSocket is a file descriptor for a system socket. type netSocket struct { // System file descriptor. fd int } func (ns netSocket) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } n, err := syscall.Read(ns.fd, p) if err != nil { n = 0 } return n, err } func (ns netSocket) Write(p []byte) (int, error) { n, err := syscall.Write(ns.fd, p) if err != nil { n = 0 } return n, err } // Creates a new netSocket for the next pending connection request. func (ns *netSocket) Accept() (*netSocket, error) { // syscall.ForkLock doc states lock not needed for blocking accept. nfd, _, err := syscall.Accept(ns.fd) if err == nil { syscall.CloseOnExec(nfd) } if err != nil { return nil, err } return &amp;netSocket{nfd}, nil } func (ns *netSocket) Close() error { return syscall.Close(ns.fd) } // Creates a new socket file descriptor, binds it and listens on it. func newNetSocket(ip net.IP, port int) (*netSocket, error) { // ForkLock docs state that socket syscall requires the lock. syscall.ForkLock.Lock() // AF_INET = Address Family for IPv4 // SOCK_STREAM = virtual circuit service // 0: the protocol for SOCK_STREAM, there's only 1. fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0) if err != nil { return nil, os.NewSyscallError("socket", err) } syscall.ForkLock.Unlock() // Allow reuse of recently-used addresses. if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil { syscall.Close(fd) return nil, os.NewSyscallError("setsockopt", err) } // Bind the socket to a port sa := &amp;syscall.SockaddrInet4{Port: port} copy(sa.Addr[:], ip) if err = syscall.Bind(fd, sa); err != nil { return nil, os.NewSyscallError("bind", err) } // Listen for incoming connections. if err = syscall.Listen(fd, syscall.SOMAXCONN); err != nil { return nil, os.NewSyscallError("listen", err) } return &amp;netSocket{fd: fd}, nil } type request struct { method string // GET, POST, etc. header textproto.MIMEHeader body []byte uri string // The raw URI from the request proto string // "HTTP/1.1" } func parseRequest(c *netSocket) (*request, error) { b := bufio.NewReader(*c) tp := textproto.NewReader(b) req := new(request) // First line: parse "GET /index.html HTTP/1.0" var s string s, _ = tp.ReadLine() sp := strings.Split(s, " ") req.method, req.uri, req.proto = sp[0], sp[1], sp[2] // Parse headers mimeHeader, _ := tp.ReadMIMEHeader() req.header = mimeHeader // Parse body if req.method == "GET" || req.method == "HEAD" { return req, nil } if len(req.header["Content-Length"]) == 0 { return nil, errors.New("no content length") } length, err := strconv.Atoi(req.header["Content-Length"][0]) if err != nil { return nil, err } body := make([]byte, length) if _, err = io.ReadFull(b, body); err != nil { return nil, err } req.body = body return req, nil } func main() { ipFlag := flag.String("ip_addr", "127.0.0.1", "The IP address to use") portFlag := flag.Int("port", 8080, "The port to use.") flag.Parse() ip := net.ParseIP(*ipFlag) port := *portFlag socket, err := newNetSocket(ip, port) defer socket.Close() if err != nil { panic(err) } log.Print("===============") log.Print("Server Started!") log.Print("===============") log.Print() log.Printf("addr: http://%s:%d", ip, port) for { // Block until incoming connection rw, e := socket.Accept() log.Print() log.Print() log.Printf("Incoming connection") if e != nil { panic(e) } // Read request log.Print("Reading request") req, err := parseRequest(rw) log.Print("request: ", req) if err != nil { panic(err) } // Write response log.Print("Writing response") io.WriteString(rw, "HTTP/1.1 200 OK\r\n"+ "Content-Type: text/html; charset=utf-8\r\n"+ "Content-Length: 20\r\n"+ "\r\n"+ "&lt;h1&gt;hello world&lt;/h1&gt;") if err != nil { log.Print(err.Error()) continue } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T13:48:39.890", "Id": "413223", "Score": "0", "body": "I edited your question because the sentence I rephrased made the question sound off-topic (which I don't believe it is.) If you feel the edit is in error please feel free to revert it or possibly rephrase on your own." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T07:10:20.313", "Id": "213643", "Score": "2", "Tags": [ "go", "networking", "socket", "server" ], "Title": "Web server using syscalls in Go" }
213643
<p>I have just finished my minesweeper game using tkinter and would like to know how I could improve my program.</p> <pre><code>from tkinter import * from tkinter import messagebox from random import randint class setupwindow(): def __init__(window): #window is the master object of the setup window window.root = Tk() window.root.title("Setup") window.root.grid() window.finish = "N" labels = ["Height:", "Width:", "Mines:"] window.label = ["","",""] window.entry = ["","",""] for i in range(3): window.label[i] = Label(text = labels[i]) window.label[i].grid(row = i, column = 1) window.entry[i] = Entry() window.entry[i].grid(row = i, column = 2) window.startbutton = Button(text = "Start", command = lambda: setupwindow.onclick(window)) window.startbutton.grid(column = 2) window.root.mainloop() def onclick(window): setupwindow.verification(window) if window.verf == "Y": window.finish = "Y" window.root.destroy() return window def verification(window): height = window.entry[0].get() width = window.entry[1].get() mines = window.entry[2].get() window.verf = "N" if height.isdigit() and width.isdigit() and mines.isdigit(): height = int(height) width = int(width) mines = int(mines) if height &gt; 0 and height &lt;= 24: totalsquares = height * width if width &gt; 0 and width &lt;= 48: if mines &gt; 0: if mines &lt; totalsquares: window.verf = "Y" window.height = height window.width = width window.mines = mines else: messagebox.showerror("Invalid", "You cannot have more mines than squares!") else: messagebox.showerror("Invalid", "You can't play minesweeper without mines!") else: messagebox.showerror("Invalid", "Width must be between 1 and 48 inclusive") else: messagebox.showerror("Invalid", "Height must be between 1 and 24 inclusive") else: messagebox.showerror("Invalid", "All values must be integers") class gamewindow(): def __init__(s, setup): #s is the master object of the main game s.height = setup.height s.width = setup.width s.mines = setup.mines s.root = Tk() s.root.title("Minesweeper") s.root.grid() s.finish = "N" s.maingrid = list() for i in range(s.height): s.maingrid.append([]) for x in range(s.width): s.maingrid[i].append(" ") s.maingrid[i][x] = Button(height = 0, width = 3, font = "Calibri 15 bold", text = "", bg = "gray90", command = lambda i=i, x=x: gamewindow.onclick(s, i, x)) s.maingrid[i][x].bind("&lt;Button-3&gt;", lambda event="&lt;Button-3&gt;", i=i, x=x: gamewindow.rightclick(event, s, i, x)) s.maingrid[i][x].grid(row = i, column = x) s.maingrid[i][x].mine = "False" totalsquares = s.height * s.width s.scoreneeded = totalsquares - s.mines s.score = 0 indexlist = list() for i in range(totalsquares): indexlist.append(i) spaceschosen = list() #where the mines are going to be for i in range(s.mines): chosenspace = randint(0, len(indexlist) - 1) spaceschosen.append(indexlist[chosenspace]) del indexlist[chosenspace] for i in range(len(spaceschosen)): xvalue = int(spaceschosen[i] % s.width) ivalue = int(spaceschosen[i] / s.width) s.maingrid[ivalue][xvalue].mine = "True" s.root.mainloop() def onclick(s, i, x): colourlist = ["PlaceHolder", "Blue", "Green", "Red", "Purple", "Black", "Maroon", "Gray", "Turquoise"] if s.maingrid[i][x]["text"] != "F" and s.maingrid[i][x]["relief"] != "sunken": if s.maingrid[i][x].mine == "False": s.score += 1 combinationsi = [1, -1, 0, 0, 1, 1, -1, -1] combinationsx = [0, 0, 1, -1, 1, -1, 1, -1] #All the surrounding spaces minecount = 0 for combinations in range(len(combinationsi)): tempi = i + combinationsi[combinations] tempx = x + combinationsx[combinations] if tempi &lt; s.height and tempx &lt; s.width and tempi &gt;= 0 and tempx &gt;= 0: if s.maingrid[tempi][tempx].mine == "True": minecount = minecount + 1 if minecount == 0: minecount = "" s.maingrid[i][x].configure(text = minecount, relief = "sunken", bg = "gray85") if str(minecount).isdigit(): s.maingrid[i][x].configure(fg = colourlist[minecount]) if minecount == "": for z in range(len(combinationsi)): if s.finish == "N": ivalue = i + int(combinationsi[z]) xvalue = x + int(combinationsx[z]) if ivalue &gt;= 0 and ivalue &lt; s.height and xvalue &gt;=0 and xvalue &lt; s.width: if s.maingrid[ivalue][xvalue]["relief"] != "sunken": gamewindow.onclick(s, ivalue, xvalue) if s.score == s.scoreneeded and s.finish == "N": messagebox.showinfo("Congratulations", "A winner is you!") s.finish = "Y" s.root.destroy() else: s.maingrid[i][x].configure(bg = "Red", text = "*") for a in range(len(s.maingrid)): for b in range(len(s.maingrid[a])): if s.maingrid[a][b].mine == "True": if s.maingrid[a][b]["text"] == "F": s.maingrid[a][b].configure(bg = "Green") elif s.maingrid[a][b]["bg"] != "Red": s.maingrid[a][b].configure(bg = "Pink", text = "*") elif s.maingrid[a][b]["text"] == "F": s.maingrid[a][b].configure(bg = "Yellow") messagebox.showinfo("GAME OVER", "You have lost") s.root.destroy() def rightclick(event, s, i, x): if s.maingrid[i][x]["relief"] != "sunken": if s.maingrid[i][x]["text"] == "": s.maingrid[i][x].config(text = "F") elif s.maingrid[i][x]["text"] == "F": s.maingrid[i][x].config(text = "?") else: s.maingrid[i][x].config(text = "") if __name__ == "__main__": setup = setupwindow() if setup.finish == "Y": game = gamewindow(setup) quit() </code></pre>
[]
[ { "body": "<ol>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a></p>\n\n<ul>\n<li><p>Class names should normally use the CapWords convention. <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">#class-names</a></p></li>\n<li><p>Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter. <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">#whitespaces</a></p></li>\n<li><p>Always use self for the first argument to instance methods. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\" rel=\"nofollow noreferrer\">#function-and-method-arguments</a></p></li>\n<li><p>There are other PEP-8 violations. Read complete document</p></li>\n</ul></li>\n<li><p><a href=\"https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">Guard clause</a></p>\n\n<p><a href=\"https://medium.com/softframe/what-are-guard-clauses-and-how-to-use-them-350c8f1b6fd2\" rel=\"nofollow noreferrer\">What are guard clauses and how to use them?</a></p></li>\n<li><p>Do not use <code>for i in range(len(list))</code> until you need it. Even if you need it use <code>enumerate</code> instead.</p>\n\n<ul>\n<li><a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Loop Like A Native</a></li>\n<li><a href=\"https://stackoverflow.com/questions/11901081/only-index-needed-enumerate-or-xrange\">https://stackoverflow.com/questions/11901081/only-index-needed-enumerate-or-xrange</a></li>\n</ul></li>\n<li><p>Convert <code>range</code> to <code>list</code></p></li>\n</ol>\n\n<pre><code> indexlist = list()\n for i in range(totalsquares):\n indexlist.append(i)\n</code></pre>\n\n<p>is equivalent to\n<code>indexlist = list(range(totalsquares))</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T21:56:07.603", "Id": "413463", "Score": "0", "body": "Thanks for the feedback however I'm unsure which part of the program you are referring to when you mentioned white spaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:41:41.657", "Id": "413609", "Score": "0", "body": "It's about functions/constructor calls like `.grid(row=i, column=x)`, `.config(text=\"F\")` and `Button(height=0, width=3, ...)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:14:11.440", "Id": "213652", "ParentId": "213648", "Score": "2" } } ]
{ "AcceptedAnswerId": "213652", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T12:59:20.153", "Id": "213648", "Score": "3", "Tags": [ "python", "tkinter", "minesweeper" ], "Title": "Python 3 minesweeper tkinter game" }
213648
<p>I was wondering if there is a better way to write the following code? The code is working, I am looking for better technique to achieve the functionality, if any exists. Never mind the classes that are not shown, indentation, class names, etc. I am focused mostly on the functionality.</p> <p><a href="https://jsfiddle.net/ekareem/tsnmrv12/59/" rel="nofollow noreferrer">JsFilddle</a></p> <pre><code>&lt;ul class="list-unstyled"&gt; &lt;li&gt; &lt;a href="#ulExpCol_1" data-toggle="collapse" data-link="#item_1" onclick="$('#thisCollapsedChevron_1').toggleClass('fa-rotate-90')"&gt; &lt;i class="zz_TreeParent" id="thisCollapsedChevron_1"&gt;&lt;/i&gt; Top Tree Node &lt;/a&gt; &lt;ul id="ulExpCol_1" class="ml-3 list-unstyled collapse"&gt; &lt;li&gt; &lt;a href="#ulExpCol_2" data-toggle="collapse" data-link="#item_1-1" onclick="$('#thisCollapsedChevron_2').toggleClass('fa-rotate-90')"&gt; &lt;i class="zz_TreeParent" id="thisCollapsedChevron_2"&gt;&lt;/i&gt; Child 1 &lt;/a&gt; &lt;!--Child 1 --&gt; &lt;ul id="ulExpCol_2" class="ml-3 list-unstyled collapse"&gt; &lt;li&gt; &lt;a href="#item_1-1-1" class="zz_TreeLeaf"&gt; Child 1.1 &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/li&gt; &lt;li&gt; &lt;a href="#item_2" class="zz_TreeLeaf"&gt; Last Node &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T16:22:40.027", "Id": "413249", "Score": "1", "body": "Welcome to Code Review! (The `Enhance code` part of the title is somewhat implicit here.) `Never mind [some aspects of the code]. I am focused [on one particular one]` OK as far as you respect [any aspect of the code posted being fair game for feedback and criticism](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T05:53:51.417", "Id": "413323", "Score": "0", "body": "@greybeard, I appreciate the comment." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T13:02:40.263", "Id": "213649", "Score": "1", "Tags": [ "javascript", "jquery", "html5", "twitter-bootstrap" ], "Title": "Collapsible left-side tree" }
213649
<p>The task:</p> <blockquote> <p>Given a string of words delimited by spaces, reverse the words in string. For example, given "hello world here", return "here world hello"</p> <p>Follow-up: given a mutable string representation, can you perform this operation in-place?</p> </blockquote> <p>My solution:</p> <pre><code>const reverseStr = s =&gt; s.split(' ').reverse().join(' '); console.log(reverseStr("hello world here")); </code></pre> <p>My "in-place" solution:</p> <pre><code>const reverseStrInPlace = s =&gt; { let exp = `\\w+$`; const startLen = s.lastIndexOf(s.match(/\w+$/)[0]); const strLen = s.length; const len = (s.match(/\s/g) || []).length; for (let i = 0; i &lt; len; i++) { exp = `(\\w+)\\s${exp}`; s += ` ${s.match(new RegExp(exp), 'g')[1]}`; exp = `(\\w+)\\s${exp}`; } return s.substring(startLen, startLen + strLen); } console.log(reverseStrInPlace('hello world here')); </code></pre> <p>"In-place" algorithms are defined as:</p> <blockquote> <p>An in-place algorithm transforms the input without using any extra memory. As the algorithm executes, the input is usually overwritten by the output and no additional space is needed for this operation.</p> </blockquote> <p>Not sure whether this is the right approach for the in-place solution, because, even though I didn't create for the string a new datastructure, i.e. during the operation I overwrite the input and return the overwritten input as the output, but I created other variables, e.g. <code>exp</code>, <code>len</code>, <code>i</code>, etc. i.e. additional space is created for the operation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:36:52.947", "Id": "413229", "Score": "0", "body": "Array `reverse` is mutating, \"in-place\" method. Strings are immutable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:37:25.047", "Id": "413230", "Score": "0", "body": "In Javascript strings are a basic type and thus can only be copied. You can not modify a string inplace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:48:09.680", "Id": "413232", "Score": "0", "body": "Ah, true. In Java as well. How would you have solved it and with what language? @Blindman67" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T15:31:28.423", "Id": "413239", "Score": "0", "body": "For performance C or C++, for on the spot solution JavaScript, for when hell freezes over I would create a complicated reverse string class and supporting eco in Java, cut of my ARM, and cry. Sorry I hate Java and would never use it unless there was absolutely no other option (which is never the case)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T15:32:49.050", "Id": "413240", "Score": "0", "body": "Why do you hate Java so much? @Blindman67" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T15:57:33.723", "Id": "413243", "Score": "0", "body": "Long and complicated history of disappointment and frustration. Main reason, the VM, it's full of holes and why use a low level like language that needs a JIT compiler. There are very few apps that need to run on every machine under there sun, and if you do, modern C/C++ compilers can compile to more targets than there are Java VM" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T16:16:53.210", "Id": "413247", "Score": "0", "body": "@Blindman67 I guess I have to experience these frustration myself yet" } ]
[ { "body": "<p>Disclaimer: I am not a JavaScripter.</p>\n\n<p>The <code>exp</code> grows inside the loop, and is not bound by a constant; ditto for <code>s</code>. This immediately disqualifies the solution as in-place. Besides, the time complexity (as it matches the growing string in the loop) seems quadratic.</p>\n\n<p>A true in-place algorithm, with linear time complexity, starts with reversing the entire string:</p>\n\n<pre><code>ereh dlrow olleh\n</code></pre>\n\n<p>Now the words are in the desired order, but are themselves reversed. The only thing left is to reverse individual words.</p>\n\n<p>Implementing a linear time in-place (sub)string reversal is left as an exercise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:25:51.357", "Id": "413331", "Score": "0", "body": "Then I guess this is not possible to solve in JS, Because reversing you need either a new array or a new string. (in JS strings are immutable; not sure how you could emulate this in JS and how it would look differently than the first solution in my OP)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:30:00.160", "Id": "413332", "Score": "0", "body": "@thadeuszlay In the wild (say, during an interview) I would accept converting a string to an array first. After all, it is the algorithmic question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:47:51.387", "Id": "213664", "ParentId": "213651", "Score": "1" } }, { "body": "<p>In javascript, strings are <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access\" rel=\"nofollow noreferrer\">immutable</a> </p>\n\n<blockquote>\n <p>For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\">Object.defineProperty()</a> for more information.)</p>\n</blockquote>\n\n<p>So this was either a trick question or the creator was not aware.</p>\n\n<p>The only \"mutable string representation\" of a javascript string would be an array.</p>\n\n<p>So if the question accepts using an array as the representation of the string, you could do something like this:</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 reverse(str){\n const mutable = str.split(\"\");\n \n for(let i = 0; i &lt; mutable.length/2; i++){\n const j = mutable.length-1-i;\n const c = mutable[i];\n mutable[i] = mutable[j];\n mutable[j] = c;\n }\n \n return mutable.join(\"\");\n}\n\nconst res = reverse(\"hello world\");\n\nconsole.log(res);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T06:38:39.730", "Id": "413938", "Score": "1", "body": "Good idea to loop only to the middle of the array!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T16:50:48.210", "Id": "213736", "ParentId": "213651", "Score": "2" } } ]
{ "AcceptedAnswerId": "213736", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T13:56:26.737", "Id": "213651", "Score": "2", "Tags": [ "javascript", "algorithm", "ecmascript-6" ], "Title": "Reverse the words in string" }
213651
<p>I'm a self-taught programmer and I'm in the process of developing a simple 2D Isometric game. There is next to no game content yet and I've been focusing on creating solid "foundation" first if you will, and I'm here to get some code reviews on the structure of the source code.</p> <ul> <li>Is it clean</li> <li>Am I using proper coding conventions?</li> <li>What can I do better? (For this project)</li> </ul> <p>Summary</p> <ul> <li>initialize game(.h) from main.cpp</li> <li>from game.h I instantiate Engine class with title, window size, fps variable and fullscreen boolean.</li> <li>After engine is instantiated I instantiate the GUI class.</li> <li>Once Engine and GUI class are instantiated, instantiate game loop that updates game events and handles game states.</li> <li>The event system is inside the engine class, and I use forward declaration for engine class so that different game systems can access it, I heard it speeds up compilation time. <strong>Not sure if I did forward declaration correctly though, or if I got the right idea about this. Would especially like to have this reviewed*</strong></li> <li>GUI class uses graphics class, again using forward declaration and <strong><em>same as before, is this correct usage? Do I have the right idea about this concept?</em></strong></li> <li>Timer and Input class are the same as Engine and Graphics class, forward declaration, and same as before, this is what I would especially like reviewed.</li> </ul> <p>Other than that, in general how does this "design"/"structure" look to you? Ugly? Pretty? etc.</p> <p>The code is also <a href="https://github.com/MatiasMunk/ISO-Game/tree/14f213a0ba891c09a6a00362e16bdec7c45a2aec" rel="nofollow noreferrer">on GitHub</a>.</p> <p>File Structure</p> <pre><code>**Header files:** engine/fwd/ -engine.h -graphics.h -input.h -timer.h engine/ -engine.h -graphics.h -input.h -timer.h / -game.h -gui.h -spritesheet.h -stdafx.h **Source files:** engine/ -engine.cpp -graphics.cpp -input.cpp -timer.cpp / -main.cpp -game.cpp -gui.cpp -spritesheet.cpp </code></pre> <p>stdafx.h</p> <pre><code>#ifndef STDAFX_H #define STDAFX_H #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;array&gt; #include &lt;vector&gt; #include &lt;chrono&gt; #include &lt;ctime&gt; #include &lt;iomanip&gt; #include &lt;allegro5/allegro.h&gt; #include &lt;allegro5/allegro_primitives.h&gt; #include &lt;allegro5/allegro_image.h&gt; #include &lt;allegro5/allegro_audio.h&gt; #include &lt;allegro5/allegro_acodec.h&gt; #include &lt;allegro5/allegro_font.h&gt; #include &lt;allegro5/allegro_ttf.h&gt; #include "engine/fwd/engine.h" #include "engine/fwd/graphics.h" #include "engine/fwd/input.h" #include "engine/fwd/timer.h" #include "engine/fwd/map.h" #include "engine/engine.h" #include "engine/graphics.h" #include "engine/input.h" #include "engine/timer.h" #include "engine/map.h" #include "game.h" #include "gui.h" #include "spritesheet.h" #endif </code></pre> <p>Main.cpp</p> <pre><code>#include "game.h" int main() { game_initialize(); game_loop(); game_cleanup(); return 0; } </code></pre> <p>Game.h</p> <pre><code>#ifndef GAME_H #define GAME_H #include "stdafx.h" typedef enum { GAME_STATE_MENU, GAME_STATE_PLAY, } GAME_STATE; bool game_initialize(); void game_loop(); void game_cleanup(); void handle_game_state(); void do_game_events(); extern Engine* engine; #endif </code></pre> <p>Game.cpp</p> <pre><code>#include "game.h" Engine* engine; GAME_STATE game_state; GUI* gui; Map* map; std::string keyboard_string = ""; bool game_initialize() { engine = new Engine("Engine", 800, 600, 60.0f, false); game_state = GAME_STATE_MENU; //bitmap.load_resource("Data/Images/Login/Background.png"); //bitmap.load_resource("Data/Images/Login/UI.png"); //bitmap.load_resource("Data/Images/Login/LoginBox.png"); gui = new GUI(); map = new Map(); return true; } void game_loop() { while (engine-&gt;engine_running()) { do_game_events(); if (engine-&gt;has_ticked()) { engine-&gt;clear(0, 0, 0); handle_game_state(); engine-&gt;flip(); } } } void game_cleanup() { delete(engine); } void handle_game_state() { switch (game_state) { case GAME_STATE_MENU: gui-&gt;draw(GAME_STATE_MENU); gui-&gt;handle_input(GAME_STATE_MENU, *engine-&gt;input); gui-&gt;update(GAME_STATE_MENU); break; case GAME_STATE_PLAY: gui-&gt;draw(1); break; } } void do_game_events() { switch (game_state) { case GAME_STATE_MENU: engine-&gt;update_event_system(GAME_STATE_MENU, gui-&gt;textbox_active, gui-&gt;textbox2_active); break; } } </code></pre> <p>gui.h</p> <pre><code>#ifndef GUI_H #define GUI_H #include "stdafx.h" enum class MAIN_ELEMENTS { BACKGROUND, GRADIENT_LEFT, GRADIENT_RIGHT, BUTTONS, LOGINBOX, TEXTBOX, TEXTBAR, MAX, }; class GUI { public: GUI(); ~GUI(); void draw(int state); void handle_input(int state, Input &amp;input); void update(int state); int xoffset; int yoffset; std::time_t ct = std::time(0); char* cc = ctime(&amp;ct); bool textbox_hover, textbox_active, textbox2_hover, textbox2_active; std::string keyboard_string; bool textboxflag; protected: int gfx[(unsigned int)MAIN_ELEMENTS::MAX]; }; #endif </code></pre> <p>gui.cpp</p> <pre><code>#include "gui.h" GUI::GUI() { /*this-&gt;gfx[1] = engine-&gt;gfx-&gt;load_from_file("Data/Images/Login/Background.png"); this-&gt;gfx[2] = engine-&gt;gfx-&gt;load_from_file("Data/Images/Login/Overlay.png"); this-&gt;gfx[3] = engine-&gt;gfx-&gt;load_from_file("Data/Images/Login/LoginBox.png");*/ this-&gt;xoffset = 0; this-&gt;yoffset = 0; this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/scrolling_background_tile.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::GRADIENT_LEFT] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/gradient_left.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::GRADIENT_RIGHT] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/gradient_right.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BUTTONS] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/title_buttons.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::LOGINBOX] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/window.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBOX] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/textfield.png"); this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBAR] = engine-&gt;gfx-&gt;load_from_file("gfx/gui/title/textbar_bottom.png"); engine-&gt;usefultimer-&gt;Reset(al_get_time()); } GUI::~GUI() { delete cc; } void GUI::draw(int state) { if (state == 0) { //Menu //Background for (int i = 0; i &lt;= al_get_display_width(engine-&gt;get_display()) / 48; i++) { for (int y = 0; y &lt;= al_get_display_height(engine-&gt;get_display()) / 48; y++) { engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND], (i * 48) + xoffset, (y * 48) + yoffset, 0); engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND], -816 + (i * 48) + xoffset, (y * 48) + yoffset, 0); engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND], (i * 48) + xoffset, -624 + (y * 48) + yoffset, 0); engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND], -816 + (i * 48) + xoffset, -624 + (y * 48) + yoffset, 0); } } //Side gradients for (int i = 0; i &lt; al_get_display_height(engine-&gt;get_display()); i++) { engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::GRADIENT_LEFT], 0, i, 0); engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::GRADIENT_RIGHT], al_get_display_width(engine-&gt;get_display()) - engine-&gt;gfx-&gt;get_width(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::GRADIENT_LEFT]), i, 0); } //Login box engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::LOGINBOX], 0, 7, al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 - 20, al_get_display_height(engine-&gt;get_display()) / 2 + 110, 6, 15, 0); for (int i = 0; i &lt; 215; i++) { engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::LOGINBOX], 7, 7, 6+i+al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 - 20, al_get_display_height(engine-&gt;get_display()) / 2 + 110, 1, 15, 0); } //Username label al_draw_text(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 130, 0, "Username: "); //Password label al_draw_text(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), -70 + al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 180, 0, "Password: "); //Textbox not hovered if (!this-&gt;textbox_hover) { engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBOX], 0, 0, al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 150, engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX), engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, 0); } else { //Assume textbox is hovered engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBOX], 0, engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 150, engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX), engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, 0); } //Textbox2 not hovered if (!this-&gt;textbox2_hover) engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBOX], 0, 0, al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 180, engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX), engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, 0); //Textbox2 hovered else engine-&gt;gfx-&gt;blit_region(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBOX], 0, engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, al_get_display_height(engine-&gt;get_display()) / 2 + 180, engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX), engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2, 0); //Textbox active if (!this-&gt;textbox_active) { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 146, 0, "%s", engine-&gt;input-&gt;username_keyboard_string.c_str()); } else { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 146, 0, "%s", engine-&gt;input-&gt;username_keyboard_string.c_str()); if (textboxflag) { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 146, 0, "%s|", engine-&gt;input-&gt;username_keyboard_string.c_str()); } } //Hide password ******* std::string temp_pass = ""; for (unsigned int i = 0; i &lt; engine-&gt;input-&gt;password_keyboard_string.size(); i++) { temp_pass.append("*"); } //Textbox active if (!this-&gt;textbox2_active) { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 176, 0, "%s", temp_pass.c_str()); } else { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 176, 0, "%s", temp_pass.c_str()); if (textboxflag) { al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + 4, al_get_display_height(engine-&gt;get_display()) / 2 + 176, 0, "%s|", temp_pass.c_str()); } } //Bottom Textbar for (int i = 0; i &lt; al_get_display_width(engine-&gt;get_display()) / engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBAR); i++) { engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBAR], i * engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBAR), al_get_display_height(engine-&gt;get_display()) - engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBAR), 0); engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::TEXTBAR], i * engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBAR), al_get_display_height(engine-&gt;get_display()) - engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBAR) * 2 + 1, 0); } //Bottom text for textbar al_draw_textf(engine-&gt;gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), 0, al_get_display_height(engine-&gt;get_display()) - 24, 0, "version %s %s", engine-&gt;get_version().c_str(), engine-&gt;get_date().c_str()); } else if (state == 1) { //Game GUI } } void GUI::handle_input(int state, Input &amp;input) { if (state == 0) { if (input.mouseX &gt;= al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 &amp;&amp; input.mouseX &lt;= al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) &amp;&amp; input.mouseY &gt;= al_get_display_height(engine-&gt;get_display()) / 2 + 150 &amp;&amp; input.mouseY &lt;= al_get_display_height(engine-&gt;get_display()) / 2 + 150 + engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2) { textbox_hover = true; if (engine-&gt;input-&gt;mouseB) { engine-&gt;input-&gt;mouseB = false; textbox_active = true; textbox2_active = false; } } else { textbox_hover = false; } if (input.mouseX &gt;= al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 &amp;&amp; input.mouseX &lt;= al_get_display_width(engine-&gt;get_display()) / 2 - engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2 + engine-&gt;gfx-&gt;get_width((unsigned int)MAIN_ELEMENTS::TEXTBOX) &amp;&amp; input.mouseY &gt;= al_get_display_height(engine-&gt;get_display()) / 2 + 180 &amp;&amp; input.mouseY &lt;= al_get_display_height(engine-&gt;get_display()) / 2 + 180 + engine-&gt;gfx-&gt;get_height((unsigned int)MAIN_ELEMENTS::TEXTBOX) / 2) { textbox2_hover = true; if (engine-&gt;input-&gt;mouseB) { engine-&gt;input-&gt;mouseB = false; textbox2_active = true; textbox_active = false; } } else { textbox2_hover = false; } } else if (state == 1) { } } void GUI::update(int state) { if (state == 0) { this-&gt;xoffset += 1; this-&gt;yoffset += 1; if (this-&gt;xoffset &gt; 480) this-&gt;xoffset = 48; if (this-&gt;yoffset &gt; 480) this-&gt;yoffset = 48; engine-&gt;usefultimer-&gt;Update(al_get_time()); if (engine-&gt;usefultimer-&gt;hasPassed(1)) { textboxflag = !textboxflag; engine-&gt;usefultimer-&gt;Reset(al_get_time()); } } else if (state == 1) { } } </code></pre> <p>spritesheet.h</p> <pre><code>#ifndef SPRITESHEET_H #define SPRITESHEET_H #include "stdafx.h" enum class Player_Spritesheet { STANDING, WALKING, ATTACKING, RESTING, MAX }; class Spritesheet { public: Spritesheet(); ~Spritesheet(); void draw(int state); protected: int gfx[(unsigned int)Player_Spritesheet::MAX]; }; #endif </code></pre> <p>spritesheet.cpp</p> <pre><code>#include "spritesheet.h" Spritesheet::Spritesheet() { this-&gt;gfx[(unsigned int)Player_Spritesheet::STANDING] = engine-&gt;gfx-&gt;load_from_file("gfx/character/101.png"); for (int i = 0; i &lt; (unsigned int)Player_Spritesheet::MAX; i++) { this-&gt;gfx[i] = 0; } } Spritesheet::~Spritesheet() { } void Spritesheet::draw(int state) { if (state == 0) { //Menu GUI engine-&gt;gfx-&gt;blit(this-&gt;gfx[0], 0, 0, 0); } else if (state == 1) { //Game GUI } } </code></pre> <p>fwd/engine.h</p> <pre><code>#ifndef FWD_ENGINE #define FWD_ENGINE class Engine; #endif </code></pre> <p>engine/engine.h</p> <pre><code>#ifndef ENGINE_H #define ENGINE_H #include "../stdafx.h" class Engine { public: Engine(std::string title, int width, int height, const float fps, bool fullscreen); ~Engine(); bool engine_running() { return this-&gt;is_running; } void stop() { this-&gt;is_running = false; } void update_event_system(int state, int textbox_active, int textbox_active2); ALLEGRO_EVENT get_event() { return this-&gt;event; }; ALLEGRO_DISPLAY* get_display() { return this-&gt;display; }; void clear(int r, int g, int b); void flip(); bool has_ticked(); void capture_screen(std::string filename); void error(std::string message); void error(std::string message, std::string filepath); std::string get_version() { return this-&gt;version; } std::string get_date() { now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buf[100] = { 0 }; std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&amp;now)); return buf; } Graphics* gfx; Input* input; Timer* usefultimer; private: ALLEGRO_DISPLAY* display; ALLEGRO_TIMER* timer; ALLEGRO_EVENT_QUEUE* queue; ALLEGRO_EVENT event; bool is_running; bool ticked; std::string version; std::time_t now{ 0 }; }; #endif </code></pre> <p>engine/Engine.cpp</p> <pre><code>#include "engine.h" Engine::Engine(std::string title, int width, int height, const float fps, bool fullscreen) : is_running(false), ticked(false), version("0.01") { this-&gt;display = nullptr; if (!al_init()) this-&gt;error("Failed to initialize program!"); this-&gt;queue = al_create_event_queue(); if (!this-&gt;queue) this-&gt;error("Failed to initialize queue system!"); this-&gt;gfx = new Graphics(); this-&gt;input = new Input(this-&gt;queue); this-&gt;usefultimer = new Timer(); int flags = ALLEGRO_RESIZABLE; if (fullscreen) flags = ALLEGRO_FULLSCREEN; al_set_new_display_flags(flags); this-&gt;display = al_create_display(width, height); if (!this-&gt;display) this-&gt;error("Failed to create display!"); flags = al_get_display_flags(this-&gt;display); al_set_window_title(this-&gt;display, title.c_str()); this-&gt;timer = al_create_timer(ALLEGRO_BPS_TO_SECS(fps)); if (!this-&gt;timer) this-&gt;error("Failed to initialize timer system!"); al_register_event_source(this-&gt;queue, al_get_display_event_source(this-&gt;display)); al_register_event_source(this-&gt;queue, al_get_timer_event_source(this-&gt;timer)); al_start_timer(this-&gt;timer); this-&gt;is_running = true; } Engine::~Engine() { if (this-&gt;display) al_destroy_display(this-&gt;display); if (this-&gt;timer) al_destroy_timer(this-&gt;timer); if (this-&gt;queue) al_destroy_event_queue(this-&gt;queue); delete(this-&gt;gfx); delete(this-&gt;input); } void Engine::update_event_system(int state, int textbox_active, int textbox_active2) { al_wait_for_event(this-&gt;queue, &amp;event); switch (this-&gt;event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: this-&gt;stop(); break; case ALLEGRO_EVENT_TIMER: this-&gt;ticked = true; break; case ALLEGRO_EVENT_KEY_DOWN: this-&gt;input-&gt;set_key_state(this-&gt;event.keyboard.keycode, true); break; case ALLEGRO_EVENT_KEY_UP: { this-&gt;input-&gt;set_key_state(this-&gt;event.keyboard.keycode, false); if (engine-&gt;get_event().keyboard.keycode == ALLEGRO_KEY_PRINTSCREEN) { FILE* fh; char buf[30]; int num = 0; while (true) { num++; sprintf(buf, "screen/screen_%i.png", num); fh = fopen(buf, "r"); if (!fh) break; fclose(fh); } printf("print Screen! id=%i\n", num); engine-&gt;capture_screen(buf); } break; } case ALLEGRO_EVENT_KEY_CHAR: { const int inputChar = engine-&gt;get_event().keyboard.unichar; if (engine-&gt;get_event().keyboard.keycode == ALLEGRO_KEY_BACKSPACE) { if (state == GAME_STATE_MENU &amp;&amp; textbox_active == 1) { if (this-&gt;input-&gt;username_keyboard_string.length() &gt; 0) { input-&gt;username_keyboard_string = this-&gt;input-&gt;username_keyboard_string.substr(0, this-&gt;input-&gt;username_keyboard_string.length() - 1); } } if (state == GAME_STATE_MENU &amp;&amp; textbox_active2 == 1) { if (this-&gt;input-&gt;password_keyboard_string.length() &gt; 0) { input-&gt;password_keyboard_string = this-&gt;input-&gt;password_keyboard_string.substr(0, this-&gt;input-&gt;password_keyboard_string.length() - 1); } } } else if ( (inputChar &gt;= 48 &amp;&amp; inputChar &lt;= 57) //is a number || (inputChar &gt;= 65 &amp;&amp; inputChar &lt;= 90) //is a capital letter || (inputChar &gt;= 97 &amp;&amp; inputChar &lt;= 122) //is a lower-case letter || (inputChar == 95) //is an underscore ) { if (state == GAME_STATE_MENU &amp;&amp; textbox_active == 1) this-&gt;input-&gt;username_keyboard_string += inputChar; if (state == GAME_STATE_MENU &amp;&amp; textbox_active2 == 1) this-&gt;input-&gt;password_keyboard_string += inputChar; std::cout &lt;&lt; this-&gt;input-&gt;keyboard_string &lt;&lt; std::endl; } } break; case ALLEGRO_EVENT_MOUSE_AXES: this-&gt;input-&gt;mouseX = event.mouse.x; this-&gt;input-&gt;mouseY = event.mouse.y; break; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: if (event.mouse.button &amp; 1) this-&gt;input-&gt;set_mouse_state(this-&gt;event.mouse.button, true); break; case ALLEGRO_EVENT_MOUSE_BUTTON_UP: if (event.mouse.button &amp; 1) this-&gt;input-&gt;set_mouse_state(this-&gt;event.mouse.button, false); break; } } void Engine::clear(int r, int g, int b) { al_set_target_backbuffer(this-&gt;display); al_clear_to_color(al_map_rgb(r, g, b)); } void Engine::flip() { al_flip_display(); } bool Engine::has_ticked() { bool temp = this-&gt;ticked; this-&gt;ticked = false; return temp; } void Engine::capture_screen(std::string filename) { al_draw_textf(gfx-&gt;get_font(FONT_TINYUNICODE), al_map_rgb(255, 255, 255), 0, 0, 0, "Game V%s", version.c_str()); al_save_bitmap(filename.c_str(), al_get_backbuffer(this-&gt;display)); } void Engine::error(std::string message) { printf(message.c_str()); exit(-1); } void Engine::error(std::string message, std::string filepath) { printf(message.c_str(), filepath.c_str()); exit(-1); } </code></pre> <p>fwd/graphics.h</p> <pre><code>#ifndef FWD_GRAPHICS_H #define FWD_GRAPHICS_H class Graphics; #endif </code></pre> <p>engine/graphics.h</p> <pre><code>#ifndef GRAPHICS_H #define GRAPHICS_H #include "../stdafx.h" enum fonts { FONT_COMICI, FONT_TINYUNICODE, FONT_MAX }; class Graphics { public: Graphics(); ~Graphics(); int load_from_file(std::string filename); void blit(int id, int x, int y, int flags, int alpha = 255); void blit_region(int id, int sx, int sy, int x, int y, int sw, int sh, int flags, int alpha = 255); int get_width(int id); int get_height(int id); ALLEGRO_BITMAP* get_bitmap(int id); int count(); ALLEGRO_FONT* get_font(int id); protected: std::vector&lt;ALLEGRO_BITMAP*&gt; bitmap; ALLEGRO_FONT* comici; ALLEGRO_FONT* tinyunicode; bool is_valid_id(unsigned int id); }; #endif </code></pre> <p>engine/graphics.cpp</p> <pre><code>#include "graphics.h" Graphics::Graphics() { if (!al_init_image_addon()) engine-&gt;error("Failed to initialize image addon!"); if (!al_init_font_addon()) engine-&gt;error("Failed to initialize font addon!"); if (!al_init_ttf_addon()) engine-&gt;error("Failed to initialize ttf addon!"); this-&gt;comici = al_load_ttf_font("data/font/comici.ttf", 12, 0); if (!this-&gt;comici) engine-&gt;error("Failed to initialize font: \"data/font/comici.ttf\""); this-&gt;tinyunicode = al_load_ttf_font("data/font/TinyUnicode.ttf", 24, 0); if (!this-&gt;tinyunicode) engine-&gt;error("Failed to initialize font: \"data/font/TinyUnicode.ttf\""); } Graphics::~Graphics() { for (unsigned int i = 0; i&lt;this-&gt;bitmap.size(); i++) { if (this-&gt;bitmap[i]) al_destroy_bitmap(this-&gt;bitmap[i]); } if (this-&gt;comici) al_destroy_font(this-&gt;comici); if (this-&gt;tinyunicode) al_destroy_font(this-&gt;tinyunicode); al_shutdown_image_addon(); al_shutdown_font_addon(); al_shutdown_ttf_addon(); } int Graphics::load_from_file(std::string filename) { ALLEGRO_BITMAP* temp_bmp = al_load_bitmap(filename.c_str()); if (!temp_bmp) engine-&gt;error("Error loading bitmap: gfx/updatethis/%s", filename.c_str()); if (temp_bmp) { this-&gt;bitmap.push_back(temp_bmp); return this-&gt;bitmap.size() - 1; } return -1; } void Graphics::blit(int id, int x, int y, int flags, int alpha) { if (this-&gt;is_valid_id(id)) { if (alpha != 255) { al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); al_draw_tinted_bitmap(this-&gt;bitmap[id], al_map_rgba(255, 255, 255, alpha), x, y, flags); } else al_draw_bitmap(this-&gt;bitmap[id], x, y, flags); } } void Graphics::blit_region(int id, int sx, int sy, int x, int y, int sw, int sh, int flags, int alpha) { if (this-&gt;is_valid_id(id)) { if (alpha != 255) { al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); al_draw_tinted_bitmap_region(this-&gt;bitmap[id], al_map_rgba(255, 255, 255, alpha), sx, sy, sw, sh, x, y, flags); } else al_draw_bitmap_region(this-&gt;bitmap[id], sx, sy, sw, sh, x, y, flags); } } int Graphics::get_width(int id) { if (this-&gt;is_valid_id(id)) { return al_get_bitmap_width(this-&gt;bitmap[id]); } return 0; } int Graphics::get_height(int id) { if (this-&gt;is_valid_id(id)) { return al_get_bitmap_height(this-&gt;bitmap[id]); } return 0; } ALLEGRO_BITMAP* Graphics::get_bitmap(int id) { if (this-&gt;is_valid_id(id)) { return this-&gt;bitmap[id]; } return NULL; } bool Graphics::is_valid_id(unsigned int id) { if (id &lt; 0 || id &gt;= this-&gt;bitmap.size()) return false; if (!this-&gt;bitmap[id]) return false; return true; } int Graphics::count() { return this-&gt;bitmap.size(); } ALLEGRO_FONT * Graphics::get_font(int id) { switch (id) { case FONT_COMICI: return this-&gt;comici; break; case FONT_TINYUNICODE: return this-&gt;tinyunicode; default: return nullptr; break; } } </code></pre> <p>fwd/input.h</p> <pre><code>#ifndef FWD_INPUT_H #define FWD_INPUT_H class Input; #endif </code></pre> <p>engine/input.h</p> <pre><code>#ifndef INPUT_H #define INPUT_H #include "../stdafx.h" class Input { public: Input(ALLEGRO_EVENT_QUEUE* queue); ~Input(); //void processInput(int state, GUI* gui); int mouseX, mouseY, mouseB; std::string username_keyboard_string = ""; std::string password_keyboard_string = ""; std::string keyboard_string = ""; private: bool keys[ALLEGRO_KEY_MAX]; bool mouse[2]; int prevMouseState; int curMouseState; void set_key_state(int keycode, bool is_down) { this-&gt;keys[keycode] = is_down; } void set_mouse_state(int button, bool is_down) { this-&gt;mouseB = is_down; } friend class Engine; }; #endif </code></pre> <p>engine/input.cpp</p> <pre><code>#include "input.h" Input::Input(ALLEGRO_EVENT_QUEUE* queue) { if (!al_install_keyboard()) { engine-&gt;error("Failed to install keyboard!"); } if (!al_install_mouse()) { engine-&gt;error("Failed to install mouse!"); } al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); for (int i = 0; i &lt; ALLEGRO_KEY_MAX; i++) { this-&gt;keys[i] = false; } for (int i = 0; i &lt; 2; i++) { this-&gt;mouse[i] = false; } this-&gt;mouseX = 0; this-&gt;mouseY = 0; this-&gt;mouseB = 0; } Input::~Input() { al_uninstall_keyboard(); al_uninstall_mouse(); } //void Input::processInput(int state, GUI* gui) { // switch (engine-&gt;get_event().type) { // case ALLEGRO_EVENT_KEY_CHAR: // { // const int inputChar = engine-&gt;get_event().keyboard.unichar; // if (engine-&gt;get_event().keyboard.keycode == ALLEGRO_KEY_BACKSPACE) { // if (gui-&gt;keyboard_string.length() &gt; 0) { // gui-&gt;keyboard_string = gui-&gt;keyboard_string.substr(0, gui-&gt;keyboard_string.length() - 1); // } // } // else if // ( // (inputChar &gt;= 48 &amp;&amp; inputChar &lt;= 57) //is a number // || (inputChar &gt;= 65 &amp;&amp; inputChar &lt;= 90) //is a capital letter // || (inputChar &gt;= 97 &amp;&amp; inputChar &lt;= 122) //is a lower-case letter // || (inputChar == 95) //is an underscore // ) { // gui-&gt;keyboard_string += inputChar; // std::cout &lt;&lt; gui-&gt;keyboard_string &lt;&lt; std::endl; // std::cout &lt;&lt; inputChar &lt;&lt; std::endl; // } // } // break; // case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: // if (engine-&gt;get_event().mouse.button &amp; 1) // std::cout &lt;&lt; "Hello"; // break; // case ALLEGRO_EVENT_KEY_DOWN: { // if (engine-&gt;get_event().keyboard.keycode == ALLEGRO_KEY_RIGHT) { // // } // } // case ALLEGRO_EVENT_KEY_UP: { // if (engine-&gt;get_event().keyboard.keycode == ALLEGRO_KEY_PRINTSCREEN) { // FILE* fh; // char buf[30]; // int num = 0; // // while (true) { // num++; // sprintf(buf, "screen/screen_%i.png", num); // // fh = fopen(buf, "r"); // // if (!fh) // break; // // fclose(fh); // } // // printf("print Screen! id=%i\n", num); // engine-&gt;capture_screen(buf); // } // break; // } // } //} </code></pre> <p>fwd/timer.h</p> <pre><code>#ifndef FWD_TIMER_H #define FWD_TIMER_H class Timer; #endif </code></pre> <p>engine/timer.h</p> <pre><code>#ifndef TIMER_H #define TIMER_H #include "../stdafx.h" /* SunOS 4.1.* does not define CLOCKS_PER_SEC, so include &lt;sys/param.h&gt; */ /* to get the HZ macro which is the equivalent. */ #if defined(__sun__) &amp;&amp; !defined(SVR4) &amp;&amp; !defined(__SVR4) #include &lt;sys/param.h&gt; #define CLOCKS_PER_SEC HZ #endif class Timer { public: /* Default c'tor */ Timer(); ~Timer(); time_t GetTime(); void Update(const time_t&amp; time); bool hasPassed(double seconds) { m_elapsedTime = al_get_time() - m_startTime; if (m_elapsedTime &gt;= seconds) return true; else return false; return false; } bool Paused(); void Pause(); void Reset(const time_t&amp; time); private: bool m_paused; // Whether system timer is currently paused double m_startTime; // Previous global time, compares against current global time double m_elapsedTime; // Local amount of elapsed time (pause-aware) }; #endif // Timer_h </code></pre> <p>engine/timer.cpp</p> <pre><code>#include "engine/timer.h" /* Default c'tor */ Timer::Timer() : m_paused(false), m_startTime(0), m_elapsedTime(0) { // Default constructor } Timer::~Timer() { } time_t Timer::GetTime() { return m_elapsedTime; } void Timer::Update(const time_t&amp; time) { double delta = m_elapsedTime - m_startTime; if (!m_paused) m_elapsedTime += delta; } bool Timer::Paused() { return m_paused; } void Timer::Pause() { m_paused = !m_paused; } void Timer::Reset(const time_t&amp; time) { m_elapsedTime = 0; m_startTime = time; } </code></pre>
[]
[ { "body": "<p>There's a lot here that I believe you can improve. Here are some suggestions that may help you to do that.</p>\n\n<h2>Isolate platform-specific code</h2>\n\n<p>If you must have <code>stdafx.h</code>, consider wrapping it so that the code is portable:</p>\n\n<pre><code>#ifdef WINDOWS\n#include \"stdafx.h\"\n#endif\n</code></pre>\n\n<p>In this case, it is being seriously abused, so I'd recommend omitting it entirely as in the next few suggestions.</p>\n\n<h2>Avoid relative paths in #includes</h2>\n\n<p>Generally it's better to omit relative path names from #include files and instead point the compiler to the appropriate location. So don't write this:</p>\n\n<pre><code>#include \"engine/timer.h\"\n</code></pre>\n\n<p>Write this:</p>\n\n<pre><code>#include \"timer.h\"\n</code></pre>\n\n<p>For <code>gcc</code>, you'd use <code>-I</code>. This makes the code less dependent on the actual directory structure, and leaves such details in a <em>single</em> location: a <code>Makefile</code> or compiler configuration file.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>In C++, this is usually done by putting the interface into separate <code>.h</code> files and the corresponding implementation into <code>.cpp</code> files. It helps users (or reviewers) of the code see and understand the interface and hides implementation details. So instead of having this in <code>Engine.h</code>:</p>\n\n<pre><code>#include \"../stdafx.h\"\n</code></pre>\n\n<p>I would highly recommend something more like this:</p>\n\n<pre><code>#include \"graphics.h\"\n#include \"input.h\"\n#include \"timer.h\"\n#include &lt;string&gt;\n#include &lt;chrono&gt;\n#include &lt;ctime&gt;\n</code></pre>\n\n<p>This way, it's much easier to identify the <strong>real</strong> dependencies for the interface. For implementation files such as <code>Engine.cpp</code>, one can hide the details of the particular implementation. For example, I'd recommend moving the implementation of <code>get_date()</code> into the <code>.cpp</code> file and moving the <code>&lt;chrono&gt;</code> and <code>&lt;ctime&gt;</code> includes there as well. Those files are not essential details that a <em>user</em> of the class needs to know.</p>\n\n<h2>Don't hardcode file names</h2>\n\n<p>The font files, bitmaps, etc. might be something that a user of this program has in different locations than you do on your machine. Because all of these settings are both hardcoded and embedded in the <code>.cpp</code> files, it would be quite tedious to fix all of those paths so that your game works on anyone else's computer. Use a configuration file instead, or at the very least, isolate the file names within the <code>.h</code> files so that the dependencies are obvious and easy to find and update.</p>\n\n<h2>Don't write this-></h2>\n\n<p>Within member functions <code>this-&gt;data</code> is redundant. It add visual clutter and does not usually aid in understanding. So for example, we have the existing <code>Engine</code> destructor:</p>\n\n<pre><code>Engine::~Engine() {\n if (this-&gt;display) al_destroy_display(this-&gt;display);\n if (this-&gt;timer) al_destroy_timer(this-&gt;timer);\n if (this-&gt;queue) al_destroy_event_queue(this-&gt;queue);\n\n delete(this-&gt;gfx);\n delete(this-&gt;input);\n}\n</code></pre>\n\n<p>It's much less cluttered and easier to read if it's written like this instead:</p>\n\n<pre><code>Engine::~Engine() {\n if (display) {\n al_destroy_display(display);\n }\n if (timer) {\n al_destroy_timer(timer);\n }\n if (queue) {\n al_destroy_event_queue(queue);\n }\n delete(gfx);\n delete(input);\n}\n</code></pre>\n\n<p>Note also that I've eliminated the single-line <code>if</code> statements.</p>\n\n<h2>Be wary of signed versus unsigned</h2>\n\n<p>The code currently contains this code:</p>\n\n<pre><code>bool Graphics::is_valid_id(unsigned int id)\n{\n if (id &lt; 0 || id &gt;= this-&gt;bitmap.size())\n return false;\n\n if (!this-&gt;bitmap[id])\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>However, that first condition <code>id &lt; 0</code> can never be true because it's an unsigned number. I would simplify this considerably and write it like this:</p>\n\n<pre><code>bool Graphics::is_valid_id(unsigned int id) const\n{\n return id &lt; bitmap.size() &amp;&amp; bitmap[id];\n}\n</code></pre>\n\n<p>Because of <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"noreferrer\">short-circuit evaluation</a>, the second clause will only be executed if the first one is true.</p>\n\n<h2>Avoid global variables</h2>\n\n<p>There are some very dubious design decisions embedded within the current code. One is the use of a global <code>Engine</code> object. Another is the fact that three important data members of <code>Engine</code> are public. Yet another is the fact those members are all three raw pointers. All of these make code that is brittle and hard to understand and maintain. </p>\n\n<h2>Rethink your class design</h2>\n\n<p>It seems that <code>Game</code> should be a class instead of a collection of global variables and some free functions. It also appears that the <code>GUI</code> class is inextricably bound to the <code>Engine</code> class (and to a global instance) and the <code>Graphics</code> class, but it's unclear which responsibilities belong to which class or why there are three different kinds of objects. Another peculiar decision is that the <code>Input</code> class appears to only have a pointer to a <code>queue</code> which is actually a member of the <code>Engine</code> class instead of being a member of the <code>Input</code> class.</p>\n\n<h2>Avoid magic numbers</h2>\n\n<p>One of the lines of code here is this:</p>\n\n<pre><code>engine-&gt;gfx-&gt;blit(this-&gt;gfx[(unsigned int)MAIN_ELEMENTS::BACKGROUND], -816 + (i * 48) + xoffset, (y * 48) + yoffset, 0);\n</code></pre>\n\n<p>All of those numbers, such as -816 and 48 no doubt mean something, but what? I'm sure I could figure it out with enough study, but it would be better to use well-named constants to avoid the need to guess. It also makes the code easier to maintain because if, for example, you wanted to change all instances of 48 to some other value, you wouldn't have to figure out, for each instance, whether this <em>particular</em> 48 is refers to the particular thing you're trying to change or not.</p>\n\n<h2>Use <code>const</code> where possible</h2>\n\n<p>The <code>engine_running</code>, <code>get_event</code>, <code>get_display</code> and <code>get_version</code> functions do not (and should not) alter the underlying <code>Engine</code> object and should therefore be declared <code>const</code>.</p>\n\n<h2>Use const references where practical</h2>\n\n<p>The code currently defines one of its error functions like so:</p>\n\n<pre><code>void Engine::error(std::string message, std::string filepath) {\n printf(message.c_str(), filepath.c_str());\n exit(-1);\n}\n</code></pre>\n\n<p>Both <code>message</code> and <code>filepath</code> could be passed by <code>const std::string &amp;</code> instead. </p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>In the following code:</p>\n\n<pre><code>void set_mouse_state(int button, bool is_down) { this-&gt;mouseB = is_down; }\n</code></pre>\n\n<p>the <code>button</code> parameter is never used and could be eliminated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:05:25.870", "Id": "413295", "Score": "0", "body": "`stdafx.h` is just a precompiled header - it's not Windows specific. (Though it probably isn't necessary / shouldn't have that much in it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:07:57.503", "Id": "413296", "Score": "1", "body": "Yes, I know what it is, but it seems only to be used by programmers using Windows compilers. I'd suggest that it is attempting to solve a problem that probably doesn't exist (slow compile times) and that you're better off with a clean class design and forgetting about `fwd` and `stdafx.h` until you actually encounter a problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T21:58:01.817", "Id": "213676", "ParentId": "213653", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:26:44.310", "Id": "213653", "Score": "5", "Tags": [ "c++", "game", "allegro" ], "Title": "Isometric game engine using Allegro" }
213653
<p>I wrote the below code which contains the following functions: establish session with the user, determine if the user is authenticated, perform ping request, search about the user from the database, reset password and import bulk product with the type text/xml.</p> <ul> <li>Did I handle the functions correctly? </li> <li>Is my code secure? </li> <li>Should I correct any parts of the code?</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var db = require('../models') var bCrypt = require('bcrypt') const exec = require('child_process').exec; var mathjs = require('mathjs') var libxmljs = require("libxmljs"); var serialize = require("node-serialize") const Op = db.Sequelize.Op var express = require('express') var bodyParser = require('body-parser') var passport = require('passport') var session = require('express-session') var ejs = require('ejs') var morgan = require('morgan') const fileUpload = require('express-fileupload'); var config = require('./config/server') var app = express() require('./core/passport')(passport) app.use(express.static('public')) app.set('view engine','ejs') app.use(morgan('tiny')) app.use(bodyParser.urlencoded({ extended: false })) app.use(fileUpload()); app.use(session({ secret: 'secret_key', resave: true, saveUninitialized: true, cookie: { secure: false } })) app.use(passport.initialize()) app.use(passport.session()) app.use(require('express-flash')()); app.use('/app',require('./routes/app')()) app.use('/',require('./routes/main')(passport)) app.listen(config.port, config.listen) module.exports.isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) { req.flash('authenticated', true) return next(); res.redirect('/login'); } module.exports.ping = function (req, res) { exec('ping -c 2 ' + req.body.address, function (err, stdout, stderr) { output = stdout + stderr res.render('app/ping', { output: output }) }) } module.exports.userSearch = function (req, res) { var query = "SELECT name,id FROM Users WHERE login='" + req.body.login + "'"; db.sequelize.query(query, { model: db.User, logging: true }).then(user =&gt; { if (user.length) { var output = { user: { name: user[0].name, id: user[0].id res.render('app/usersearch', { output: output }) } else { req.flash('warning', 'User not found') res.render('app/usersearch', { output: null }) }).catch(err =&gt; { req.flash('danger', 'Internal Error') res.render('app/usersearch', { output: null }) }) } module.exports.resetpasswd = function (req, res) { if (req.query.login) { db.User.find({ where: { 'login': req.query.login }).then(user =&gt; { if (user) { if (req.query.token == md5(req.query.login)) { res.render('resetpassword', { login: req.query.login, token: req.query.token }) } else { req.flash('danger', "Invalid reset token") res.redirect('/forgotpassword') } else { req.flash('danger', "Invalid login username") res.redirect('/forgotpassword') }) } else { req.flash('danger', "invalid username") res.redirect('/forgotpassword') } module.exports.importBulkProducts = function(req, res) { if (req.files.products &amp;&amp; req.files.products.mimetype=='text/xml'){ var products = libxmljs.parseXmlString(req.files.products.data.toString('utf8'), {noent:true,noblanks:true}) products.root().childNodes().forEach( product =&gt; { var newProduct = new db.Product() newProduct.name = product.childNodes()[0].text() newProduct.code = product.childNodes()[1].text() newProduct.tags = product.childNodes()[2].text() newProduct.description = product.childNodes()[3].text() newProduct.save() }) res.redirect('/app/products') }else{ res.render('app/bulkproducts',{messages:{danger:'Invalid file'},legacy:false}) }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>The general rule is that you should <em>never</em> incorporate user-controlled input into a string that will be interpreted by a computer system without escaping it first. Specifically, at a quick glance, it's obvious that…</p>\n\n<ul>\n<li><p>Your <code>exec()</code> call is vulnerable to command-line injection:</p>\n\n<blockquote>\n<pre><code>exec('ping -c 2 ' + req.body.address, …)\n</code></pre>\n</blockquote></li>\n<li><p>Your SQL query is vulnerable to SQL injection:</p>\n\n<blockquote>\n<pre><code>var query = \"SELECT name,id FROM Users WHERE login='\" + req.body.login + \"'\";\n</code></pre>\n</blockquote></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-09T19:26:04.623", "Id": "230452", "ParentId": "213656", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T15:24:20.443", "Id": "213656", "Score": "3", "Tags": [ "javascript", "node.js", "security", "express.js", "status-monitoring" ], "Title": "Express.js functions to start session, authenticate user, perform ping, search for user, reset password, and import product XML" }
213656
<p>The purpose of the code is to efficiently stream JSON items from a large file. I am wondering if this is efficient and decently idiomatic. Not sure how I could eliminate the while loop either.</p> <pre><code>module Seq = let inline tryMove (e:IEnumerator&lt;'T&gt;) = try let moved = e.MoveNext() if moved then Some &lt;| Choice1Of2 e.Current else e.Dispose() None with ex -&gt; Some &lt;| Choice2Of2 ex let catch (items:_ seq) = use e = items.GetEnumerator() e |&gt; Seq.unfold( tryMove &gt;&gt; function | Some (Choice1Of2 item) -&gt; Some(Choice1Of2 item,e) | Some (Choice2Of2 ex) -&gt; Some(Choice2Of2 ex, e) | None -&gt; None ) module SuperSerial = let deserialize&lt;'T&gt;(x):'T = JsonConvert.DeserializeObject&lt;'T&gt;(x) let streamJson&lt;'T&gt; sr = let serializer = JsonSerializer() seq{ use r = new JsonTextReader(sr) while r.Read() do if r.TokenType = JsonToken.StartObject then yield serializer.Deserialize&lt;'T&gt;(r) } let streamString&lt;'T&gt; x = seq{ use s = new StringReader(x) yield! streamJson(s) } let streamJsonFile&lt;'T&gt; target = seq{ use s = File.Open(target,FileMode.Open) use sr = new StreamReader(s) yield! streamJson(sr) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T15:44:39.223", "Id": "213658", "Score": "2", "Tags": [ "f#" ], "Title": "Creating idiomatic and efficient method to stream large JSON file" }
213658
<p>I wrote this script to replace a VBA script for mailbox management that was in place before. Essentially, I have an Excel sheet in which the rules are defined. These have to be loaded and applied to the mails currently in the inbox. The file's structure looks like this:</p> <pre><code>criteria (required): &quot;begins with&quot; or &quot;contains&quot; filename (optional): &quot;filename part&quot; address (optional): &quot;example@email.com&quot; subject (optional): &quot;subject part&quot; directory (optional): &quot;C:\\my\\custom\\abs\\path\\&quot; outlook_folder_1 (required): &quot;folder name&quot; outlook_folder_2 (optional): &quot;subfolder name&quot; </code></pre> <p>Emails should be moved to the specified Outlook folder. For each mail, first address and subject are checked for matches and the mail is moved to the specified folder. Then attachments are checked, mail should be moved, if not moved yet, and the attachment downloaded, if a directory is provided.</p> <p>The script is currently working fine, but I'm wondering if it'd be possible to improve performance somehow. Also, I was thinking about replacing the <code>criteria</code> column from the file and use <code>regex</code> to search mails based on patterns. What are your thoughts?</p> <h3>harvester.py</h3> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Central mailbox management rules&quot;&quot;&quot; import logging import os import zipfile import pandas as pd from pandas.tseries.offsets import BDay import win32com.client from misc import sanitize_col_name # create a logger logger = logging.getLogger(__name__) # get today's date today = pd.datetime.now().date() # defining paths and constants ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CENTRAL_MAILBOX = &quot;Central mailbox&quot; # get the outlook instance and inbox folders outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).Session account = outlook.Accounts(1) personal_inbox = outlook.Folders( account.DeliveryStore.DisplayName).Folders(&quot;Inbox&quot;) user = outlook.CreateRecipient(CENTRAL_MAILBOX) central_inbox = outlook.GetSharedDefaultFolder(user, 6) def load_criteria(): criteria_path = os.path.join( ROOT, &quot;rsc&quot;, &quot;attachment_criteria.xlsx&quot;) df = pd.read_excel(criteria_path) for i in range(len(df)): row = df.iloc[-1] if row.isna().all(): df = df[:-1] else: break df.columns = [sanitize_col_name(c) for c in df.columns] return df criteriadf = load_criteria() def check_attachment(row, att): if not isinstance(row.filename, str): return False if att.Type == 6 or att.FileName.split(&quot;.&quot;)[1] in [&quot;jpg&quot;, &quot;png&quot;]: return False if row.criteria == &quot;begins with&quot; and row.filename == att.FileName[:len(row.filename)]: return True elif row.criteria == &quot;contains&quot; and row.filename in att.FileName: return True else: return False def check_subject(row, mail): if not isinstance(row.subject, str): return False if row.criteria == &quot;begins with&quot; and row.subject == mail.Subject[:len(row.subject)]: return True elif row.criteria == &quot;contains&quot; and row.subject in mail.Subject: return True else: return False def check_zip_and_extract(filepath): filetype = filepath.split(&quot;.&quot;)[1] if not filetype == &quot;zip&quot;: return None logger.info(&quot;The attachment is a zip file. Extracting now..&quot;) directory = os.path.dirname(filepath) zip_ref = zipfile.ZipFile(filepath, &quot;r&quot;) zip_ref.extractall(directory) logger.info(f&quot;Extracted zip file to {directory}&quot;) zip_ref.close() def get_mails(days): if not isinstance(days, int): logger.info(&quot;Days has to be an int. Aborting..&quot;) return None if central_inbox.Items.Count == 0: logger.info(&quot;There are no messages in the central inbox. Aborting..&quot;) return None retrieve_from = today - BDay(days) logger.info(f&quot;Retrieving mails from {retrieve_from.strftime('%Y-%m-%d')} onwards.&quot;) mails = central_inbox.Items.Restrict( &quot;[ReceivedTime] &gt; '{}'&quot;.format(retrieve_from.strftime(&quot;%d/%m/%Y %H:%M&quot;)) ) logger.info(f&quot;Retrieved {len(mails)} mails.&quot;) return mails def run(mails): moved = 0 downloaded = 0 for mail in mails: for i, row in criteriadf.iterrows(): if ((mail.SenderEmailAddress == row.address and ( not isinstance(row.subject, str) or check_subject(row, mail))) or (not isinstance(row.address, str) and check_subject(row, mail))): logger.info( f&quot;The mail from {mail.SenderEmailAddress} with subject {mail.Subject} matches the criteria at index {row.name}&quot;) mail.Move(central_inbox.Folders(row[&quot;outlook_folder_1&quot;])) logger.info(f&quot;Moved mail {mail.Subject} to folder {row.outlook_folder_1}&quot;) moved += 1 logger.debug(&quot;Total moved: %s&quot;, moved) if mail.Attachments.Count == 0: continue for att in mail.Attachments: att_valid = check_attachment(row, att) if (not isinstance(row.address, str) and not isinstance(row.subject, str) and att_valid): logger.info(f&quot;The attachment {att.FileName} matches the criteria at index {row.name}\n&quot; f&quot;Mail has not been moved based on address or subject criteria yet.\n&quot; f&quot;Moving based on attachment..&quot;) mail.Move(central_inbox.Folders(row[&quot;outlook_folder_1&quot;])) logger.info(f&quot;Moved mail {mail.Subject} to folder {row.outlook_folder_1}&quot;) moved += 1 logger.debug(&quot;Total moved: %s&quot;, moved) if att_valid and isinstance(row.directory, str): filepath = os.path.join(row.directory, att.FileName) att.SaveAsFile(filepath) logger.info(f&quot;Saved attachment {att.FileName} under {filepath}&quot;) downloaded += 1 check_zip_and_extract(filepath) logger.debug(&quot;Total downloaded: %s&quot;, downloaded) return moved, downloaded </code></pre> <h3>misc.py</h3> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Util functions&quot;&quot;&quot; import json import logging import logging.config import re with open(r&quot;C:\path\to\config.json&quot;, &quot;r&quot;) as f: log_config = json.load(f) logging.config.dictConfig(log_config) def get_root_logger(): root_logger = logging.getLogger(&quot;root&quot;) return root_logger # sanitize column names def sanitize_col_name(name): nosigns = re.compile(&quot;[^A-Za-z0-9_\s]&quot;) nname = re.sub(nosigns, &quot;&quot;, name).strip().replace(&quot; &quot;, &quot;_&quot;).lower() nname = &quot;empty&quot; if nname == &quot;&quot; else nname return nname </code></pre> <h3>main.py</h3> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Main script to call the program from CLI&quot;&quot;&quot; import argparse import sys import harvester as harvester from misc import get_root_logger # getting the root logger logger = get_root_logger() # parsing arguments parser = argparse.ArgumentParser( description=&quot;Download Outlook attachments according to pre-defined rules&quot;) parser.add_argument(&quot;days&quot;, type=int, nargs=&quot;?&quot;, default=1) parser.add_argument(&quot;--verbose&quot;, &quot;-v&quot;, action=&quot;count&quot;) def main(): args = vars(parser.parse_args()) bdays_back = args[&quot;days&quot;] mails = harvester.get_mails(bdays_back) moved, downloaded = harvester.run(mails) logger.info(f&quot;Downloaded {downloaded} attachments and moved {moved} emails.\n&quot; &quot;Have a nice day!&quot;) if __name__ == &quot;__main__&quot;: logger.info(&quot;Initialising email mover&quot;) status = main() sys.exit(status) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T16:32:25.237", "Id": "213660", "Score": "2", "Tags": [ "python", "email", "outlook" ], "Title": "Outlook email rules and attachment downloader in Python" }
213660
<p>I created <a href="https://webapps.stackexchange.com/a/106604/140514">a way to export my Google Play playlists to a text file</a> and also <a href="https://webapps.stackexchange.com/a/125423/140514">a way to export all of my songs in Google Play to a text file</a>. Now I have both the song list (in an array format) and playlist data (in object and array format) in their respective text files. Here is a simplified version of the files:</p> <pre><code>[ "song 1 name", "song 2 name", "song 3 name" ] </code></pre> <p>and</p> <pre><code>{ "playlist 1": [ "song 1", "song 3" ], "playlist 2": [ "song 1" ] } </code></pre> <p>When I run them in my script, it works correctly and creates the following output:</p> <pre><code>{ "song 1": [ "playlist 1", "playlist 2" ], "song 2": [], "song 3": [ "playlist 1" ] } </code></pre> <p>Here's my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var songInput = document.getElementById("songInput"), playlistInput = document.getElementById("playlistInput"), result = document.querySelector("textarea"); var songList, playlistData; function loadData(id, elem) { if(elem.files &amp;&amp; elem.files[0]) { let myFile = elem.files[0]; let reader = new FileReader(); reader.addEventListener('load', function (e) { if(id === "songInput") songList = JSON.parse(e.target.result); if(id === "playlistInput") playlistData = JSON.parse(e.target.result); checkBothAdded(); }); reader.readAsBinaryString(myFile); } } function checkBothAdded() { if(songList &amp;&amp; playlistData) { getSongPlaylistData(); } } var songData = {}; function getSongPlaylistData() { for(let song of songList) { let playlistsItsIn = []; Object.keys(playlistData).forEach(function(key) { if(playlistData[key].includes(song)) { playlistsItsIn.push(key); } }); songData[song] = playlistsItsIn; } result.value = JSON.stringify(songData, null, '\t'); } songInput.addEventListener("change", function() { loadData("songInput", this); }); playlistInput.addEventListener("change", function() { loadData("playlistInput", this); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label&gt;Song text file (generated from &lt;a href="https://webapps.stackexchange.com/q/108103/140514"&gt;this answer&lt;/a&gt;): &lt;input type="file" id="songInput"&gt;&lt;/label&gt; &lt;br&gt; &lt;label&gt;Playlist text file (generated from &lt;a href="https://webapps.stackexchange.com/a/106604/140514"&gt;this answer&lt;/a&gt;): &lt;input type="file" id="playlistInput"&gt;&lt;/label&gt; &lt;br&gt; &lt;textarea style="width: 500px; height: 200px;"&gt;&lt;/textarea&gt;</code></pre> </div> </div> </p> <p>It works on this small set of data I hand-wrote, but it freezes the browser page when I run it on <a href="https://gist.github.com/ZachSaucier/74d5c8bfcde67d95d578894f185bce9c/2e4ccf880fff25ca9810173d90db0085887b0954" rel="nofollow noreferrer">my ~4,000 song list</a> and <a href="https://gist.github.com/ZachSaucier/7ce36c134eaa37f87c6e74c586179a91" rel="nofollow noreferrer">substantial playlist file</a>. </p> <p>How can I do this same thing while helping it perform better so it doesn't freeze my browser tab?</p> <p>I'm theorizing that it would work faster if I keep them as text files and try to parse each of the playlist names if the song is found, but I'm curious if I can speed up/reduce the memory of this object approach somehow. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:11:28.693", "Id": "413273", "Score": "0", "body": "Without looking at your code, to prevent blocking code, Two options, run parallel by using a webWorker to process the data. OR time share using setTimeout to give the browser some of the CPU time while you are crunching the numbers.Data is processed so much faster when you are watching a progress bar, rather than waiting on a hung page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:21:44.360", "Id": "413297", "Score": "0", "body": "@Blindman67 Thanks, I know those are ways to work around the issue, but I am searching more so how to increase the speed/reduce the memory of the JavaScript object approach (though, as the answer I posted says, I'm just going to use the regex search version I made for now)." } ]
[ { "body": "<p>I am still interested if anyone knows how to improve the speed of the JavaScript object approach, but I ended up <strong>searching the playlist text file with regex instead</strong>. It now runs in only a few seconds (without needing a background worker or anything): </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var songInput = document.getElementById(\"songInput\"),\n playlistInput = document.getElementById(\"playlistInput\"),\n result = document.querySelector(\"textarea\");\n\nvar songList, \n playlistData;\n\nfunction loadData(id, elem) {\n if(elem.files\n &amp;&amp; elem.files[0]) {\n let myFile = elem.files[0];\n let reader = new FileReader();\n \n reader.addEventListener('load', function (e) {\n if(id === \"songInput\")\n songList = JSON.parse(e.target.result);\n\n if(id === \"playlistInput\")\n playlistData = e.target.result;\n\n checkBothAdded();\n });\n \n reader.readAsBinaryString(myFile);\n }\n}\n\nfunction checkBothAdded() {\n if(songList\n &amp;&amp; playlistData) {\n getSongPlaylistData();\n }\n}\n\n/* Needed to escape song names that have (), [], etc. */\nfunction regexEscape(s) {\n return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&amp;');\n};\n\nvar songData = {};\nfunction getSongPlaylistData() {\n for(let song of songList) {\n let playlistsItsIn = [];\n\n /* Use regex to search the playlist file for all instances,\n add the playlist name that it's in (if any) to an array. */\n let reg = new RegExp('\"([^\"]*?)\":(?=[^\\\\]]+' + regexEscape(song) + ')', \"g\");\n let result;\n while((result = reg.exec(playlistData)) !== null) {\n playlistsItsIn.push(result[1]);\n }\n \n // Update our song data object\n songData[song] = playlistsItsIn;\n }\n\n result.value = JSON.stringify(songData, null, '\\t');\n}\n\nsongInput.addEventListener(\"change\", function() {\n loadData(\"songInput\", this);\n});\n\nplaylistInput.addEventListener(\"change\", function() {\n loadData(\"playlistInput\", this);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;Please note that this will take a few seconds to run if you have a large amount of songs and playlists.&lt;/p&gt;\n&lt;label&gt;Song text file (generated from &lt;a href=\"https://webapps.stackexchange.com/q/108103/140514\"&gt;this answer&lt;/a&gt;): &lt;input type=\"file\" id=\"songInput\"&gt;&lt;/label&gt;\n&lt;br&gt;\n&lt;label&gt;Playlist text file (generated from &lt;a href=\"https://webapps.stackexchange.com/a/106604/140514\"&gt;this answer&lt;/a&gt;): &lt;input type=\"file\" id=\"playlistInput\"&gt;&lt;/label&gt;\n&lt;br&gt;\n&lt;textarea style=\"width: 500px; height: 200px;\"&gt;&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:20:29.497", "Id": "213678", "ParentId": "213661", "Score": "0" } }, { "body": "<h1>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> for fast lookups</h1>\n\n<p>The main performance cost is the search for songs</p>\n\n<p>The best way to get better lookup performance is to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> to store the songs. Maps use a hash to lookup items and is very fast once the Map has been created.</p>\n\n<p>You can create a map as follows, it adds an array for the playlist.</p>\n\n<pre><code>const songMap = new Map(songList.map(name =&gt; [name,{name,playLists:[]]));\n</code></pre>\n\n<p>Then you iterate the playlist and the songs it contains, adding the playlist to each song</p>\n\n<pre><code>for (const [playListName, songs] of Object.entries(playlists)) {\n for (const songName of songs) {\n const songItem = songMap.get(songName); \n if (songItem) {\n songItem.playLists.push(playListName);\n }\n }\n}\n</code></pre>\n\n<p>You can then iterate the <code>songMap</code> and create the final object containing <code>songNames</code> with arrays of playlists</p>\n\n<pre><code> const songPlaylists = {}; \n for(const song of songMap.values()) {\n songPlaylists[song.name] = song.playLists;\n }\n</code></pre>\n\n<p>Then convert to JSON if you need.</p>\n\n<h2>Why the processed store?</h2>\n\n<p>However I would argue that the whole process is pointless unless you are extracting some higher level information from this process.</p>\n\n<p>Ideally you would store the <code>songs</code> in a <code>Map</code> and each <code>playlist</code> also stored in a <code>Map</code> and would contain a <code>Map</code> of songs. Thus you can lookup playlists a song is in as follows</p>\n\n<pre><code> function findSongPlaylists(songName) {\n const playlists = [];\n for (const playlist of playlistMap.values()) {\n if (playlist.songs.has(songName)) { playLists.push(playList.name) }\n }\n return playlists;\n }\n</code></pre>\n\n<p>To further improve the store, you would assign a unique id (a number) to each song and playlist and use the and do all the searches using ids. This will give even better performance and save a huge amount of RAM.</p>\n\n<p>For casual viewing it is the ideal.</p>\n\n<p>BTW the link you provided showing how you extracted the song data has a very long way of getting the data. All that data is store in the page indexed DB and can be extracted and saved to disk with a few lines of JS. (no need to scroll the page). Use Dev tools > application tab and open indexedDB to find the data.</p>\n\n<h2>Update Extra</h2>\n\n<p>Looking through the link you posted <a href=\"https://webapps.stackexchange.com/a/125423/140514\">Copy Google Play Music songs</a> all the solutions required rather hacky method (due to song list being a view) of slowly scrolling over the data to acquire it. The question is locked thus I am unable to add a better answer. As this question is related I will add a better way of sourcing the data here.</p>\n\n<p>Paste the following snippet into the Dev-Tools console and hit enter. It will extract all the songs and save them to your download directory as a JSON file (named music_[your id].tracks.json)</p>\n\n<p>The json file contains (<code>data</code> refers to the parsed json file)</p>\n\n<ul>\n<li><code>data.fields</code> an array of field names in the same order as in the array</li>\n<li><code>data.tracks</code> an array of records (one per song) containing fields in the same order as in <code>data.fields</code>.</li>\n</ul>\n\n<p>Note I do not use Google Music (Used a friends account so had limited time) and hence I guessed the content. You can add extra fields if you find the array index. To get a single record go to dev-tools > application (tab) > indexedDB > music_[your id] and select a record.</p>\n\n<p>Example record extracted from <code>music_####.tracks</code> For security ids have been masked with <code>#</code> or <code>A...</code></p>\n\n<pre><code>\"########-####-####-####-############\":[\"########-####-####-####-############\",\"Sheep\",\"https://lh4.ggpht.com/AAAAAAA-AAAAAAAAAAAAAA_AAAAAA...\",\"Pink Floyd\",\"Animals\",\"Pink Floyd\",\"sheep\",\"pink floyd\",\"animals\",\"pink floyd\",\"Roger Waters\",\"Rock\",null,620059,4,0,0,0,1977,0,null,null,0,0,1372528857298236,1408583771004924,null,\"AAAAAA...\",\"AAAAAAAA...\",2,\"\",null,\"AAAAAAA...\",\"AAAAAAAA...\",128,1372582779985000,\"https://lh3.googleusercontent.com/AAAAAA_AAAA...\",null,null,[],null,null,null,null,null,null,null,null,null,null,\"AAAAAA...\",[],null,null,null,null,0,null,null,[[\"https://lh3.googleusercontent.com/AAAAA...\",0,2],[\"https://lh3.googleusercontent.com/AAAAA...\",0,1]],true,6,null,1],\n</code></pre>\n\n<p>To keep the file size down the data is in an array. Nulls have been converted to 0.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function () {\n console.log(\"From https://codereview.stackexchange.com/a/213683/120556\"); // DO NOT REMOVE THIS LINE if you publish this snippet.\n console.log(\"Just a moment locating music DB...\");\n const data = {\n dbName:\"\",\n info: \"From Google Play Music App IndexedDB.\\nField names in order of song array index.\\nTo keep JSON size down null has been replaced with 0.\\nDates ar in micro seconds 1/1,000,000 sec (I don't know what date1, date2, date3 represent)\\nImages may require additional query properties.\\nSource https://codereview.stackexchange.com/a/213683/120556\",\n fields: \"GUID,song,image1,band,album,albumArt,composer,genre,length,track,tracks,disk,disks,year,plays,date1,date2,bitrate,date3,image2\".split(\",\"),\n tracks: [],\n };\n const idxs = [0,1,2,3,4,5,10,11,13,14,15,16,17,18,22,24,25,34,35,36]; // idx of info to extract. There are many more field, \n indexedDB.databases().then(info =&gt; {\n const name = data.dbName = info.find(db =&gt; db.name.indexOf(\"music_\") === 0).name;\n indexedDB.open(name).onsuccess = e =&gt; {\n console.log(\"Extracting tracks fro DB \" + name);\n const t = e.target.result.transaction(\"tracks\", IDBTransaction.READ_ONLY); \n t.oncomplete = () =&gt; {\n Object.assign(document.createElement(\"a\"), { download : name + \".tracks.json\", href: URL.createObjectURL(new Blob([JSON.stringify(data)]), {type: \"text/json\" })})\n .dispatchEvent(new MouseEvent(\"click\", {view: window, bubbles: true, cancelable: true}));\n }\n t.objectStore(\"tracks\").openCursor().onsuccess = e =&gt; {\n if (e = e.target.result) { \n Object.values(JSON.parse(e.value)).forEach(t =&gt; data.tracks.push(idxs.map(i=&gt;t[i]===null?0:t[i])));\n e.continue();\n }\n }\n }\n }).catch(()=&gt;console.log(\"Sorry can not complete data dump :(\"));\n})()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>To extract a record from the JSON </p>\n\n<pre><code>// data is the parsed JSON file\nconst songName = \"A song name\";\nconst songFieldIdx = data.fields.indexOf(\"song\");\nconst track = data.tracks.find(rec =&gt; rec[songFieldIdx] === songName);\n</code></pre>\n\n<p>To convert track array record to track object</p>\n\n<pre><code>const trackObj = {}\nfor(const field of data.fields) { trackObj[field] = track.shift() }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T04:28:12.810", "Id": "413320", "Score": "0", "body": "Thanks for the input! Maps are a good way to go but I haven't really used them before so this is a good step for me. \nI can't seem to get the `indexedDB` to give me any readable data. Any idea how to work with it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:38:03.780", "Id": "413435", "Score": "0", "body": "@ZachSaucier I have updated my answer with info on how to dump indexedDB to your download directory and then basic usage. NOTE if you have more than one Google Music account on the computer the snippet will get the first one. You will need to modify it to extract the one you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-23T17:59:20.357", "Id": "414069", "Score": "0", "body": "I'm trying to find playlist information using this DB approach but can't seem to find any. Any idea where that might be stored? I suppose it could just be on Google Play's server side" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-24T01:31:43.267", "Id": "414108", "Score": "0", "body": "@ZachSaucier if its not in the DB then likely a XHR request. Open Dev tools and go to the network tab. On main Google Music select a play list, back on dev tools, network if there is any data exchange it will show up there. It will likely contain index references to songs rather then song names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-24T02:15:57.163", "Id": "414120", "Score": "0", "body": "After looking at the Networks tab, it doesn't appear to be through an XHR request. The only potentially relevant XHR request is the same no matter what the playlist is. The songs are also loaded one by one so I don't think that'd make much sense to do over the network" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:46:46.630", "Id": "213683", "ParentId": "213661", "Score": "3" } } ]
{ "AcceptedAnswerId": "213683", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T16:32:49.660", "Id": "213661", "Score": "3", "Tags": [ "javascript", "performance", "object-oriented", "search" ], "Title": "Listing the playlists on which each song appears" }
213661
<p>I am trying to optimize matrix multiplication on a single processor by optimizing cache use. I am implemented a block multiplication and used some loop unrolling, but I'm at a loss on how to optimize further though it is clearly still not very optimal based on the benchmarks.</p> <p>Matrices are in column major order.</p> <p>Any suggestions would be appreciated!</p> <pre><code>const int blockSize = 12; void readBlock(double outputMatrix[], double inputMatrix[], int beginX, int endX, int beginY, int endY, int n) { int i = 0; for (int x = beginX; x &lt; endX; x++) { for (int y = beginY; y &lt; endY; y++) { outputMatrix[i] = inputMatrix[x*n + y]; i++; } for (int y = endY-beginY; y &lt; blockSize; y++) { outputMatrix[i] = 0; i++; } } for (int x = endX - beginX; x &lt; blockSize; x++) { for (int y = 0; y &lt; blockSize; y++) { outputMatrix[i] = 0; i++; } } } int min(int a, int b) { if (a &lt; b) return a; else return b; } void multiplyMatrices(double inputMatrix1[], double inputMatrix2[], double outputMatrix[], int endx, int endy) { for (int i = 0; i &lt; endx; i++) { for (int j = 0; j &lt; endy; j++) { double cvalue = outputMatrix[i*blockSize + j]; for (int l = 0; l &lt; blockSize; l+=2) { double a1 = inputMatrix1[l*blockSize + j] * inputMatrix2[i*blockSize + l];; double a2 = inputMatrix1[(l+1)*blockSize + j] * inputMatrix2[i*blockSize + l + 1]; cvalue += a1 + a2; } outputMatrix[i*blockSize + j] = cvalue; } } } void writeMatrix(double* inputMatrix, double* outputMatrix, int beginX, int endX, int beginY, int endY, int n) { int k,l=0; for (int i = beginX; i &lt; endX; i++) { k = 0; for (int j = beginY; j &lt; endY; j++) { outputMatrix[i*n + j] = inputMatrix[l*blockSize+k]; k++; } l++; } } void square_dgemm(int n, double* A, double* B, double* C) { for (int x = 0; x &lt; n; x += blockSize) { for (int y = 0; y &lt; n; y += blockSize) { double CC[blockSize*blockSize]; readBlock(CC, C, x, min(x + blockSize, n), y, min(y + blockSize, n), n); for (int z = 0; z &lt; n; z += blockSize) { double BC[blockSize*blockSize]; double AC[blockSize*blockSize]; int zAdj = min(z + blockSize, n); readBlock(AC, A, z, zAdj,y, min(y+blockSize, n), n); readBlock(BC, B, x, min(x + blockSize, n), z,zAdj, n); multiplyMatrices(AC, BC, CC, min(x+blockSize,n)-x,min(y+blockSize,n)-y); } writeMatrix(CC, C, x, min(x + blockSize, n), y, min(y + blockSize, n), n); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:19:34.597", "Id": "413259", "Score": "0", "body": "What compiler and what flags are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:20:37.970", "Id": "413260", "Score": "0", "body": "cc -c -Wall -std=gnu99 -O3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:22:49.617", "Id": "413262", "Score": "0", "body": "What is `cc`? If you do `cc --version` does it identify as gcc, clang, icc, ... ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:28:46.380", "Id": "413263", "Score": "0", "body": "cc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:30:54.570", "Id": "413264", "Score": "0", "body": "What's the target processor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T17:33:19.647", "Id": "413266", "Score": "0", "body": "Processor name : Intel(R) Xeon(R) E5-2695 v3\nPackages(sockets) : 2\nCores : 28\nProcessors(CPUs) : 28\nCores per package : 14\nThreads per core : 1\n===== Cache sharing =====\nCache Size Processors\nL1 32 KB no sharing\nL2 256 KB no sharing\nL3 35 MB (0,1,2,3,4,5,6,14,15,16,17,18,19,20)(7,8,9,10,11,12,13,21,22,23,24,25,26,27)" } ]
[ { "body": "<p>The block size shouldn't be 12 (more like 1 to 2 orders of magnitude bigger), but I don't know exactly what it <em>should</em> be and it's easier to try some values and see how they work out than trying to predict it.. Likely the blocks shouldn't be square either (and therefore, not all three the same shape), because the eventual kernel will \"prefer\" a certain direction over the other.</p>\n\n<p>There are inherent inefficiencies in <code>multiplyMatrices</code> due to its \"shape\" and we can calculate in advance what shape it <em>should</em> have. The Intel(R) Xeon(R) E5-2695 v3 has the Haswell micro-architecture, which has these key properties:</p>\n\n<ul>\n<li>Vector FMA per cycle: 2</li>\n<li>Vector FMA latency: 5</li>\n<li>Vector loads per cycle: 2</li>\n<li>Vector size: 256bit (4 doubles)</li>\n</ul>\n\n<p>This means that, in order to max out the amount of arithmetic that happens, we will need at least 2*5=10 (the throughput-latency product) independent vector accumulators. Unrolling by 2 was a good start, but not close to what is required. Just unrolling more would be easy but there is more to it.</p>\n\n<p>The limited number of loads, only a 1:1 ratio with FMAs at most (otherwise it starts to eat into the arithmetic throughput), means that we must somehow re-use data within a single iteration of the inner loop. Having two loads for each FMA (loading elements from each matrix) is twice the budget, that's definitely out.</p>\n\n<p>So the inner loop itself needs to have a somewhat rectangular footprint to enable data re-use, and that rectangle needs to have an area of at least 10 4-wide vectors. For example it could be 2x5, 5x2, 3x4, 4x3.. that's about it. It can't really be bigger, then we would run out of registers, and spilling accumulators is <em>super</em> out. 3x5 seems like it could be possible, but it does not only require 15 accumulators but also some extra registers to hold the values from the input matrixes and it won't fit. By the way an other way to view the \"rectangular footprint\" is unrolling the <em>outer two</em> loops. The above sizes are all in numbers of vectors, so in a scalar view one of the directions gets 4 times as big again.</p>\n\n<p>As an example (consider this mainly clarificational as in \"how to put all of the above abstract-sounding considerations together into code\" and not so much \"copy&amp;paste code\") I'll pick 5x2 (20x2 scalars). That means the main part of the code would look something like this:</p>\n\n<pre><code>#include &lt;x86intrin.h&gt;\n\n// must be multiple of 20\n#define BLOCK_H 120\n\n// must be multiple of 2\n#define BLOCK_W 128\n\n// this is the number of columns of mat1 and the number of rows of mat2\n// has no relation to the size of the result block\n// can be whatever\n#define BLOCK_K 128\n\nvoid matmulBlock(double *result, double *mat1, double *mat2) {\n size_t i, j, k;\n __m256d sum0, sum1, sum2, sum3, sum4;\n __m256d sum5, sum6, sum7, sum8, sum9;\n __m256d tmp0, tmp1, tmp2, tmp3, tmp4;\n __m256d m1, m2;\n size_t N = BLOCK_H;\n for (i = 0; i &lt; BLOCK_W; i += 2) {\n for (j = 0; j &lt; BLOCK_H; j += 20) {\n sum0 = _mm256_load_pd(&amp;result[i * N + j]);\n sum1 = _mm256_load_pd(&amp;result[i * N + j + 4]);\n sum2 = _mm256_load_pd(&amp;result[i * N + j + 8]);\n sum3 = _mm256_load_pd(&amp;result[i * N + j + 12]);\n sum4 = _mm256_load_pd(&amp;result[i * N + j + 16]);\n\n sum5 = _mm256_load_pd(&amp;result[i * N + j + N]);\n sum6 = _mm256_load_pd(&amp;result[i * N + j + N + 4]);\n sum7 = _mm256_load_pd(&amp;result[i * N + j + N + 8]);\n sum8 = _mm256_load_pd(&amp;result[i * N + j + N + 12]);\n sum9 = _mm256_load_pd(&amp;result[i * N + j + N + 16]);\n\n for (k = 0; k &lt; BLOCK_K; k++) {\n m1 = _mm256_set1_pd(mat2[i * N + k]);\n m2 = _mm256_set1_pd(mat2[i * N + k + N]);\n\n tmp0 = _mm256_load_pd(&amp;mat1[k * N + j]);\n tmp1 = _mm256_load_pd(&amp;mat1[k * N + j + 4]);\n tmp2 = _mm256_load_pd(&amp;mat1[k * N + j + 8]);\n tmp3 = _mm256_load_pd(&amp;mat1[k * N + j + 12]);\n tmp4 = _mm256_load_pd(&amp;mat1[k * N + j + 16]);\n\n sum0 = _mm256_fmadd_pd(m1, tmp0, sum0);\n sum1 = _mm256_fmadd_pd(m1, tmp1, sum1);\n sum2 = _mm256_fmadd_pd(m1, tmp2, sum2);\n sum3 = _mm256_fmadd_pd(m1, tmp3, sum3);\n sum4 = _mm256_fmadd_pd(m1, tmp4, sum4);\n\n sum5 = _mm256_fmadd_pd(m2, tmp0, sum5);\n sum6 = _mm256_fmadd_pd(m2, tmp1, sum6);\n sum7 = _mm256_fmadd_pd(m2, tmp2, sum7);\n sum8 = _mm256_fmadd_pd(m2, tmp3, sum8);\n sum9 = _mm256_fmadd_pd(m2, tmp4, sum9);\n }\n\n _mm256_store_pd(&amp;result[i * N + j], sum0);\n _mm256_store_pd(&amp;result[i * N + j + 4], sum1);\n _mm256_store_pd(&amp;result[i * N + j + 8], sum2);\n _mm256_store_pd(&amp;result[i * N + j + 12], sum3);\n _mm256_store_pd(&amp;result[i * N + j + 16], sum4);\n\n _mm256_store_pd(&amp;result[i * N + j + N], sum5);\n _mm256_store_pd(&amp;result[i * N + j + N + 4], sum6);\n _mm256_store_pd(&amp;result[i * N + j + N + 8], sum7);\n _mm256_store_pd(&amp;result[i * N + j + N + 12], sum8);\n _mm256_store_pd(&amp;result[i * N + j + N + 16], sum9);\n }\n }\n}\n</code></pre>\n\n<p>By the way I didn't test this, I converted it from code that <em>is</em> tested, but it was single precision and row-major and some miscellaneous differences, I may have made some errors in changing it just now. Even if its works, this is ultimately not the most efficient code, this is just step 1: writing code to fit the basic parameters of the machine - it's not optimized beyond that.</p>\n\n<p>Some assumptions are made: <code>result</code> and <code>mat1</code> both 32-aligned, and zero padding in empty areas (same block size always).</p>\n\n<p>GCC 4.8.5 needs <code>-mfma</code> to compile this but cannot take <code>-march=haswell</code> yet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T19:31:39.967", "Id": "213668", "ParentId": "213662", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T16:58:21.207", "Id": "213662", "Score": "3", "Tags": [ "performance", "algorithm", "c", "matrix", "cache" ], "Title": "Cache-optimized matrix multiplication algorithm in C" }
213662
<p>I've started learning Python yesterday with the intention of studying machine learning. Before this, my experience with programming was exclusive to my first semester where I had a C course.</p> <p>I decided to work towards a final objective: have an AI learn how to win the snake game. For that goal, I had to make the actual game. I didn't want to copy an already made game as I'm still learning. So with that in mind, I spent an entire night building my little snake game.</p> <p>I would like the game to be as good as possible before I started the machine learning part, which is why I'm posting it here. My biggest problem right now is controlling the speed of the game. I achieved this by limiting the FPS number based on the current score but it seems like a cheap way to do it.</p> <p>I divided the game in two files: vars.py where I define most variables and functions and snake.py with the actual game and a few other things. This is the way I was taught to program so if it's wrong or not done please feel free to point that out.</p> <p><strong>vars.py</strong></p> <pre><code>import random import math width = 800 height = 600 BG = 255, 255, 255 FOOD_C = 128, 0, 0 BODY_C = 0, 0, 0 sqr_size = 10 SPEED = sqr_size def dist(a, b): return math.sqrt((b.pos[0] - a.pos[0])**2 + (b.pos[1] - a.pos[1])**2) def check_food(snake, food): #Check if food is eaten if dist(snake, food) &gt; sqr_size: return False else: return True def loser(snake, food): #Check if lost the game if snake.pos[0]&lt;sqr_size or snake.pos[0]&gt;width-sqr_size: return True if snake.pos[1]&lt;sqr_size or snake.pos[1]&gt;height-sqr_size: return True for i in snake.body[1:]: if i == snake.pos: return True def game_speed(snake): if (10 + snake.score()//2) &lt; 30: return 10 + snake.score()//2 else: return 30 class Snake(object): def __init__(self): self.pos = [random.randint(1, (width-sqr_size)/10)*10, random.randint(1, (height-sqr_size)/10)*10] self.mov = "UP" self.body = [self.pos[:]] def change_mov(self, key): #Decide where to move if key == "UP" and self.mov != "DOWN": self.mov = key if key == "DOWN" and self.mov != "UP": self.mov = key if key == "RIGHT" and self.mov != "LEFT": self.mov = key if key == "LEFT" and self.mov != "RIGHT": self.mov = key def score(self): return len(self.body) def move(self, eat): #Snake movement if self.mov == "UP": self.pos[1] = self.pos[1] - SPEED if self.mov == "DOWN": self.pos[1] = self.pos[1] + SPEED if self.mov == "LEFT": self.pos[0] = self.pos[0] - SPEED if self.mov == "RIGHT": self.pos[0] = self.pos[0] + SPEED self.body.insert(0, self.pos[:]) if not eat: self.body.pop() class Food(object): def __init__(self): self.pos = [random.randint(1, (width-sqr_size)/10)*10, random.randint(1, (height-sqr_size)/10)*10] </code></pre> <p><strong>snake.py</strong></p> <pre><code>import pygame, sys import vars #Initialising pygame pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Times New Roman', 30) clock = pygame.time.Clock() screen = pygame.display.set_mode((vars.width,vars.height)) pygame.display.update() #Initialising variables lost = False eat = False snake = vars.Snake() food = vars.Food() screen.fill(vars.BG) key1 = "0" def whatkey(event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: return "LEFT" if event.key == pygame.K_RIGHT: return "RIGHT" if event.key == pygame.K_UP: return "UP" if event.key == pygame.K_DOWN: return "DOWN" while not lost: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() key1 = whatkey(event) #How the game works snake.change_mov(key1) eat = vars.check_food(snake, food) snake.move(eat) if eat: food = vars.Food() lost = vars.loser(snake, food) #Screen drawings screen.fill(vars.BG) for i in snake.body: pygame.draw.circle(screen, vars.BODY_C, (i[0], i[1]), vars.sqr_size, 0) pygame.draw.circle(screen, vars.FOOD_C, (food.pos[0], food.pos[1]), vars.sqr_size, 0) pygame.display.set_caption("Snake. Your score is: {}".format(snake.score())) pygame.display.update() #Control of the game speed via fps #Not related to the SPEED variable. That is for movement msElapsed = clock.tick(vars.game_speed(snake)) #Lose screen pygame.display.update() screen.fill(vars.BG) textsurface1 = myfont.render('You lost. Your score is:', False, (0, 0, 0)) textsurface2 = myfont.render("{}".format(snake.score()), False, (0, 0, 0)) screen.blit(textsurface1,(250, 200)) screen.blit(textsurface2,(380,280)) pygame.display.update() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T19:45:54.937", "Id": "413288", "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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T20:17:53.293", "Id": "413292", "Score": "0", "body": "@Mast I'm sorry, I didn't know. However, the edits I made weren't to incorporate the answers. I changed circles to squares, for example and colours I believe but didn't know I shouldn't. I won't do it again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T23:00:40.117", "Id": "413302", "Score": "0", "body": "Feel free to post a follow-up question with improved code if your code has changed significantly enough in the meantime. You can save such edits for then. No problem." } ]
[ { "body": "<p>I'm on my phone so I'll just mention something minor I noticed. </p>\n\n<p><code>check_food</code>'s return is redundant. <code>dist(snake, food) &gt; sqr_size</code> already evaluates to a boolean value. You just need to negate that:</p>\n\n<pre><code>def check_food(snake, food): #Check if food is eaten\n return not dist(snake, food) &gt; sqr_size\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>def check_food(snake, food): #Check if food is eaten\n return dist(snake, food) &lt;= sqr_size\n</code></pre>\n\n<p>And there's a similar situation in <code>loser</code>. The first two conditions are just returning <code>True</code>. They could be \"connected\" via <code>or</code> to be simplified. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:46:22.857", "Id": "413280", "Score": "0", "body": "You are absolutely right. I deleted the check_food function altogether and just used `eat = vars.dist(snake, food) < vars.sqr_size`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:55:44.773", "Id": "413284", "Score": "0", "body": "@AndréRocha Unless you've double checked that logic, you may want to use `<=` instead, as that would be the opposite of `>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T19:08:58.323", "Id": "413285", "Score": "0", "body": "I did, it was eating the food while it was walking on an adjacent space. This way that won't happen" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:37:37.000", "Id": "213666", "ParentId": "213665", "Score": "3" } }, { "body": "<p>For efficiency reasons, you should always do <code>x1**2 + y1**2 &lt; r**2</code> rather than <code>sqrt(x1**2 + y1**2) &lt; r</code>, because <code>sqrt</code> is much much slower than <code>pow</code>. Because <a href=\"https://en.wikibooks.org/wiki/Algorithms/Distance_approximations#You_don%27t_need_a_square_root_to_compare_distances\" rel=\"nofollow noreferrer\">You don't need a square root to compare distances</a>. This is the special case of <code>x1**2 + y1**2 &lt; x2**2 + y2**2</code>. </p>\n\n<p>Sometimes <code>sqrt</code> distances computing when you have a bunch of things on your screen becomes the slowest thing in your program. And there is absolutely no reason to do it.</p>\n\n<p>My suggestion is to keep everything squared, until you really need to compute <code>sqrt</code> (which you don't)</p>\n\n<hr>\n\n<p>Also, storing a direction in a string works (<code>\"DOWN\"</code>), but isn't very practical, it is a beginner pattern called 'stringly typed code'. You could instead make a constant called <code>DOWN</code> which corresponds to the vector pointing down (<code>(0, -1)</code> to make it simple or <code>0 - 1j</code> if you like complex numbers (best imo) or a custom object if you like OOP). You can then replace:</p>\n\n<pre><code>if self.mov == \"UP\": \n self.pos[1] = self.pos[1] - SPEED\nif self.mov == \"DOWN\": \n self.pos[1] = self.pos[1] + SPEED\nif self.mov == \"LEFT\": \n self.pos[0] = self.pos[0] - SPEED\nif self.mov == \"RIGHT\": \n self.pos[0] = self.pos[0] + SPEED\n\n# becomes\n\nself.pos += self.mov\n</code></pre>\n\n<p>with constants, math becomes easier:</p>\n\n<pre><code>UP = 0 + 1j\nDOWN = 0 - 1j\nLEFT = -1 + 0j\nRIGHT = 1 + 0j\n\n2*DOWN + 5*LEFT # means move 2 cases down and 5 left how intuitive\n\nif key == \"UP\" and self.mov != \"DOWN\":\n self.mov = key\nif key == \"DOWN\" and self.mov != \"UP\":\n self.mov = key\nif key == \"RIGHT\" and self.mov != \"LEFT\":\n self.mov = key\nif key == \"LEFT\" and self.mov != \"RIGHT\":\n self.mov = key\n\n# becomes\n\nif key - self.mov:\n self.mov = key\n</code></pre>\n\n<p>It takes time getting used to but it is worth it, you can always use tuples but they are the same except math doesn't work with them. The fact is Complex numbers are awesome it generalises nicely for arbitrary directions and distances. And if you assign to constants, you don't ever need to see them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:33:23.187", "Id": "413312", "Score": "0", "body": "I'll also suggest looking into ``numpy`` for direction vectors. It's not strictly necessary for 2D vectors (I actually really like that idea of using complex numbers, I might borrow that), but it'll certainly show up once you start looking into AI code, so you might as well get used to it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T09:20:40.590", "Id": "413345", "Score": "0", "body": "Nice use of complex numbers. I would use `Enum`s instead of constants. They are even more clear" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T21:12:45.040", "Id": "213673", "ParentId": "213665", "Score": "7" } }, { "body": "<p>This is a general comment on the structure of the code, and in particular how you may want to think about redesigning some of it.</p>\n\n<p>Given your end goal is to have AI learn to play snake, you may wish to abstract away the input source, the graphics, and also anything relating to time.</p>\n\n<p>Rather than formulate the game of snake as checking which key the user has selected at certain times, you may want to structure it as a decision each turn. Yes, this is a bit of a modification to snake, but it may be easier for you to get started. So this basically eliminates the time factor.</p>\n\n<p>Yes, time is of major importance when it comes to human players, but developing ML that's sensitive to time constraints is more complicated. Maybe you can make it a stretch goal? :)</p>\n\n<p>So, in general, I would have the structure as this:</p>\n\n<p>[User] &lt;-> [Game] &lt;-> [Graphics]</p>\n\n<p>When developing your AI, you swap out the user module for the AI. You also may want to have a graphics module you can swap in and out. You don't want graphics to limit how fast your AI can learn, but you may want to turn it on to see what your AI is doing from time to time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T07:07:55.710", "Id": "213698", "ParentId": "213665", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:19:46.357", "Id": "213665", "Score": "6", "Tags": [ "python", "beginner", "pygame", "snake-game" ], "Title": "First Python program: Snake" }
213665
<p>I have an Angular component and it is just a label which renders a value and if it has an associated pipe, the output of the pipe should be rendered as value of the label. But I don't want to declare all the pipes in the component. Currently I would like to use the currency pipe and the date pipe with their parameters. But maybe I can extend the component to use other pipes.</p> <p>Would you pass the pipes as input parameter of the component or what would be your approach to achieve that? Any idea?</p> <p>app.component.ts</p> <pre><code>&lt;app-custom-label value="10000" title="My Title for a Currency render" datatype="currency" param="EUR"&gt;&lt;/app-custom-label&gt; &lt;app-custom-label value="01.10.1980" title="My Title for a Date render" datatype="date" param="dd MMMM"&gt;&lt;/app-custom-label&gt; </code></pre> <p>custom.label.component.html</p> <pre><code>&lt;h1&gt;{{ title }}&lt;/h1&gt; &lt;label&gt; {{ value }} &lt;/label&gt; </code></pre> <p>custom.label.component.ts</p> <pre><code>import { Component, Input, OnInit } from '@angular/core'; import { DataType } from './type'; import { CurrencyPipe, DatePipe } from '@angular/common'; import { registerLocaleData } from '@angular/common'; import localeDe from '@angular/common/locales/de'; import localeDeExtra from '@angular/common/locales/extra/de'; registerLocaleData(localeDe, 'de-DE', localeDeExtra); @Component({ selector: 'app-custom-label', templateUrl: './custom.label.component.html' }) export class CustomLabelComponent implements OnInit { @Input() value: string; @Input() title: string; @Input() datatype: DataType; @Input() param: string; constructor() {} ngOnInit(){ if (this.datatype === "currency") { this.value = (new CurrencyPipe('de-DE')).transform(this.value, this.param, true); } else if (this.datatype === "date") { this.value = (new DatePipe('de-DE')).transform(this.value, this.param); } } } </code></pre> <p>Here you have my StackBlitz. If you can see, I pass a type of a pipe and its params as parameters, if I want to use any pipe. The component could also render a label without using a pipe. </p> <p><a href="https://stackblitz.com/edit/angular-label-render" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-label-render</a></p>
[]
[ { "body": "<p>The syntax of both the pipes:</p>\n\n<p><a href=\"https://angular.io/api/common/CurrencyPipe\" rel=\"nofollow noreferrer\">Currency Pipe</a></p>\n\n<pre><code>{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}\n</code></pre>\n\n<p>and <a href=\"https://angular.io/api/common/DatePipe\" rel=\"nofollow noreferrer\">Date Pipe</a></p>\n\n<pre><code>{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}\n</code></pre>\n\n<p>In my understanding, we must use pipes to integrate directly into the \"templates\" and avoid writing excess code in the component.\nIn your approach, passing the pipe names and the other parameters appears to me as a redundant step.</p>\n\n<p>My approach would be:</p>\n\n<pre><code>&lt;app-custom-label value=\"{{10000 | currency:'EUR':true:null:'de-DE'}}\" title=\"My Title for a Currency render\"&gt;&lt;/app-custom-label&gt;\n&lt;app-custom-label value=\"{{'01.10.1980' | date:'dd MMMM':null:'de-DE'}}\" title=\"My Title for a Date render\"&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:48:28.773", "Id": "215732", "ParentId": "213672", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T20:57:23.537", "Id": "213672", "Score": "1", "Tags": [ "formatting", "typescript", "angular-2+" ], "Title": "Angular component to render currency or date values" }
213672
<p>I have written some python code to play <a href="https://scratch.mit.edu/projects/37896272/" rel="nofollow noreferrer">this scratch game.</a> But it is to slow to function correctly because each frame if it clicks, it takes a screenshot of almost the same thing like this</p> <pre><code> ____ _ _ | ______ _|______ | Click Screenshot ____ _ _ | ______ __|_____ | </code></pre> <p>And so it clicks again because it thinks that it is still down low enough to jump, and so it double jumps to its death.</p> <p>Any ideas on how to improve the speed, to get it working? Here is the code:</p> <pre><code>#Circle on scratch destroyer import numpy as np #Numpy import screenUtils #My custom code that gets the screenshot (Not a problem the screenshots are lightning fast) from time import sleep, time #Sleep for sleep and time for time checking from pymouse import PyMouse #Mouse clicking from pykeyboard import PyKeyboardEvent #Failsafe key is q from threading import Thread #Threading for keyboard input and the screen shot loop m = PyMouse() #Init mouse jumpHeight = 40 #How high the player jumps each click class safe(PyKeyboardEvent): #I named it safe because it has the failsafe def xtra(self): self.tog = False #Toggle def tap(self, keycode, character, press): """ Subclass this method with your key event handler. It will receive the keycode associated with the key event, as well as string name for the key if one can be assigned (keyboard mask states will apply). The argument 'press' will be True if the key was depressed and False if the key was released. """ if self.lookup_char_from_keycode(keycode) == "q" and press: #If the event is a press of the key "q" self.tog = not self.tog #Toggle the screenshot loop else: pass click = (575, 450) #where on screen to click e = safe() #Init keyboard event handler e.xtra() def checkClick(screen): lineY = [] #The Y axis of all the line pixels circP = [] #The pixels of the right side of the circle if e.tog: #Only execute if the safegaurd is off pX = 0 #Pos X pY = 0 #Pos Y width = len(screen[0]) #Width of the screenshot whiteFilter = [] #Init the white filter for w in range(width): whiteFilter.append(np.array([255,255,255])) #Fill the white filter for y in range(len(screen)): #For each Y layer if np.array_equal(whiteFilter, screen[y]): #If the layer is white, skip it #meh pass else: for x in range(len(screen[y])): #For each pixel on this layer if screen[y][x][0] &gt;= 30 and screen[y][x][0] &lt;= 50 and screen[y][x][1] &gt;= 50 and screen[y][x][1] &lt;= 65 and screen[y][x][2] &gt;= 130 and screen[y][x][2] &lt;= 150: lineY.append(pY) #Found a line pixel if screen[y][x][0] &gt;= 60 and screen[y][x][0] &lt;= 70 and screen[y][x][1] &gt;= 75 and screen[y][x][1] &lt;= 85 and screen[y][x][2] &gt;= 175 and screen[y][x][2] &lt;= 185: circP.append((pX, pY)) #Found a circle pixel pX += 1 #Increment X pos pY += 1 #Increment Y pos pX = 0 #Reset X Pos pix = [] #Init pix array (this stores all circle pixels at X position 35 of the screenshot) for pos in circP: if pos[0] == 35: pix.append(pos) final = [] found = False for p in pix: #This loop gets the two inner pixels of the circle at X position 35 for P in pix: if found == False: if abs(p[1] - P[1]) == 87: final.append(p) final.append(P) found = True bottom = () #The bottom pixel if len(final) == 2: #Double check the length of final try: #Handle random exceptions if you turn off safeguard when not on the game if final[0][1] &gt; final[1][1]: #Find the bottom pixel bottom = final[1] else: bottom = final[0] if max(lineY) - bottom[1] &gt;= jumpHeight: #Detect if the program should click print("click") m.click(click[0], click[1]) except: pass def screenLoop(): while True: if e.tog: screen = screenUtils.grab_screen(405,325,468,675) #Screenshot screena = np.array(screen) start = time() checkClick(screena) stop = time() print("Time: " + str(stop - start)) t = Thread(target=screenLoop) t.daemon = True t.start() e.run() </code></pre>
[]
[ { "body": "<p>You should change :</p>\n\n<pre><code> found = False\n for p in pix: #This loop gets the two inner pixels of the circle at X position 35\n for P in pix:\n if found == False:\n if abs(p[1] - P[1]) == 87:\n final.append(p)\n final.append(P)\n found = True\n</code></pre>\n\n<p>by :</p>\n\n<pre><code> for p in pix: #This loop gets the two inner pixels of the circle at X position 35\n for P in pix:\n if abs(p[1] - P[1]) == 87:\n final.append(p)\n final.append(P)\n break\n else: continue\n break\n</code></pre>\n\n<p>This breaks the two loops instead of pointlessly running the loop after it's found.</p>\n\n<hr>\n\n<p>Second thing, you use Threads, they aren't executed in parallel due to GIL, this can be a problem if you're looking for performance, consider multiprocessing if needed.</p>\n\n<hr>\n\n<p>This code is inefficient, assign <code>screen[y][x]</code> to a variable to avoid lookups, and do you really need to check every pixel of every frame ? This will be difficult to run in real time without melting your CPU, for the game you linked, you probably only need one column of pixel. Also it seems that pixels are either white or not white, so these big conditions are a bit superfluous.</p>\n\n<pre><code> for x in range(len(screen[y])): #For each pixel on this layer\n if screen[y][x][0] &gt;= 30 and screen[y][x][0] &lt;= 50 and screen[y][x][1] &gt;= 50 and screen[y][x][1] &lt;= 65 and screen[y][x][2] &gt;= 130 and screen[y][x][2] &lt;= 150:\n lineY.append(pY) #Found a line pixel\n if screen[y][x][0] &gt;= 60 and screen[y][x][0] &lt;= 70 and screen[y][x][1] &gt;= 75 and screen[y][x][1] &lt;= 85 and screen[y][x][2] &gt;= 175 and screen[y][x][2] &lt;= 185:\n circP.append((pX, pY)) #Found a circle pixel\n</code></pre>\n\n<hr>\n\n<p>Your code would be easier to read if it was broken down into multiple functions and if you used good variable names (not single/double letters, snake_case, PEP8 compliant).</p>\n\n<hr>\n\n<p>Take time to research about <code>for else</code> notation, the <code>GIL</code> and parallel computing in python (to make it simple: Theads run on one Core, Processes run on multiple Cores). <code>screen[y][x]</code> calls multiple functions behind the scene that is why you should assign in this case. <code>PEP8</code> gives good advices on how to write readable code (It is a question of habit, use a linter, it can help).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:56:14.970", "Id": "413300", "Score": "1", "body": "Wow thanks for this information, also yes I probably only need to check row 35 of my screenshot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T16:16:22.840", "Id": "413414", "Score": "0", "body": "I use VSCode with pylinter installed, so I already use a" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:45:22.503", "Id": "213680", "ParentId": "213677", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T22:19:29.343", "Id": "213677", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "ai" ], "Title": "Game AI to slow to work" }
213677
<p>Problem: Given an integer between 1 and 32767 print the individual digits with 2 spaces between them. </p> <p>I am using <em>C How To Program</em> but this is not homework. The book has not gotten to arrays or anything more complicated than looping structures and function. I try to avoid using those structures and concepts that have not been introduced yet. I get the digits to separate and output. I was wondering if there is a better way to do this using the tools I have. </p> <p>My Code:</p> <pre><code>//----------------------------------------------------------------------------- // Program: EX5_22.c - Separating Digits // Programmer: Joseph Cunningham // Class: CsC_20 - c // Date: 2/16/19 // // This program will prompt the user for a number from 1 - 32767. It will then // output that number separated into its constituent digits with 2 spaces // between each digit //----------------------------------------------------------------------------- #include&lt;stdio.h&gt; #include&lt;math.h&gt; int getNumLength(int number); void separate(int number, int power); // Fucntion prototype int main (void) { // Variable declaration int number; // User entered number to digitize int power; // Power to generate divisor // Prompt user for number printf("Please input a number (1-32767): "); scanf("%d", &amp;number); // Get the power for the divisor power = getNumLength(number); // Output digits separate(number, power); return 0; } //----------------------------------------------------------------------------- // Function: getPower(number) - counts the number of digits in the number to // generate a power // Input: int number - the user entered number // Output: none // Return value - length of thr number //----------------------------------------------------------------------------- int getNumLength(int number) { int length; // the length of number while (number != 0) { number = number / 10; length++; } return length; } //----------------------------------------------------------------------------- // Function: separate(number) - separates and displays an integer between 1 // -32767 into its digits // Input: int number - intger betwenn 1 - 32767, int power - power for divisor // Output: numbers digits separated by 2 spaces // Return value: none //----------------------------------------------------------------------------- void separate(int number, int power) { int divisor; // the divisor from power int i; // loop counter for(i = power - 1; i &gt;=0; i--) { divisor = (int)pow(10, i); printf("%d ", number / divisor); number = number % divisor; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:09:29.780", "Id": "413304", "Score": "0", "body": "Looks interesting (Is `case` `more complicated than looping`?). But, as the code is known not to work as intended, it is [off topic here](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:15:22.930", "Id": "413305", "Score": "0", "body": "I'll change the code above to one that works as intended but may need optimizing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:23:54.037", "Id": "413308", "Score": "0", "body": "Sounds promising: Welcome to Code Review! Even *if* your post gets closed before you're done, it will be bound to be re-opened once fixed. (Closing would be for the better: it is an indication that the question is not in a state to be answered.) Note that you should not alter your code a considerable time after posting, and are [forbidden to so in a way that invalidates answers](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:34:29.980", "Id": "413313", "Score": "2", "body": "Can I take it down and try again later?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T00:36:24.630", "Id": "413314", "Score": "0", "body": "Yes, of course. Removing content that *is* useful for others is frowned upon, but possible, too." } ]
[ { "body": "<blockquote>\n<pre><code> // Variable declaration\n\n int number; // User entered number to digitize\n int power; // Power to generate divisor\n</code></pre>\n</blockquote>\n\n<p>So <code>//</code> is a C++ comment that is only available in newer versions of C. </p>\n\n<p>Declaring variables at the beginning of the block is an old C standard that you don't need in newer versions of C. The modern standard (in C and most other languages) is to put variable declarations as close to first use as possible. For <code>number</code>, you're pretty much there. For <code>power</code>, it could be declared with the initialization. </p>\n\n<pre><code> /* Power to generate divisor */\n int power = getNumLength(number);\n</code></pre>\n\n<p>I put the comment on a separate line so as to be more readable and to avoid side scroll (not so much here as in other examples). </p>\n\n<p>I would have probably have written that </p>\n\n<pre><code> int digit_count = count_digits(number);\n</code></pre>\n\n<p>That's clearer in my opinion and does not require an explanatory comment. We're counting the number of digits and storing the result in a variable. We'll know what the variable is later, because we call it <code>digit_count</code>. </p>\n\n<p>I prefer snake_case, particularly in C. It relies less on the reader (who may not be a native English speaker) being able to recognize capital letters. That said, camelCase is quite common. Which to use is up to you so long as you do so consistently. </p>\n\n<p>I also changed to a four column indent. That is more common than two column in code. The only place that I'd recommend two column is in markup languages like HTML and XML. They don't have methods, so their indent increases with their complexity. With code, if you are indenting so much that you are running out of space on the screen, that may be a sign that you should push code into separate functions or methods. </p>\n\n<h3>An alternate approach</h3>\n\n<blockquote>\n<pre><code> int divisor; // the divisor from power\n int i; // loop counter\n\n for(i = power - 1; i &gt;=0; i--)\n {\n divisor = (int)pow(10, i);\n printf(\"%d \", number / divisor);\n number = number % divisor;\n }\n</code></pre>\n</blockquote>\n\n<p>You are using the rather expensive <code>pow</code> function in each iteration of your for loop. </p>\n\n<p>Consider </p>\n\n<pre><code> for (int divisor = buildInitialDivisor(number); divisor &gt; 0; divisor /= BASE) {\n printf(\"%01d \", number / divisor);\n number %= divisor;\n }\n</code></pre>\n\n<p>This declares the loop variable as part of the loop declaration. </p>\n\n<p>This uses a constant <code>BASE</code> instead of the <a href=\"https://stackoverflow.com/q/47882/6660678\">magic number</a> 10. This improves readability and makes the program easier to modify. </p>\n\n<p>I changed from <code>%d</code> to <code>%01d</code>. Now if you wanted to display, say, two digits at a time, you could change that to <code>%02d</code> and change <code>BASE</code> to 100. It should zero pad the number so as to always print two digits. Of course, it would print a single leading digit as two digits too. That might be undesirable. You might consider how you could fix that. </p>\n\n<p>The <code>%=</code> is just a shorter syntax. Your original line and the revised one will do the exact same thing. <a href=\"https://www.tutorialspoint.com/cprogramming/c_assignment_operators.htm\" rel=\"nofollow noreferrer\">Assignment operators in C</a>. </p>\n\n<p>This gets rid of <code>pow</code> and replaces it with a different function and then divides on each iteration. </p>\n\n<p>This gets rid of your <code>i</code> variable which only tracked the number of iterations. We can do that directly. </p>\n\n<p>I prefer to always put the curly brackets on the same line as the code structure. Either form is fine so long as you are consistent. But you'll see both as you go, so might as well start recognizing them now. </p>\n\n<p>This also requires </p>\n\n<pre><code>const int BASE = 10;\n</code></pre>\n\n<p>and </p>\n\n<pre><code>int buildInitialDivisor(int number) {\n int divisor = 1;\n while (number / BASE &gt;= divisor) {\n divisor *= BASE;\n }\n\n return divisor;\n}\n</code></pre>\n\n<p>But it gets rid of your <code>getNumLength</code> function. </p>\n\n<h3>Recursion</h3>\n\n<p>You may not have gotten there yet, but when you get to recursion, you might try this problem again. Recursion often helps when you need to reverse the natural order of output. This is because you can display while returning from the recursion. So rather than building the largest divisor first, you can incrementally increase the size of the divisor (or better yet, decrease the number, always using the same divisor). </p>\n\n<p>You also might try this again after learning <code>sprintf</code> and character arrays. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:12:18.280", "Id": "413327", "Score": "0", "body": "Thank you! This is a lot to digest and look up. I have vacillated between snake_case and camelCase over time and was never quit sure which one was better. Recursion is also in this chapter but at the end so I am pretty sure that there is an exercise revisiting this exercise but to make use of recursion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T07:15:54.007", "Id": "413336", "Score": "0", "body": "\"in newer versions of C\" – in particular, any C compiler that implements C99 (from the year 1999) has it, so it's a safe bet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:17:49.703", "Id": "413407", "Score": "0", "body": "Recursion should be avoided for most purposes and IMO should not be taught to anyone, least of all beginners. It is very rare to encounter trouble-free, correctly optimized recursion in any C application. Buggy, unreadable, dangerous recursion however, is a common source of problems." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T04:18:31.280", "Id": "213687", "ParentId": "213682", "Score": "4" } }, { "body": "<p>Overall the code looks good, but old style C. Standard C allows variable declarations inside function bodies, and also inside for loops:</p>\n\n<pre><code>for(int i=0; i&lt;n; i++)\n</code></pre>\n\n<p>This has been in the C standard for 20 years and a common non-standard extension since 1990. So you might want to question why you are writing programs in such old-fashioned ways. If your teacher/book says \"it's ANSI-C\" then note that <code>//</code> comments aren't allowed in that old standard either.</p>\n\n<p>Your function documentation comments don't correspond with the actual code.</p>\n\n<hr>\n\n<p>The main issue is actually the use of the <code>pow()</code> function, which in turn requires the whole floating point library. Some compilers might be able to optimize it at compile-time, but I wouldn't count on it. On some systems like low-end microcontrollers, floating point isn't even an option.</p>\n\n<p>So how to write this without access to <code>pow()</code> but just plain integers? The advantage of <code>pow</code> is that you can iterate digit per digit, starting at 10^n and go down towards 10^0. Without that option, you would rather iterate from least significant digit and upwards. And this in turn complicates printing, because we want to print the most significant digit first.</p>\n\n<p>A naive implementation (doesn't support negative numbers etc) without <code>pow</code> might look like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint get_digits (int n)\n{\n int divisor=10000;\n int length;\n for(length=5; length&gt;0; length--)\n {\n if(n/divisor)\n {\n break;\n }\n divisor/=10;\n }\n return length;\n}\n\nvoid print_with_spaces (const char* str)\n{\n while(*str != '\\0')\n {\n printf(\"%c \", *str);\n str++;\n }\n}\n\nint main (void)\n{\n int input = 12345;\n char output[5+1] = \"0\";\n int digits = get_digits(input);\n\n for(int i=0; i&lt;digits &amp;&amp; input!=0; i++)\n {\n if((input % 10) != 0)\n {\n output[digits-1-i] = (input%10) + '0';\n }\n input /= 10;\n }\n\n print_with_spaces (output);\n}\n</code></pre>\n\n<p>Alternatively you can implement an integer version of pow yourself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:14:03.433", "Id": "213731", "ParentId": "213682", "Score": "3" } }, { "body": "<p>I see some things that may help you improve your program. Here are a few things not mentioned by the other reviews.</p>\n\n<h2>Fix the bug</h2>\n\n<p>There is a problem with <code>getNumLength</code> because although it carefully counts digits, the value of <code>length</code> is never initialized. If you want it to be zero, you need to set it to zero.</p>\n\n<h2>Sanitize user input</h2>\n\n<p>It's possible for the user to enter a non-numeric value or zero or a negative number. Does your program correctly handle those cases? Generally, a robust program checks thoroughly for such problems and handles them in a rational way.</p>\n\n<h2>Consider alternative approaches</h2>\n\n<p>Note that the <code>getNumLength</code> and <code>separate</code> functions both do successive divisions of the same number. A more efficient approach would be to iterate through just once, calculating each digit, starting from the least significant digit and storing them in the appropriate structure for later printing. One approach using a fixed size string and pointers:</p>\n\n<pre><code>void print_digits(int number) {\n char answer[14] = \"0 0 0 0 0\";\n char *ptr = &amp;answer[12];\n if (number) {\n while (number) {\n (*ptr) += number % 10;\n number /= 10;\n ptr -= 3;\n }\n ptr += 3;\n }\n puts(ptr);\n}\n</code></pre>\n\n<h2>Omit <code>return 0</code></h2>\n\n<p>When a C or C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so it is not required to put <code>return 0;</code> explicitly at the end of <code>main</code>. I prefer to omit it; others don't. In any case, if you encounter that you'll know what it means.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T16:26:03.957", "Id": "213734", "ParentId": "213682", "Score": "1" } } ]
{ "AcceptedAnswerId": "213687", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T23:51:52.497", "Id": "213682", "Score": "2", "Tags": [ "beginner", "c", "formatting" ], "Title": "Printing integers with spaces between the digits" }
213682
<p>My implementation of <a href="https://en.wikipedia.org/wiki/Karatsuba_algorithm" rel="noreferrer">Karatsuba multiplication</a> from <a href="https://youtu.be/JCbZayFr9RE" rel="noreferrer">Tim Roughgarden's Algorithms course</a>. I've made a Integer class that holds an integer in string format. I've added operations to this class to add, subtract and multiply numbers. Karatsuba.cpp performs <a href="https://en.wikipedia.org/wiki/Multiplication_algorithm#Complex_multiplication_algorithm" rel="noreferrer">Gauss' trick (complex multiplication algorithm)</a>.</p> <p><strong>Integer.hpp</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;functional&gt; class Integer{ public: Integer(); Integer(const std::string&amp; input); ~Integer(); Integer operator+(const Integer&amp; other) const; Integer operator-(const Integer&amp; other) const; Integer operator*(const Integer&amp; other) const; size_t size() const{return fString.size();} void padRight(size_t num); void padLeft(size_t num); Integer substr(size_t pos, size_t length) const; void print() const; void stripLeadingZeros(); private: std::string fString; }; void equalizeLengthsPadLeft(Integer&amp; first, Integer&amp; second); void equalizeLengthsPadRight(std::string&amp; first, std::string&amp; second); </code></pre> <p><strong>Integer.cpp</strong></p> <pre><code>#include "Integer.hpp" #include &lt;assert.h&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; namespace { int char2int(char c){ return c - '0'; } } Integer::Integer() : fString() { } Integer::Integer(const std::string&amp; input) : fString(input) { } Integer::~Integer(){} Integer Integer::substr(size_t pos, size_t len) const{ return fString.substr(pos, len); } void equalizeLengthsPadLeft(Integer&amp; first, Integer&amp; second){ if (first.size() &lt; second.size()){ first.padLeft(second.size()-first.size()); } else if(first.size() &gt; second.size()){ second.padLeft(first.size() - second.size()); } } void equalizeLengthsPadRight(std::string&amp; first, std::string&amp; second){ if (first.size() &lt; second.size()){ first += std::string(second.size()-first.size(), '0'); } else if(first.size() &gt; second.size()){ second += std::string(first.size() - second.size(), '0'); } } Integer Integer::operator+(const Integer&amp; other) const{ // For the time being, just conver to integer and return std::string first = fString; std::reverse(first.begin(), first.end()); std::string second = other.fString; std::reverse(second.begin(), second.end()); equalizeLengthsPadRight(first,second); std::string::iterator first_it = first.begin(); std::string::iterator second_it = second.begin(); std::string resultStr; int carry = 0; while(first_it != first.end()){ int sum = char2int(*first_it) + char2int(*second_it) + carry; carry = 0; if (sum &gt;= 10){ sum = sum%10; carry = 1; } resultStr += std::to_string(sum); first_it++;second_it++; } if (carry){ resultStr += '1'; } std::reverse(resultStr.begin(), resultStr.end()); return resultStr; } Integer Integer::operator-(const Integer&amp; other) const{ std::string first = fString; std::reverse(first.begin(), first.end()); std::string second = other.fString; std::reverse(second.begin(), second.end()); // Equalize equalizeLengthsPadRight(first,second); std::string::iterator first_it = first.begin(); std::string::iterator second_it = second.begin(); std::string resultStr; while(first_it != first.end()){ int up = char2int(*first_it); int down = char2int(*second_it); int localResult; if (up &gt;= down){ localResult = up-down; } else{ // Keep searching forward until you get a non-zero value auto next_it = first_it+1; while(true){ if (char2int(*next_it) &gt; 0){ // Found the first non-zero number break; } next_it++; } *next_it = std::to_string(char2int(*next_it)-1)[0]; // Now chase back to first_it setting 9's // on the way. Make sure everything was 0 // beforehand next_it--; while(next_it != first_it){ assert(char2int(*next_it) == 0); *next_it = std::to_string(9)[0]; next_it--; } localResult = up+10 -down; } assert(localResult&gt;=0); resultStr += std::to_string(localResult); first_it++; second_it++; } std::reverse(resultStr.begin(), resultStr.end()); return resultStr; } Integer Integer::operator*(const Integer&amp; other) const { // Only allow multiplication when size is 1 assert(size() == other.size() == 1); return std::to_string(std::stoi(fString)*std::stoi(other.fString)); } void Integer::padRight(size_t num){ fString += std::string(num, '0'); } void Integer::padLeft(size_t num){ fString.insert(0,num,'0'); } void Integer::print() const{ std::cout &lt;&lt; fString &lt;&lt; std::endl; } void Integer::stripLeadingZeros(){ // Don't strip if all are zeros - this will lead to an empty string if (std::all_of(fString.cbegin(), fString.cend(), [](char c){return ('0'== c); })){ return; } fString.erase(0, fString.find_first_not_of('0')); } </code></pre> <p><strong>Karatsuba multiplication</strong></p> <pre><code>#include &lt;string&gt; #include &lt;assert.h&gt; #include &lt;cmath&gt; #include "Integer.hpp" Integer multiply(const Integer&amp; inp1, const Integer&amp; inp2){ Integer first = inp1; Integer second = inp2; equalizeLengthsPadLeft(first, second); assert(first.size()==second.size()); size_t sz = first.size(); // Base case if (sz == 1){ return first*second; } int n = sz/2; Integer A = first.substr(0,n); Integer B = first.substr(n, sz-n); Integer C = second.substr(0,n); Integer D = second.substr(n, sz-n); Integer AC = multiply(A, C); Integer BD = multiply(B, D); Integer A_plus_B = A+B; Integer C_plus_D = C+D; Integer sum = multiply(A_plus_B, C_plus_D); Integer AD_plus_BC = sum - AC - BD; AC.padRight(2*(sz-n)); AD_plus_BC.padRight(sz-n); Integer result = AC+ AD_plus_BC + BD; result.stripLeadingZeros(); return result; } int main(){ Integer first("3141592653589793238462643383279502884197169399375105820974944592"); Integer second("2718281828459045235360287471352662497757247093699959574966967627"); Integer ans = multiply(first, second); ans.print(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T05:06:57.490", "Id": "413321", "Score": "0", "body": "What is a Gauss trick, and how Karatsuba.cpp performs it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:07:00.473", "Id": "413326", "Score": "0", "body": "Karatsuba is div-conq multiplication. If \\$x\\$ and \\$y\\$ are \\$n\\$-digit strings in some base \\$B\\$, then for any positive integer \\$m < n\\$, you can write \\$x = aB^m + b, y = cB^m + d\\$ where \\$b\\$ and \\$d\\$ are less than \\$B^m\\$. The product \\$x \\cdot y = \\ldots =acB^{2m} + (ad + bc)B^m + bd\\$. Applying Gauss' complex multiplication algorithm, reuse the results of \\$ac\\$ and \\$bd\\$ to find \\$(ad + bc)\\$. Thus, \\$(ad + bc) = (a + b)(c + d) - ac - bd\\$, reducing the no. of recursive multiplications at the cost of extra additions. This is performed when `AD_plus_BC` is introduced in the code." } ]
[ { "body": "<p>Your code is formatted inconsistently. Sometimes you placed spaces around operators, sometimes not, with no apparent patterns or rules. Just let your IDE format the code automatically.</p>\n\n<p>Sometimes you use snake_case, sometimes camelCase. You should only use one of them, for consistency.</p>\n\n<p>Instead of <code>sum = sum%10</code> you can write <code>sum -= 10</code> since the sum can never be greater than 19.</p>\n\n<p>Having <code>operator*</code> restricted to a single digit is unexpected. That function should better be an internal implementation detail, and <code>multiply</code> should become the new <code>operator*</code>.</p>\n\n<p>Instead of <code>Integer::print</code>, you should define the usual <code>os &lt;&lt; Integer</code> operator. Don't use <code>std::endl</code> unless you really know you need it. A simple <code>'\\n'</code> performs better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T07:04:50.243", "Id": "213697", "ParentId": "213686", "Score": "8" } }, { "body": "<p>I miss comments and use of a documentation tool like doxygen. </p>\n\n<ul>\n<li>I did not expect separate digit handling loops in <code>operator+()</code> and <code>operator-()</code> (obviously, I expected handling of <em>signed</em> integers). Nor the asymmetry between the procedures. </li>\n</ul>\n\n<p>In <code>multiply()</code>,<br>\n(I don't quite like <code>sum</code> for what it names (still undecided about <code>sz</code>):) </p>\n\n<ul>\n<li><code>sz-n</code> occurs just often enough to ponder introducing an abstraction, a name, a variable for it. </li>\n<li>\"Padding before adding\" leads to two <em>2×sz</em> additions: an alternative would be to exclude the least significant part (say, <code>bd</code>) of <code>BD</code> from addition, \"appending\" its most significant part to <code>AC</code> for a single <em>sz+n</em> addition and just append <code>bd</code>. </li>\n</ul>\n\n<p>(The remaining remarks may lead to <em>more</em> code, code more difficult to maintain/read:<br>\nrevisiting the test harness seems a good idea before coding any.) </p>\n\n<ul>\n<li>The next step in <em>avoiding complex digit operations</em> would seem to be not padding in <code>operator±()</code> and using <code>increment()</code>/<code>decrement()</code> instead.) </li>\n<li>With factors that differ widely in order of magnitude, there may be a lot of padding &amp; stripping: consider an inner procedure doing just *three multiplications and five additions\" (possibly with operand lengths passed in) and an outer one taking care of interface (like stripping leading zeroes). </li>\n</ul>\n\n<p>(On second thought, I'm not sure where \"tactics\" should go: passing the shorter factor where it terminates recursion sooner, extra strategy (\"long multiplication\") when one factor reaches the base case, handling 0 and powers of \"the base\" separately (0th power = 1 being a prominent and trivial case).)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T14:41:32.347", "Id": "413398", "Score": "0", "body": "\"Nor the asymmetry between the procedures.\" - How can this be improved? Aren't addition and subtraction fundamentally different? Inside the subtraction routine, trying to code the borrowing from the next power of 10 gave me a headache. Addition was a breeze" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T08:01:58.243", "Id": "413507", "Score": "0", "body": "A question looking so innocuous (just learned that I got the pronunciation wrong for decades) about something that tedious to implement. Faced with implementing both for integers in binary representation, someone came up with [two's complement](https://en.m.wikipedia.org/wiki/Binary_number#Subtraction). Should work with any base greater than one. (Using a *borrow* in place of carry, I don't envision \"decimal\" subtraction any more difficult to implement *on its own* than addition?!)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T09:07:34.087", "Id": "213705", "ParentId": "213686", "Score": "8" } }, { "body": "<p>I could be wrong, but looking at <code>Integer</code> I think it is really <code>NaturalNumber</code>. It doesn't seem to support negative numbers.</p>\n\n<p>There are a <em>lot</em> of reversals going on. It would almost certainly make more sense to use the reversed (little-endian) number internally, and only actually call <code>std::reverse</code> when converting between strings and <code>Integer</code>s.</p>\n\n<p><code>padLeft</code> and <code>stripLeadingZeros</code> do not belong in the public API of the class (and I'm not even sure they should be required in the private API). An <code>Integer</code> should be an integer, not a string. <code>padRight</code> would be more appropriately named something like <code>multiplyByPowerOfTen</code> or <code>shiftLeftDecimal</code>.</p>\n\n<p>If the Karatsuba multiplication is intended to be practical rather than purely an academic exercise, the base case should be when the multiplication can be done in a native type: probably when both numbers are less than 10 ** 9, so they fit in a (signed) 32-bit type and the result in a (signed) 64-bit type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T14:29:10.763", "Id": "413393", "Score": "0", "body": "Absolutely right about renaming Integer to NaturalNumber. The assignment assumed positive numbers and that doesn't get implied anywhere in the code. Extending the class a little bit will open it to negative numbers too.\n\nI could store the number in a reverse manner but it makes it harder to reason about the code. When constructing an integer from a raw string, I could perhaps just reverse the input and store it in `fString`. On further thought, only 2 operations - `operator+ ` and `operator-` need the string in reverse order, maybe I can store another reversed string as a member" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T14:35:05.220", "Id": "413394", "Score": "0", "body": "Only `operator+` and `operator-` explicitly reverse, but the Karatsuba multiplication uses those operators..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T09:42:07.537", "Id": "213708", "ParentId": "213686", "Score": "13" } } ]
{ "AcceptedAnswerId": "213708", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T03:33:53.250", "Id": "213686", "Score": "13", "Tags": [ "c++", "algorithm" ], "Title": "Karatsuba multiplication" }
213686
<blockquote> <p>An array of N words is given. Each word consists of small letters ('a'- 'z'). Our goal is to concatenate the words in such a way as to obtain a single word with the longest possible sub-string composed of one particular letter. Find the length of such a sub-string.</p> </blockquote> <ul> <li>Examples: <ol> <li>Given N=3 and words=['aabb','aaaa','bbab'], your function should return 6. One of the best concatenations is words[1]+words[0]+words[2]='aaaaaabbbbab'. The longest sub-string is composed of the letter 'a' and its length is 6.</li> <li>Given N=3 and words=['xxbxx','xbx','x'], your function should return 4. One of the best concatenations is words[0]+words[2]+words[1]='xxbxxxxbx'. The longest sub-string is composed of letter 'x' and its length is 4.</li> </ol></li> </ul> <pre><code> public class DailyCodingProblem4 { public static void main(String args[]) { String[] arr = { "aabb", "aaaa", "bbab" }; int res = solution(arr); System.out.println(res); String[] arr2 = { "xxbxx", "xbx", "x" }; res = solution(arr2); System.out.println(res); } private static int solution(String[] arr) { Map&lt;Integer, Integer&gt; prefix = new HashMap&lt;&gt;(); Map&lt;Integer, Integer&gt; suffix = new HashMap&lt;&gt;(); Map&lt;Integer, Integer&gt; both = new HashMap&lt;&gt;(); for (int i = 0; i &lt; arr.length; i++) { String word = arr[i]; int j = 1; while (j &lt; word.length() &amp;&amp; word.charAt(0) == word.charAt(j)) { j++; } int key = word.charAt(0); if (j == word.length()) { if (both.containsKey(key)) { Integer temp = both.get(key); both.put(key, j + temp); } else { both.put(key, j); } } else { if (suffix.containsKey(key)) { Integer temp = suffix.get(key); if (j &gt; temp) { suffix.put(key, j); } } else { suffix.put(key, j); } j = word.length() - 1; while (j &gt; 0 &amp;&amp; word.charAt(word.length() - 1) == word.charAt(j - 1)) { j--; } key = word.charAt(word.length() - 1); if (prefix.containsKey(key)) { Integer temp = prefix.get(key); if (word.length() - j &gt; temp) { prefix.put(key, word.length() - j); } } else { prefix.put(key, word.length() - j); } } } int res = 0; for (Integer key : prefix.keySet()) { if (suffix.containsKey(key)) { int temp = prefix.get(key) + suffix.get(key); if (temp &gt; res) { res = temp; } } } for (Integer key : suffix.keySet()) { if (prefix.containsKey(key)) { int temp = prefix.get(key) + suffix.get(key); if (temp &gt; res) { res = temp; } } } for (Integer key : both.keySet()) { if (prefix.containsKey(key)) { int temp = prefix.get(key) + both.get(key); if (temp &gt; res) { res = temp; } } if (suffix.containsKey(key)) { int temp = both.get(key) + suffix.get(key); if (temp &gt; res) { res = temp; } } } return res; } } </code></pre> <p>Is there a better approach to solve the above problem? Is there something I can improve on?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T05:54:50.147", "Id": "413324", "Score": "0", "body": "In `solution`, your handling for the `both` case appears wrong. If you have words 'aa' and 'aaa', you would not replace the 2 with a 3, but rather you would *add* the 2+3 getting 5, since you can concatenate the words as 'aaaaa', right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:06:21.380", "Id": "413325", "Score": "0", "body": "@AustinHastings you are right. I have missed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:16:19.837", "Id": "413328", "Score": "0", "body": "@AustinHastings updated line 43 to both.put(key, j + temp); This should solve it." } ]
[ { "body": "<p>I think I see a few bugs:</p>\n\n<ol>\n<li><p>In the initial processing loop, your handling for the <code>both</code> case appears wrong. If you have words 'aa' and 'aaa', you would not replace the 2 with a 3, but rather you would add the 2+3 getting 5, since you can concatenate the words as 'aaaaa'.</p></li>\n<li><p>In the prefix/suffix handling, there is the possibility that the same word would be the largest prefix and suffix, which is an impossibility. Consider a test case like this:</p>\n\n<pre><code>String[] arr = { \"xxbxxx\", \"xbx\", \"x\" }; // note: xx(2)bxxx(3)\nres = solution(arr);\n</code></pre>\n\n<p>What should <code>res</code> be? I believe you will compute the <code>prefix['x']</code> as being 3, and the <code>suffix['x']</code> as being 2, yielding an answer of 6. But the correct answer is 5, since you cannot use \"xxbxxx\" twice.</p>\n\n<p>(<strong>Note:</strong> This is a significant problem, since if true it will require you to significantly change how you are implementing your solution.)</p></li>\n<li><p>In the final phase, computing results, your <code>prefix</code> and <code>suffix</code> loops ignore the possibility of a single winner. That is, <code>prefix</code> requires a <code>suffix</code> to win, and <code>suffix</code> requires a <code>prefix</code> to win. It does not allow for the possibility that a word like \"xzzzzzzzzzz\" could have a long enough (prefix|suffix) to just dominate the result.</p></li>\n<li><p>The same is true for <code>both</code>: there is no acknowledgement of the possibility of a prefix+both+suffix.</p></li>\n</ol>\n\n<p>And now here's some non-bug stuff:</p>\n\n<p>You spend a <strong>lot</strong> of time checking if a map contains a given key. If you go through and count lines of code, it is probably the most expensive thing you do. (Not to mention that many of your bugs are around this area.) I think it would benefit you to set up your maps so that the keys were always present with a default value of zero. There are some proposed options in <a href=\"https://stackoverflow.com/questions/7519339/hashmap-to-return-default-value-for-non-found-keys\">this SO question</a>.</p>\n\n<p>For a specific example, consider this:</p>\n\n<pre><code>if (both.containsKey(key)) {\n Integer temp = both.get(key);\n if (j &gt; temp) {\n both.put(key, j);\n }\n} else {\n both.put(key, j);\n}\n</code></pre>\n\n<p>That could be rewritten as:</p>\n\n<pre><code>temp = both.getOrDefault(key, 0);\nif (j &gt; temp)\n both.put(key, j)\n</code></pre>\n\n<p>Which could be rewritten as:</p>\n\n<pre><code>if (j &gt; both.getOrDefault(key, 0))\n both.put(key, j);\n</code></pre>\n\n<p>I also see code like this in a few places:</p>\n\n<pre><code>while (j &lt; word.length() &amp;&amp; word.charAt(0) == word.charAt(j)) {\n j++;\n}\nint key = word.charAt(0);\n</code></pre>\n\n<p>Why are you writing <code>word.charAt(0)</code> more than one time? Define the <code>key</code> above the loop, and make things shorter, clearer, and simpler:</p>\n\n<pre><code>int key = word.charAt(0);\nwhile (j &lt; word.length() &amp;&amp; key == word.charAt(j)) {\n j++;\n}\n</code></pre>\n\n<p>In your bottom section, you can remove a lot of that code using the map-with-default-value approach. The best answer is the one that has the largest total of prefix + both + suffix, where the default for any of them is zero. Also, <code>res</code> is a bad name. Try <code>longest</code>.</p>\n\n<pre><code>for (Integer key : prefix.keySet()) {\n longest_for_key = prefix.getOrDefault(key, 0) + both.getOrDefault(key, 0) + suffix.getOrDefault(key, 0);\n if (longest_for_key &gt; longest)\n longest = longest_for_key;\n</code></pre>\n\n<p>}</p>\n\n<p>You'll still have to do all three, since there might be a unique key in one of the maps with a dominant string. But as least the code is simpler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:24:45.410", "Id": "213691", "ParentId": "213689", "Score": "8" } }, { "body": "<p>Your code repeats in many places. Instead of using <code>if (map.containsKey)</code>, you should make good use of <code>Map.getOrDefault</code>:</p>\n\n<pre><code>map.put(key, j + map.getOrDefault(key, 0));\n</code></pre>\n\n<p>That way you can convert many five-liners into one-liners.</p>\n\n<p>Instead of the <code>&lt;</code> operator just use <code>Math.max</code>, which leads to shorter code as well.</p>\n\n<p>I don't understand the formatting of the code, especially why the methods are indented by 11 spaces. If there's no hidden meaning to it, let your IDE or editor format the code automatically.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T09:20:51.253", "Id": "413346", "Score": "2", "body": "That `map.put(...` line can simplified even more by using `map.merge(key, j, (a, b) -> a + b)`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:44:29.020", "Id": "213695", "ParentId": "213689", "Score": "3" } } ]
{ "AcceptedAnswerId": "213691", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T05:37:56.640", "Id": "213689", "Score": "8", "Tags": [ "java", "algorithm", "strings", "programming-challenge" ], "Title": "Concatenate words in such a way as to obtain the longest possible sub-string of the same letter" }
213689
<p>new to bash , I use the following code to open the super folder with a file path.</p> <pre><code>function openUp(){ cd $(echo $1 | sed 's@\(.*\)/.*@\1@' ); open .. } </code></pre> <p>like drag a file to terminal, then open the super folder conveniently.</p> <blockquote> <p>openup /Users/de/Downloads/32/S01E32-array-arrayslice-collection-collections-1-master.zip </p> </blockquote> <p>How to combine the two line code to one line? </p> <p>I originally think open directly without changing directory.</p>
[]
[ { "body": "<p>You can use <code>open</code> with an absolute path, it doesn't have to be a relative path.</p>\n\n<p>That is, you could write the same in one line, with some basic improvements:</p>\n\n<pre><code>openUp() {\n open \"$(sed 's@\\(.*\\)/.*@\\1@' &lt;&lt;&lt; \"$1\")/..\"\n}\n</code></pre>\n\n<p>The basic improvements:</p>\n\n<ul>\n<li>Instead of <code>echo \"...\" | cmd</code>, use <em>here strings</em>: <code>cmd &lt;&lt;&lt; \"...\"</code></li>\n<li>Double-quote variables used as command line arguments (in your example, of <code>cd</code>, and <code>echo</code></li>\n<li>It's not recommended to use the <code>function</code> keyword, write without</li>\n</ul>\n\n<p>A more important improvement would be to stop using <code>sed</code> to get the name of the base directory. Using a regex is error-prone and not as intuitive as the <code>dirname</code> command:</p>\n\n<pre><code>openUp() {\n open \"$(dirname \"$1\")/..\"\n}\n</code></pre>\n\n<p>Notice that the arguments of <code>dirname</code> and <code>open</code> are both double-quoted,\nas mentioned earlier.\nThis is necessary, to protect from word-splitting and globbing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:48:49.023", "Id": "413333", "Score": "0", "body": "`open \"$(dirname \"$1\")/..\"` works perfect. while `open \"$(sed 's@\\(.*\\)/.*@\\1@') <<< \"$1\")/..\"` get stuck there, just holding on. I tested in Mac." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:55:13.430", "Id": "413334", "Score": "0", "body": "`open \"$((sed 's@\\(.*\\)/.*@\\1@') <<< \"$1\")/..\";` , lack a close parenthesis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:57:31.817", "Id": "413335", "Score": "0", "body": "@black_pearl oops, typo, fixed it, thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:30:50.413", "Id": "213692", "ParentId": "213690", "Score": "3" } } ]
{ "AcceptedAnswerId": "213692", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:12:31.813", "Id": "213690", "Score": "1", "Tags": [ "bash", "macos" ], "Title": "Mac Bash: how to combine the open and str subtract to one line code?" }
213690
<blockquote> <h2><a href="https://leetcode.com/problems/count-and-say/" rel="noreferrer">38. Count and Say</a></h2> <p>The count-and-say sequence is the sequence of integers with the first five terms as following:</p> <pre><code>1. 1 2. 11 3. 21 4. 1211 5. 111221 </code></pre> <p><code>1</code> is read off as <code>"one 1"</code> or <code>11</code>.</p> <p><code>11</code> is read off as <code>"two 1s"</code> or <code>21</code>.</p> <p><code>21</code> is read off as <code>"one 2, then one 1"</code> or <code>1211</code>.</p> <p>Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.</p> <p>Note: Each term of the sequence of integers will be represented as a string.</p> </blockquote> <h3>With iteration:</h3> <p>How to reduce 3 kinds of situation to one solution?</p> <pre><code>class Solution { func countAndSay(_ n: Int) -&gt; String { var ans = ["1"] var temp: [String], j: Int for _ in 1..&lt;n{ // from the beginning 1 to what we what j = 1 temp = [] for i in 1..&lt;ans.count{ if ans[i - 1] == ans[i]{ j += 1 // Situation one: the current is equal to the previous ( util the last ) } else{ temp.append(String(j)) temp.append(ans[i-1]) // Situation two: the current is not equal to the previous ( util the last ) j = 1 } } // Situation three: the last value temp.append(String(j)) temp.append(ans.last!) ans = temp print(ans.reduce("", +)) } return ans.reduce("", +) } } </code></pre> <h3>With Recursion, which is a little leaner.</h3> <pre><code>class Solution { func countAndSay(_ n: Int) -&gt; String { if n == 1 { return "1" } let str = countAndSay(n-1) let arr = Array(str).map{Int(String($0))} var last = arr[0]! var temp : [(count: Int, val: Int)] = [(1, last)] for num in arr[1...]{ if last == num{ var final = temp.last! final.count += 1 temp.removeLast() temp.append(final) } else{ temp += [(1, num!)] } last = num! } var result = "" for key in temp{ result += "\(key.0)\(key.1)" } return result } } </code></pre> <p>How to go on doing some improvement? </p>
[]
[ { "body": "<h3>Your iterative solution</h3>\n\n<p>This is generally fine, with the only exception that it operates on an array of <em>strings</em> –  I'll come back to that later.</p>\n\n<p>Variables should be defined in the narrowest scope where they are used. This applies to</p>\n\n<blockquote>\n<pre><code>var temp: [String], j: Int\n</code></pre>\n</blockquote>\n\n<p>which are used only in the inner loop. Both variable names are non-descriptive and can be improved (e.g.: <code>j</code> actually <em>counts</em> the number of consecutive equal numbers).</p>\n\n<h3>Your recursive solution</h3>\n\n<p>Here</p>\n\n<blockquote>\n<pre><code>let arr = Array(str).map{Int(String($0))}\n</code></pre>\n</blockquote>\n\n<p>the conversion from <code>str</code> to an array is not needed: A Swift string is a collection of its characters, and you can call <code>map()</code> directly on the string. You also <em>know</em> that the string contains only decimal digits. Therefore you can force-unwrap here, replacing several force-unwraps in the following code:</p>\n\n<pre><code>let arr = str.map{ Int(String($0))! }\n</code></pre>\n\n<p>This</p>\n\n<blockquote>\n<pre><code>var final = temp.last!\nfinal.count += 1\ntemp.removeLast()\ntemp.append(final)\n</code></pre>\n</blockquote>\n\n<p>is more simply and more efficiently done as</p>\n\n<pre><code>temp[temp.count - 1].count += 1\n</code></pre>\n\n<p>And this loop</p>\n\n<blockquote>\n<pre><code>var result = \"\"\nfor key in temp{\n result += \"\\(key.0)\\(key.1)\"\n}\nreturn result\n</code></pre>\n</blockquote>\n\n<p>can be simplified using <code>map()</code>:</p>\n\n<pre><code>return temp.map { \"\\($0.count)\\($0.val)\" }.joined()\n</code></pre>\n\n<p>Generally, this looks less efficient to me than the first approach, because a string is converted to an integer array in each recursion step.</p>\n\n<h3>Redesign</h3>\n\n<p>In order to avoid unnecessary conversions between strings, characters, and integers, I would suggest to operate on an integer array generally, and create the string answer only as the final step.</p>\n\n<p>Instead of an inner loop or recursion I would put the code to compute the next iteration into a separate function. That makes the code easier to read and to test:</p>\n\n<pre><code>class Solution {\n func countAndSay(_ n: Int) -&gt; String {\n var seq = [1]\n for _ in 1..&lt;n {\n seq = transform(seq)\n }\n return seq.map(String.init).joined()\n }\n\n func transform(_ seq: [Int]) -&gt; [Int] {\n // ... TODO ...\n }\n}\n</code></pre>\n\n<p>This works with both your solutions. For your first solution the transform function would be something like this:</p>\n\n<pre><code>func transform(_ seq: [Int]) -&gt; [Int] {\n var result = [Int]() // The transformed sequence\n var current = seq[0] // The current number\n var count = 1 // Counts # of consecutive equal numbers\n for num in seq.dropFirst() {\n if num == current {\n count += 1\n } else {\n result.append(count)\n result.append(current)\n current = num\n count = 1\n }\n }\n result.append(count)\n result.append(current)\n return result\n}\n</code></pre>\n\n<p>Instead of comparing against <code>arr[i-1]</code> the current number is “remembered” in a local variable, so that we can iterate over the sequence (without its first element) instead of iterating over the array indices.</p>\n\n<p>Your second solution creates an array of <code>(count, value)</code> tuples first, and therefore does not need to handle the case of the last run separately. If you start with an empty array of tuples (and use optional chaining to compare against the last value) then you even don't have to handle the first value separately:</p>\n\n<pre><code>func transform(_ seq: [Int]) -&gt; [Int] {\n\n var pairs: [(count: Int, val: Int)] = []\n for num in seq {\n if num == pairs.last?.val {\n pairs[pairs.count - 1].count += 1\n } else {\n pairs.append((count: 1, val: num))\n }\n }\n return Array(pairs.map { [$0.count, $0.val] }.joined())\n}\n</code></pre>\n\n<p>In my tests this was a bit faster than your original solution, but slower than the first approach, probably because of the intermediate array.</p>\n\n<h3>A third solution</h3>\n\n<p>Here is another possible solution, which combines the advantages of both approaches. Instead of traversing the array elements, we directly search for the next <em>index</em> of a number different from the current. Neither the first nor the last run has be be treated specially:</p>\n\n<pre><code>func transform(_ seq: [Int]) -&gt; [Int] {\n var result = [Int]()\n var fromIndex = seq.startIndex // Start index of current run\n while fromIndex != seq.endIndex {\n let current = seq[fromIndex]\n // Start index of next run:\n let toIndex = seq[(fromIndex+1)...].firstIndex(where: { $0 != current }) ?? seq.endIndex\n result.append(toIndex - fromIndex)\n result.append(current)\n fromIndex = toIndex\n }\n return result\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:34:26.707", "Id": "213714", "ParentId": "213694", "Score": "6" } }, { "body": "<h2><strong>Iterative vs Recursive</strong></h2>\n\n<p>For code efficiency, I personally always prefer the iterative approach. According to LeetCode :</p>\n\n<ul>\n<li>You iterative code clocked at 12ms on Leetcode, being 3 times as fast as your recursive approach (36ms).</li>\n<li>It uses less memory 18.7MB, vs 19.2MB for the recursive solution. </li>\n</ul>\n\n<p>Now let's dig in to see what could be improved :</p>\n\n<h2><strong>Iterative approach</strong></h2>\n\n<ul>\n<li><p>On Leetcode, or whenever you're benchmarking your code, printing to the console would slow down the execution time dramatically. The previous execution times are given without <code>print(ans.reduce(\"\", +))</code></p></li>\n<li><p>I see that you've used an array of strings to ease the access to characters at a given index. You could do the same thing with <code>String.Index</code> and it would spare you the excess memory allocations :</p>\n\n<pre><code>var ans = \"1\"\nvar temp: String, j: Int\nfor _ in 1..&lt;n {\n // from the beginning 1 to what we what\n j = 1\n temp = \"\"\n for i in ans.indices.dropFirst() {\n // Situation one: the current is equal to the previous ( util the last )\n if ans[ans.index(before: i)] == ans[i] {\n j += 1\n }\n // Situation two: the current is not equal to the previous ( util the last )\n else {\n temp.append(String(j))\n temp.append(ans[ans.index(before: i)])\n j = 1\n }\n }\n // Situation three: the last value\n temp.append(String(j))\n temp.append(String(ans.last!))\n ans = temp\n}\n</code></pre></li>\n</ul>\n\n<p>This reduces memory usage slightly to 18.6MB. \nBut the execution time was on average 16ms (varied from 12ms to 20ms on Leetcode). This could be due to <code>.count</code> <s>and <em>subscripting</em></s> being O(n) on a String: a <code>String</code> in Swift is not randomAccess, unlike an array. Just to check, I tried it on <a href=\"https://tio.run/##nZPBbtswDIbvegouJwlr3QXbKVgKDCgK9OzjUBSqzTQMHMqTqKTFkGfPJDndmqRZsPFimPpJfqTEsKaZfNluadk7L3DrIrdWyDEo1XQ2BKhdF4vjp4Jks8gNNEkm37it7Yt@AJ7AHYuBy2uoxRM/7aTZVtaD5QBTGI1He17BZT/ZBVzAouT4LZg5Dw9ADOOq@spv8mW7ukoC75Ygc4RHfCLmXHQM4mA9twJrLN@9oEVCGO95MkDmGu15c2XKlRN1RdxSg6FqvetvyQfR5oDllacmicPcHOOkkDXRe2QBCoA/ou0yXvb3HlfkYgANabBd8aVJC5ijzDTLGN93KPisHzHxpfxk7mE6LYd0/w7S0PHHw5azbc7wy9od8bOT/@4Bu4AnCPMNVLbvkVs9PAS9MOas9ORIzIk5nB/DRv1lIHOPuystLa5sF1H9Yx/vSHILOeGHA@mwLjlAHeN5lOjL41TDwUapDgWC2LS@U7ixgtoMrvT7urzaVG939vOnQZJo/sSoPmGJDoPyIh9WQktMe4k@NV0TN6hLIWO2218\" rel=\"nofollow noreferrer\">TIO</a>, and it gave the edge to the <code>String.Index</code> version. Anyway, in the rest of this answer, I'll revert to using an array for clarity.</p>\n\n<ul>\n<li><p><strong>3 for the price of one</strong> : This is the direct answer to your question, and all it takes is adjusting the bounds of the inner loops (the forced-unwrapping was calling for this change) :</p>\n\n<pre><code>for _ in 1..&lt;n {\n var temp: [String] = []\n var i = 0\n while i &lt; ans.count {\n let char = ans[i]\n var j = 0\n while i &lt; ans.count &amp;&amp; ans[i] == char {\n j += 1\n i += 1\n }\n temp.append(String(j))\n temp.append(char)\n }\n ans = temp\n} \n</code></pre></li>\n</ul>\n\n<p>Notice that the outer loop was chosen as a <code>for</code> loop, since it is faster than a <code>while</code> loop in Swift, since the latter checks the condition on each iteration. <a href=\"https://tio.run/##tY6xCsJAEETr26/YMkEJF7FMOhGs/YBwmA0uJHtyWROC5NvPQ23sbFyYZmYeO@PMne5j5OHmg@LR36V1yl4AWo8PMJMLuGCNFsD0pDiqC7pLxsEpZXly5yv3lDoVltbaJilxmM6YBTc1lmDWD0zSfqG3wKLZsn0FhfJAJ1EKk@vPLBfK3s/yHNbf53Q@YIMsaIui@uuiGJ8\" rel=\"nofollow noreferrer\">Try It Online!</a></p>\n\n<ul>\n<li><p><code>ans.reduce(\"\", +)</code> can be simply written as <code>ans.joined()</code></p></li>\n<li><p>Instead of using arrays of strings that contains one character only, better use arrays of the less expensive type: <code>Character</code>. </p></li>\n</ul>\n\n<p>Putting it all together :</p>\n\n<pre><code>class Solution {\n func countAndSay(_ n: Int) -&gt; String {\n var ans: [Character] = [\"1\"]\n for _ in 1..&lt;n {\n var temp: [Character] = []\n var i = 0\n while i &lt; ans.count {\n let char = ans[i]\n var j = 0\n while i &lt; ans.count &amp;&amp; ans[i] == char {\n j += 1\n i += 1\n }\n temp.append(Character(String(j)))\n temp.append(char)\n }\n ans = temp\n }\n return String(ans)\n }\n}\n</code></pre>\n\n<p>Leetcode : Runtime: 12 ms, Memory Usage: 18.8 MB</p>\n\n<h2><strong>Recursive approach</strong></h2>\n\n<ul>\n<li><p>Personally, I find it more idiomatic to use the <code>guard</code> statement instead of an if condition in an (<em>very</em>) early return :</p>\n\n<pre><code>guard 1 &lt; n else {\n return \"1\"\n}\n</code></pre></li>\n</ul>\n\n<p>Notice that I've used the <code>&lt;</code> since it is the one defined by default, and no protocol witnesses would be generated at runtime for it. This a very slight improvement, and you could <a href=\"https://tio.run/##hYzBCsIwEETv@xXrLSlqI3i0NxE8@wES7IoLaVLStQ2I3x5jPXgSB@Y0b94w8VW2OXPXhyh4CHffWuHgAUYbMWGDG2PO5lMAR4KD2II2uLdCSsN0Y0eFXDRo8AFYknBVfvCccfLtF4a6@u0wuCvXf4qqBugje1Fp@V7Wwh0dvVAcrTuxv5Ca7VpDzi8\" rel=\"nofollow noreferrer\">try it online</a>.</p>\n\n<ul>\n<li><p><code>arr</code> is an array of optional Ints, which is unnecessary since we're sure that all characters of <code>str</code> are convertible to <code>Int</code>. So, we'd better use <code>compactMap</code>. That would spare you force unwrapping <code>last</code> and <code>num</code> :</p>\n\n<pre><code>let arr = Array(str).compactMap{Int(String($0))}\n</code></pre></li>\n</ul>\n\n<p>This change alone brings the execution time from 36ms to 32ms.</p>\n\n<p>Or, force unwrap inside the <code>map</code> closure :</p>\n\n<pre><code>let arr = Array(str).map{Int(String($0))!}\n</code></pre>\n\n<p>which brings the runtime to 28ms.</p>\n\n<ul>\n<li><p>Using string interpolation is <a href=\"https://tio.run/##fY49C8IwEIb3@xVHpsSvRnC0mwjOXQUJNmqgTUt6tgHxt8czOOjiTXcPPPe@w@QutEnJtX0XCPfd3deGXOcBRhMwYolrrU9a63wPFJy/MhQCoLHEwLBW4s6QlQqgmMF0c41FjVu2H4A8H2teYpU3GVXmEZf8Hp4wK@CvJo6siF8nx1tff4VDzwLJuHjzFbnWHjzZMJqmcv5sZS6rFKT0Ag\" rel=\"nofollow noreferrer\">really slow</a>, better use a String initializer:</p>\n\n<pre><code>result += String(key.0) + String(key.1)\n</code></pre></li>\n</ul>\n\n<p><strong>Alternative recursive implementation:</strong></p>\n\n<p>Here is an alternative implementation that clocks at 16ms, 18.4MB :</p>\n\n<pre><code>class Solution {\n func countAndSay(_ n: Int) -&gt; String {\n guard 1 &lt; n else {\n return \"1\"\n }\n let str = countAndSay(n - 1)\n var ans = \"\"\n var count = 0\n var i = str.startIndex\n while i &lt; str.endIndex {\n count += 1\n let indexfterI = str.index(after: i)\n if (indexfterI &lt; str.endIndex &amp;&amp; str[indexfterI] != str[i]) ||\n indexfterI == str.endIndex {\n ans += String(count) + String(str[i])\n count = 0\n }\n i = indexfterI\n }\n return ans\n }\n}\n</code></pre>\n\n<h2><strong>Taking advantage of the problem description</strong></h2>\n\n<p>Since <code>n</code> is less than 30, you can generate all the answers from 1, to 30, put them in an array, and return the element corresponding to <code>n</code> :</p>\n\n<pre><code>class Solution {\n func countAndSay(_ n: Int) -&gt; String {\n return a[n]\n }\n let a = [\"\", \"1\", \"11\", \"21\", \"1211\", \"111221\", \"312211\", ... ] //31 elements\n}\n</code></pre>\n\n<p>This hack clocks at 8ms.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:52:02.150", "Id": "413838", "Score": "0", "body": "I don't think that protocol witnesses are generated for integer comparison, these directly translate into machine instructions. In my experience a `==` comparison is faster than `<` (or `>`) for integers, that is also confirmed here: https://tio.run/##zY/PCoJAEMbvPsV0U9LYoGPeQujUoQeIRdcaWHdlnfxD@Optq0IpnYM@WBi@b@Y3O1WDOe2sxaLUhiDRd5VxQq08D5wyDY@xGFRzAy3EsGXswqa3yDqXfRwpCCriDhrDgZPwg3fU3FAKh1q5/hl/UAuRW7CwOljPrX6xQajsm18aVOS3IXTh0LAhLMRRkTA1l2dUqfDHjwXTRP/zSxnsHe4PDrX2meaSXysbnV4. (I added some code to the loop to prevent the compiler from optimizing it away.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:56:34.190", "Id": "413839", "Score": "1", "body": "With respect to the “more idiomatic use of guard”: That might be opinion based, but I disagree that every “early return” should be a guard. Terminating a recursion with `if n == 1 { return \"1\" }` looks clearer to me than the “double-negation Yoda condition” `guard 1 < n else { return \"1\" }` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T12:42:09.127", "Id": "413845", "Score": "0", "body": "Btw, subscripting a string (with String.Index) is O(1), not O(n). That is a general requirement for collection types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-02T00:16:30.963", "Id": "414939", "Score": "1", "body": "@MartinR “I disagree that every ‘early return’ should be a `guard`” ... I’m with you on that! My favorite example is `guard !(annotation is MKUserLocation) else { return nil }`, whereas `if annotation is MKUserLocation { return nil }` is just so much more intuitive. I think one should use the pattern where one’s intent is most clear. Sure, we should favor `guard` all things being equal, but often they ain’t." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:21:58.963", "Id": "213879", "ParentId": "213694", "Score": "6" } }, { "body": "<p>For what it’s worth, when I see a progression like this, I lean towards <code>Sequence</code>/<code>Iterator</code> pattern, e.g.:</p>\n\n<pre><code>struct CountAndSayIterator&lt;T&gt;: IteratorProtocol where T: RangeExpression, T.Bound == Int {\n private let range: T\n private var currentValue: String = \"\"\n private var currentIndex: Int = 0\n\n init(_ range: T) {\n self.range = range\n\n // burn off values if we have to\n\n while !range.contains(currentIndex) {\n calculateNext()\n }\n }\n\n mutating func next() -&gt; String? {\n guard range.contains(currentIndex) else {\n return nil\n }\n\n return calculateNext()\n }\n\n @discardableResult\n private mutating func calculateNext() -&gt; String? {\n currentIndex += 1\n\n if currentValue.isEmpty {\n currentValue = \"1\"\n return currentValue\n }\n\n var iterator = currentValue.makeIterator()\n\n guard var previousCharacter: Character = iterator.next() else { return nil }\n var count = 1\n\n var character: Character?\n var result = \"\"\n\n repeat {\n character = iterator.next()\n switch character {\n case previousCharacter:\n count += 1\n\n default:\n result += \"\\(count)\\(previousCharacter)\"\n if let character = character {\n previousCharacter = character\n count = 1\n }\n }\n } while character != nil\n\n currentValue = result\n return result\n }\n}\n\nstruct CountAndSaySequence&lt;T&gt;: Sequence where T: RangeExpression, T.Bound == Int {\n let range: T\n\n init(_ range: T) {\n self.range = range\n }\n\n func makeIterator() -&gt; CountAndSayIterator&lt;T&gt; {\n return CountAndSayIterator(range)\n }\n}\n</code></pre>\n\n<p>Then you can do natural things like:</p>\n\n<pre><code>for value in CountAndSaySequence(0..&lt;5) {\n print(value)\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>let array = Array(CountAndSaySequence(0...4))\nprint(array)\n</code></pre>\n\n<p>And, when you have this <code>Iterator</code> that calculates the values for you, you can implement the requested method like so:</p>\n\n<pre><code>func countAndSay(_ n: Int) -&gt; String {\n var iterator = CountAndSayIterator(n...)\n return iterator.next()!\n}\n</code></pre>\n\n<p>Clearly, I’m using a zero-based index and this question, despite our living in a zero-based world, is using 1-based index, so adjust that <code>countAndSay</code> method as you see fit.</p>\n\n<p>And, obviously, if you wanted, you could further extend this <code>CountAndSaySequence</code> type to be a <code>Collection</code> with caches for previously calculated values, etc. But that seemed beyond the scope of this question.</p>\n\n<p>But using <code>Sequence</code> feels a bit swiftier to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-27T01:12:54.000", "Id": "219222", "ParentId": "213694", "Score": "3" } } ]
{ "AcceptedAnswerId": "213714", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T06:44:11.943", "Id": "213694", "Score": "8", "Tags": [ "programming-challenge", "comparative-review", "swift" ], "Title": "Leetcode 38: The “count-and-say” sequence" }
213694
<p>I have two methods which are <code>GetMinimumSize()</code> and <code>GetMaximumSize()</code>. They return the maximum size of the window, and they take one parameter, which is an enum either <code>WindowSizeLimitParam::Width</code>, or <code>WindowSizeLimitParam::Height</code>, because of course, we want to specify which maximum or minimum we want to get.</p> <p>Here is the enum</p> <pre><code>enum class WindowSizeLimitParam { Width = 0, Height = 1 }; </code></pre> <p>Some time ago, I didn't have this enum, and I just had 4 methods which were just for min size width, min size height, max size width, and max size height, but for the sake of shortness, I decided to do it with an enum. So my question is, is this a good design choice? Using an enum to specify the size type which we want to get? Keep in mind I have other methods like setting size or getting size, but they don't use enums, they are <code>GetWidth()</code>, <code>GetHeight()</code>, <code>SetWidth()</code>, <code>SetHeight()</code>. If I'm using an enum for the size limit, should i use an enum here and just have <code>SetSize()</code> and <code>GetSize()</code> in which i pass an enum?</p> <p>Is it generally a good idea to use enums if you are developing an API, which is kind of what I am doing here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T12:24:46.943", "Id": "440344", "Score": "0", "body": "This question is lacking context, so it won't be possible to produce a sensible review. It sounds like you are asking about this more generally, as opposed to having a particular piece of code about which you are worried. If there is a particular instance you want reviewing, then we need to see how it is used (e.g. which method takes it as a parameter and how is it called). A more general query may be on-topic on the [Software Engineering StackExchange](https://softwareengineering.stackexchange.com/help/on-topic)." } ]
[ { "body": "<p>It's important to be consistent - if you already have <code>GetWidth</code>, <code>GetHeight</code>, <code>SetWidth</code> and <code>SetHeight</code> then it makes sense to have <code>GetMinimumWidth</code>, <code>GetMinimumHeight</code>, <code>GetMaximumWidth</code>, and <code>GetMaximumHeight</code>.</p>\n\n<p>An alternative approach is to retrieve every value in a struct, which further simplifies your API surface and may improve performance if you expect a consumer to call most other getters:</p>\n\n<pre><code>struct WindowSizeInfo\n{\n const int width, minWidth, maxWidth;\n const int height, minHeight, maxHeight;\n}\n\nWindowSizeInfo Window::GetSize()\n{\n return WindowSizeInfo( ... );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:56:07.420", "Id": "413352", "Score": "0", "body": "Thank you very much. It really is a better way of doing it when I give it a second thought" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:19:08.457", "Id": "213713", "ParentId": "213707", "Score": "3" } } ]
{ "AcceptedAnswerId": "213713", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T09:25:01.913", "Id": "213707", "Score": "-1", "Tags": [ "c++", "api", "enum" ], "Title": "C++ API design - Should I pass enums as method parameters" }
213707
<p>In a service I'm developing I'm using three cloud services (five if you count additional two streaming services I have to create that are used by those cloud services in turn) and to orchestrate bits and pieces incoming I need a cache for objects relating data from all those services. That cache has to be is safe to access from various Tornado handlers in an atomic manner.</p> <p>Now, since Tornado is based on I/O loop, theoretically I do not need to use locks or some other synchronization primitives... but that's obviously relying on implementation detail (GIL) and it can reportedly cause problems <a href="https://emptysqua.re/blog/pythons-swap-is-not-atomic/" rel="nofollow noreferrer">under some circumstances</a> anyway, so to be rather safe than sorry I try to develop the cache that is all:</p> <ul> <li>Singleton</li> <li>Thread-safe</li> <li>Creates a default object available under a key</li> </ul> <p>I'm approaching the subject with some trepidation as so far I have not done such stuff much. This is what I've come up with so far:</p> <p><strong>UPDATE</strong> </p> <p>I've realized I had a stupid mistake in the previous implementation: the <code>setdefault</code> method called <code>default_factory</code> every time. Updated version works but it's kinda ugly:</p> <pre><code>class ThreadSafeSingletonCache(object): __me = None __cache = None __lock = threading.Lock() def __new__(cls, _): if cls.__me is None: cls.__cache = {} cls.__me = super(ThreadSafeSingletonCache, cls).__new__(cls) return cls.__me def __init__(self, default_factory): self.default_factory = default_factory def obj_setattr(self, cache_key, obj_attr, value): with self.__lock: item = self.__like_setdefault(cache_key) setattr(item, obj_attr, value) def __like_setdefault(self, cache_key): ''' Unfortunately I cannot use .setdefault as default_factory function gets called on each setdefault use''' item = self.__cache.get(cache_key) if not item: item = self.default_factory() self.__cache[cache_key] = item return item def get(self, cache_key): with self.__lock: return self.__like_setdefault(cache_key) def set(self, cache_key, obj): with self.__lock: self.__cache[cache_key] = obj </code></pre> <p>Please point out problems and potential improvements.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T11:33:49.097", "Id": "413356", "Score": "0", "body": "I don't get it... If the default factory could change at each instantiation, why design a singleton; and if it doesn't change, why use it as a parameter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:12:08.630", "Id": "413359", "Score": "0", "body": "@MathiasEttinger: Single Responsibility Principle? Implementing the cache that is not tightly coupled to particular factory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:19:04.287", "Id": "413360", "Score": "0", "body": "Well, I guess an example usage would help here as I have a hard time understanding why a singleton would fit if you want to create one for each kind of objects you own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:26:49.180", "Id": "413361", "Score": "0", "body": "@MathiasEttinger: in this particular case there's only one cache and only one type of objects I put in cache as value, so if the code were limited to this program I'm developing now only, sure, there would be no reason. However, I could not use it if I put this class in a package and tried to use it elsewhere, no? The code would not be reusable (plus not open-close, that is open for extension but closed for modification)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:53:02.723", "Id": "413367", "Score": "0", "body": "Your last edit did not invalidate any answers, but please keep in mind that editing the code in a question (or providing a newer version) is frowned and often unacceptable the moment answers are posted. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Just a heads-up to keep in mind for your future activity on this site." } ]
[ { "body": "<p>I would consider using <code>get(cache_key)</code> within <code>obj_setattr</code>, rather than re-implementing it.</p>\n\n<p>Another thing to look at would be to use a decorator to activate the lock, instead of writing the <code>with</code> every time. This would scale better in case you want to do some preprocessing / postprocessing later in time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:56:29.607", "Id": "413412", "Score": "0", "body": "This looks like a good suggestion to improve the code; therefore it's correct to write an answer rather than a comment. Welcome to Code Review; please stay around and contribute some more!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:35:23.473", "Id": "213715", "ParentId": "213710", "Score": "2" } }, { "body": "<p>The design may sound fine as long as you’re using a single <code>default_factory</code> throughout your application; but this design permit more than that and does not handle it properly.</p>\n\n<p>You could have two parts of your application (say two <code>tornado.web.RequestHandler</code> or two <code>threading.Thread</code>) that uses your singleton like:</p>\n\n<pre><code># part 1\ncache = ThreadSafeSingletonCache(int)\ncache.set(username, user_id)\ncount = cache.get('count')\ncache.set('count', count + 1)\n…\n\n# part 2\ncache = ThreadSafeSingletonCache(dict)\nsettings = cache.get(username)\n…\n</code></pre>\n\n<p>This may not be <em>how</em> you use it, but it is something you <em>can</em> do. So, in this scenario, what could possibly go wrong? Well, both parts could start executing \"at the same time\", run the <code>cache = …</code> line one after the other and then, either <code>count</code> can be a <code>dict</code> instead of an <code>int</code> or <code>settings</code> can be an <code>int</code> instead of a <code>dict</code>.</p>\n\n<p>There are various ways to solve this, but having to specify the internal type held by your singleton <em>at each instantiation</em> is not one of them. Ideally you want either:</p>\n\n<ol>\n<li>to let the singleton aspect out of the cache and let the calling code decide on its own if it needs a single instance or not (using global objects, shared state, or whatever…);</li>\n<li>to specify a single time which kind of object is stored in the cache, ideally in a setup phase before spawning threads/IO loop;</li>\n<li>to specify the kind of queried objects at the <code>get</code> call, like a regular <code>dict.get</code> call.</li>\n</ol>\n\n<p>Implementing the first solution is very easy, just drop the <code>__new__</code> method and call it a day, it is not your problem anymore. The second one could use an init like:</p>\n\n<pre><code>def __init__(self, default_factory=None):\n factory = self.default_factory\n if factory is None:\n if default_factory is None:\n raise RuntimeError('must specify a factory at first instantiation')\n self.default_factory = default_factory\n elif default_factory is not None:\n raise RuntimeError('should not specify a default factory more than once')\n</code></pre>\n\n<p>Of course, you’ll need to define the <code>default_factory = None</code> argument at class level for this to work. This implementation is not wrapped into locks because this could allow a call with and without <code>default_factory</code> to compete and run into a <code>RuntimeError</code> anyway. So the first call <strong>must</strong> be done in a race-condition-free part of the code.</p>\n\n<p>The last solution is by far my favorite as it is the most versatile and the least surprising: just mimic <code>dict.get</code> and ask for either a default value or a default constructor.</p>\n\n<hr>\n\n<p>Also for this particular class, I would implement <code>__getitem__</code> and <code>__setitem__</code> for ease of use. And, for stylistic reasons, recommend the <a href=\"http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/\" rel=\"nofollow noreferrer\">Borg pattern</a>. <em>e.g.</em>:</p>\n\n<pre><code>class ThreadSafeCache:\n __shared_state = {\n 'default_factory': None,\n '_lock': threading.Lock(),\n '_cache': {},\n }\n def __init__(self, default_factory=None):\n self.__dict__ = self.__class__.__shared_state\n\n factory = self.default_factory\n if factory is None:\n if default_factory is None:\n raise RuntimeError('must specify a factory at first instantiation')\n self.default_factory = default_factory\n elif default_factory is not None:\n raise RuntimeError('should not specify a default factory more than once')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T16:55:38.010", "Id": "413415", "Score": "0", "body": "Thank you for pointing out that problem with default_factory. Re Borg pattern: well, I started with it.. until I've ran into severe criticisms of Borg pattern as such, see e.g. https://stackoverflow.com/questions/34568923/borg-design-pattern At this point I'm not really sure what to think about it.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:25:31.707", "Id": "413470", "Score": "0", "body": "@LetMeSOThat4U Well, if you want to keep the `default_factory` parameter, you won't be able to use a module globals to store your singleton. So you're left with overriding `__new__` or using the borg pattern. At this point this is stylistic preferences to me, as the overhead of creating a new borg each time is way less than a blocking lock. I do agree, however, that if you go the `dict.get` route, a module globals is way simpler and more adapted. See for instance Django's settings or tornado's options." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T13:27:27.570", "Id": "213727", "ParentId": "213710", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T10:14:08.323", "Id": "213710", "Score": "1", "Tags": [ "python", "thread-safety", "tornado" ], "Title": "Thread-safe singleton cache (Python)" }
213710
<p>I had answered <a href="https://stackoverflow.com/q/54730422/1757805">this</a> question from stackoverlow and the code below is code that I wrote to explain to the OP a possible way to achieve what I believe they were looking for. </p> <p>The general idea that I got from them was that they were trying to open a file with a specified file name and if that file does exist that they in turn wanted to create a new file with the same filename but with extra characters appended to the filename.</p> <p>This is the small program that I wrote to mimic that behavior.</p> <pre><code>#include &lt;string&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; int main() { std::string originalFilename("out.txt"); std::string extension(".txt"); std::string nextFilename; bool originalFileFound = false; // First test to see if original file exist by opening // if so then generate the next usable name std::fstream fileIn( originalFilename, std::ios::in ); unsigned int counter = 0; if (fileIn.is_open()) { counter++; nextFilename = originalFilename.substr( 0, originalFilename.size() - extension.size() ) + "_" + std::to_string(counter) + extension; originalFileFound = true; } fileIn.close(); // Generate a few files with the appended number system to // the end of the original filename if the original file was found. if ( originalFileFound ) { for ( int i = 1; i &lt; 6; i++ ) { std::fstream nextFile; nextFile.open( nextFilename, std::ios::out ); if (nextFile.is_open()) { nextFile &lt;&lt; nextFilename; // Write this before updating... counter++; nextFilename = nextFilename.substr(0, nextFilename.find_first_of('_') + 1) + std::to_string(counter) + extension; } nextFile.close(); } } return 0; } </code></pre> <p>I would like to know if there is a more elegant, more efficient and cleaner way to achieve this using modern C++. Writing this simple program in essence was basically self practice to improve my skills with string manipulation and the string's set of library functions and algorithms. </p>
[]
[ { "body": "<ul>\n<li><p>Prefer RAII-style opening the file in the constructor. You already done that with</p>\n\n<pre><code> std::fstream fileIn( originalFilename, std::ios::in );\n</code></pre>\n\n<p>so why not follow the suit with</p>\n\n<pre><code> std::fstream nextFile(nextFilename, std::ios::out);\n</code></pre></li>\n<li><p>There is no need to explicitly <code>nextFile.close();</code>. The destructor will take care of it at the end of each iteration.</p></li>\n<li><p>There is nothing wrong with the early return. Instead of setting <code>originalFileFound = true;</code>, and testing it later on, quit immediately if opening fails. That would spare a boolean flag and a level of indentation.</p></li>\n<li><p>Consolidate handling of <code>nextFilename</code> in one place. Consider</p>\n\n<pre><code> if (!fileIn.is_open()) {\n print_error_message();\n return 1;\n }\n\n std::string prefix = originalFilename.substr(0, originalFilename.size() - extension.size());\n\n for (int i = 0, counter = 0; counter &lt; 5; i++) {\n nextFilename = prefix + \"_\" + std::to_string(i) + extension;\n ....\n }\n</code></pre></li>\n<li><p>I would be very cautious to use this program, because it may overwrite existing files.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T20:42:20.843", "Id": "413460", "Score": "0", "body": "I truly appreciate the feed back. Using a temp string for prefix does make the code look a little more cleaner and concise. And yes I know that this could potentially overwrite existing files, but as I stated it was just a demonstration program to an already existing question over at stackoverflow. I could turn this into a function that would take file manipulation flags as arguments, such as appending, overwriting etc." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:37:57.853", "Id": "213752", "ParentId": "213717", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T11:12:20.540", "Id": "213717", "Score": "3", "Tags": [ "c++", "algorithm", "strings", "file", "stream" ], "Title": "Concatenating an already existing filename to create a new file" }
213717
<p>I'm working on a game project (with Unity) that shall handle user credentials and other data. The game connects send requests to a php script and this script send requests to the database. After spending some days learning about sql injections and password handling, I came up with this approach. I am obviously still very naive with all this, but I would like to know if it is good or not. The first one is the script for creating a new user, and the second one is for login.</p> <pre><code>&lt;?php $servername = "localhost"; $username = "whatever"; $password = "whatever"; $dbname = "whatever"; try { $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $db-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $salt = bin2hex(random_bytes(strlen($_POST["providedpass"]))); $hashpsw = hash('sha256', $_POST["providedpass"].$salt); $name = $_POST["usrnm"]; $stmt = $db-&gt;prepare("INSERT INTO users (username, password, salt, level) VALUES (?,?,?,?)"); if ($stmt-&gt;execute(array($name,$hashpsw, $salt, 1))) { echo "USER CREATED"; } $db = null; } catch (PDOException $e){ echo "Error: " . $e-&gt;getMessage(); } ?&gt; </code></pre> <p>-</p> <pre><code>&lt;?php $servername = "localhost"; $username = "whatever"; $password = "whatever"; $dbname = "whatever"; try { $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $db-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $db-&gt;prepare("SELECT * FROM users WHERE username = ?"); $providedname= $_POST["usrnm"]; $stmt-&gt;execute(array($providedname)); while($row = $stmt-&gt;fetch(PDO::FETCH_OBJ)){ echo "FOUND USER"; $hashpsw = hash('sha256', $_POST["providedpass"].$row-&gt;salt); if($hashpsw == $row-&gt;password) { echo "CORRECT CREDENTIALS"; } } $db = null; } catch (PDOException $e){ echo "Error: " . $e-&gt;getMessage(); } ?&gt; </code></pre>
[]
[ { "body": "<p>Nope, it is not safe. You can refer to the <a href=\"https://www.ibm.com/developerworks/library/wa-php-renewed_2/index.html\" rel=\"nofollow noreferrer\">following article</a> thet explains why you shouldn't use SHA-family hashing and required to use password_hash() instead. Beside other things, it means that salt field should be removed, and password field should be varchar(255).</p>\n\n<p>To soften the pill, I've got the <a href=\"https://phpdelusions.net/pdo_examples/password_hash\" rel=\"nofollow noreferrer\">reference code to check the hashed passsword</a>.</p>\n\n<p>There is one more issue which is connected to security: wherever an error occurs, <strong>you are echoing it right in the hands of a potential hacker</strong>, revealing a lot of sensitive information about your software, database structure, etc. You should never ever be doing things like <code>echo \"Error: \" . $e-&gt;getMessage();</code>! For more info refer to my article on the basics of <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a></p>\n\n<p>Everything else is rather good, save for <em>peculiar code formatting</em> and unnecessary WHILE statement. When you expect just a single row, there is no need to run a while loop. Just fetch your row right away.</p>\n\n<p>Also, it does no good to duplicate the database connection code. Store it in a file and just include wherever needed.</p>\n\n<p>So the refactored version would be like</p>\n\n<p>db.php:</p>\n\n<pre><code>&lt;?php\n\n$servername = \"localhost\";\n$username = \"whatever\";\n$password = \"whatever\";\n$dbname = \"whatever\";\n$charset = 'utf8mb4';\n\n$options = [\n PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC,\n PDO::ATTR_EMULATE_PREPARES =&gt; false,\n];\n$dsn = \"mysql:host=$servername;dbname=$dbname;charset=$charset\";\ntry {\n $db = new PDO($dsn, $username, $password, $options);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e-&gt;getMessage(), (int)$e-&gt;getCode());\n}\n</code></pre>\n\n<p>register.php</p>\n\n<pre><code>require 'db.php';\n$hashpsw = password_hash($_POST[\"providedpass\"],);\n\n$stmt = $db-&gt;prepare(\"INSERT INTO users (username, password, level) VALUES (?,?,?)\");\n$stmt-&gt;execute(array($_POST[\"usrnm\"], $hashpsw, 1));\necho \"USER CREATED\";\n</code></pre>\n\n<p>auth.php:</p>\n\n<pre><code>require 'db.php';\n$stmt = $db-&gt;prepare(\"SELECT * FROM users WHERE username = ?\");\n$stmt-&gt;execute([$_POST['usrnm']]);\n$user = $stmt-&gt;fetch();\n\nif ($user &amp;&amp; password_verify($_POST['providedpass'], $user['password']))\n{\n echo \"FOUND USER\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:48:10.927", "Id": "413409", "Score": "0", "body": "Thank you so much, I'll follow your advices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T12:48:12.890", "Id": "413534", "Score": "0", "body": "Would it be secure to store the username and the hashed password in the session variables?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:22:15.973", "Id": "213721", "ParentId": "213718", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T11:30:56.283", "Id": "213718", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "User registration and authentication using hashed passwords" }
213718
<p>I'm trying to write a policy based auto-registering class using the Curiously Recurring Template Pattern. I decided as design choice to not using registering macro.</p> <p><strong>Factory Class</strong></p> <pre><code>template&lt;typename Base&gt; class Factory{ template&lt;typename, typename&gt; friend class Registrable; public: static Base* create(std::string name){ auto callable = map().at(std::move(name)); return callable(); } static std::unique_ptr&lt;Base&gt; createUnique(std::string name){ auto callable = map().at(std::move(name)); return std::unique_ptr&lt;Base&gt;(callable()); } static std::shared_ptr&lt;Base&gt; createShared(std::string name){ auto callable = map().at(std::move(name)); return std::shared_ptr&lt;Base&gt;(callable()); } private: static std::unordered_map&lt; std::string, std::function&lt;Base*()&gt; &gt;&amp; map(){ static std::unordered_map&lt; std::string, std::function&lt;Base*()&gt; &gt; map; return map; } template&lt;typename Derived&gt; static void subscribe(std::string name){ // insert already-exist-check here std::cout&lt;&lt; "registered: " &lt;&lt; name &lt;&lt; std::endl; map().emplace(std::move(name), [](){ return static_cast&lt;Base*&gt;(new Derived{}); }); } }; </code></pre> <p><strong>Registrable Class</strong></p> <pre><code>template&lt;typename Base, typename Derived&gt; class Registrable{ protected: virtual std::string registerName() const = 0; Registrable(){ isRegistered = true; } ~Registrable() = default; static bool init(){ Derived t; Factory&lt;Base&gt;::template subscribe&lt;Derived&gt;(t.registerName()); return true; } private: static bool isRegistered; }; template&lt;typename Base, typename Derived&gt; bool Registrable&lt;Base, Derived&gt;::isRegistered = Registrable&lt;Base, Derived&gt;::init(); </code></pre> <p><strong>Client Code Example</strong></p> <pre><code>struct MyFactoryBase{ virtual ~MyFactoryBase() = default; virtual void method() const = 0; }; struct MyFactory1 : public MyFactoryBase, public Registrable&lt;MyFactoryBase, MyFactory1&gt;{ std::string registerName() const override{ return "Class1"; } void method() const override{ std::cout &lt;&lt; "yay Class1" &lt;&lt; std::endl; } MyFactory1() : MyFactoryBase(), Registrable&lt;MyFactoryBase, MyFactory1&gt;(){} }; struct MyFactory2 : public MyFactoryBase, public Registrable&lt;MyFactoryBase, MyFactory2&gt;{ std::string registerName() const override{ return "Class2"; } void method() const override{ std::cout &lt;&lt; "yay Class2" &lt;&lt; std::endl; } MyFactory2() : MyFactoryBase(), Registrable&lt;MyFactoryBase, MyFactory2&gt;(){} }; </code></pre> <p><strong><a href="https://onlinegdb.com/S1f9n7_BN" rel="nofollow noreferrer">LIVE EXAMPLE</a></strong></p> <p>This code was meant to be in Qt, so originally was with <code>QMap</code> instead of <code>std::unordered_map</code> and <code>QString</code> instead of <code>std::string</code>, I could have missed something due to the conversion of the code.</p> <p>There are improvements I could do or issues I'm not considering?</p> <p>Please review.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T11:47:00.987", "Id": "213719", "Score": "2", "Tags": [ "c++", "design-patterns", "abstract-factory" ], "Title": "Auto-registering CRTP Factory" }
213719
<p>I completed this WordPress coding task as part of an interview. I'm hoping someone can review my work and comment on everything, especially my general approach to the task, and the sanitization of output. The client's previous developer had already completed this project, but was leaving the company. So the client was going to compare my code to the code from his previous dev, to see how I sized up. Here are the requirements:</p> <p><strong>Requirements</strong></p> <ul> <li>Create a new page in the WordPress admin menu, named "Reports."</li> <li>The Reports page will display a table listing all posts of type 'contact' (an existing custom post type.</li> <li>The table on the Reports page will display data for only eight specific post authors. The IDs of those post authors will be given to you beforehand, and hard coded into the program.</li> <li>The table will display only the following columns: Contact Name, Contact Creation Date, Contact Author.</li> <li>See <a href="https://i.imgur.com/HqEGK4l.jpg" rel="nofollow noreferrer">this screenshot</a> for an illustration of the final product. <hr></li> </ul> <p>My code is at the very bottom of this post. Here are some of my caveats/rationale.</p> <p><strong>Approach/Rationale</strong></p> <ul> <li><p>My approach was to use the built-in WordPress <a href="https://codex.wordpress.org/Class_Reference/WP_List_Table" rel="nofollow noreferrer">WP_List_Table class</a> to create the table. Building and displaying a table like this seems to be the main purpose of that class.</p></li> <li><p>I did not copy the WP_List_Table class to my child theme, as suggested in the Codex. I guess best practice would be to do so? I believe some of the tutorials I read on the class omitted that step--not sure why.</p></li> <li><p>All code was added to my theme's functions.php file, with the exception of a small separate users.php file, which was added to the child theme directory. I realize custom code is typically added to a child theme. But in this case, this was a requirement of the client. Actually, the parent theme in-question was already a custom theme (created and implemented by the client).</p></li> <li><p>In the SQL SELECT statement, I did not sanitize any of my output with esc_sql() or prepare(). As I understand, such sanitization is required only if there is a chance that the data could be harmful or unexpected code. In my case, every element of the SELECT statement is hard code, so there doesn't seem like any chance that it could be harmful. But I may be misunderstanding something there. Furthermore, I did not sanitize any of the other output because of the same reason (all input is hard code). I also assumed(!) that the WP_List_Table() class would handle any necessary escaping of output for me. I guess I should at least confirm that.</p></li> </ul> <hr> <p><strong>functions.php code</strong></p> <pre><code>/*Begin code to add 'Reports' admin section.*/ if(!class_exists('WP_List_Table')){ include_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } /*Create a new list table package that extends the core WP_List_Table class.*/ class TV_List_Table extends WP_List_Table { function __construct(){ global $status, $page; parent::__construct( array( 'singular' =&gt; 'Contact', //singular name of the listed records 'plural' =&gt; 'contacts', //plural name of the listed records 'ajax' =&gt; false //does this table support ajax? ) ); } /* This method is called when the parent class can't find a method specifically build for a given column.*/ function column_default($item, $column_name){ $msg_error = "No available data."; $user = get_user_by( 'id', $item['post_author'] ); switch($column_name){ case 'contact_name': return print_r($user-&gt;user_nicename,true); case 'date_created': return print_r($item['post_date'],true); default: return print_r($msg_error,true); } } /* This method is responsible for rendering the 'Contact Name' column.*/ function column_title($item){ return sprintf('%1$s',$item['post_title']); } /*This method dictates the table's column slugs and headers.*/ function get_columns(){ $columns = array( 'title' =&gt; 'Contact Name', 'date_created' =&gt; 'Date Created', 'contact_name' =&gt; 'Created By' ); return $columns; } /*Method to prepare the data that will be displayed in the table.*/ function prepare_items() { global $wpdb; include(ABSPATH . 'wp-content/themes/contacts-db-child/users.php'); /*Define the column headers, including the sortable and hidden columns (if any).*/ $columns = $this-&gt;get_columns(); $hidden = array(); $sortable = array(); $this-&gt;_column_headers = array($columns, $hidden, $sortable); //Build the users portion of the SQL statement. $sel_users = ""; for ($i = 0; $i &lt;= count($users)-1; $i++) { if ($i == count($users)-1) { $sel_users .= "P.post_author = ". $users[$i]; } else { $sel_users .= "P.post_author = ". $users[$i] . " or "; } } $user_query = "SELECT P.ID, P.post_title, P.post_date, P.post_author FROM wp_posts AS P WHERE P.post_type = 'contact' and P.post_status = 'publish' and (" . $sel_users . ") ORDER BY post_title"; $query_results = $wpdb-&gt;get_results( $user_query, ARRAY_A ); $this-&gt;items = $query_results; } } /*Add the new 'Reports' page to the admin menu.*/ function tv_add_menu_items(){ $reports_page = "contact_reports.php"; add_menu_page('Reports', 'Reports', 'manage_options', $reports_page, 'tv_render_list_page', 'dashicons-clipboard', 6); } add_action('admin_menu', 'tv_add_menu_items'); /* This function will add all content to the 'Reports' page.*/ function tv_render_list_page(){ //Create an instance of our list class $ListTable = new TV_List_Table(); //Fetch, prepare, sort, and filter our data. $ListTable-&gt;prepare_items(); ?&gt; &lt;div class="wrap"&gt; &lt;div id="icon-users" class="icon32"&gt;&lt;/div&gt; &lt;h2&gt;Reports&lt;/h2&gt; &lt;?php $ListTable-&gt;display() ?&gt; &lt;/div&gt; &lt;?php } /*End code to add 'Reports' admin section.*/ </code></pre> <hr> <p><strong>users.php code</strong></p> <pre><code>&lt;?php /*List of WordPress user IDs that will be used to generate 'Reports' admin section.*/ $users = array( 1, 8, 12, 13, 15, 16, 18 ); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T12:35:55.307", "Id": "213722", "Score": "2", "Tags": [ "php", "wordpress" ], "Title": "Create a new WordPress admin page, and add an admin table to it" }
213722
<p>I made myself a simple script (Batch/JScript) that download a pic from a blog (APOD) &amp; set it as wallpaper.</p> <pre class="lang-none prettyprint-override"><code>@if (@a==@b) @end /* Set BaseUrl=https://apod.nasa.gov/apod/ set yr=%date:~8,2% set mn=%date:~3,2% set dy=%date:~0,2% set dte=%yr%%mn%%dy% set SaveDest=C:\Users\ME\Desktop\Wallpaper\%dte%.jpg Set Url=%baseUrl%ap%dte%.html @echo off setlocal for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%Url%"') do ( rem echo %%I set LastImg=%%I ) set ImgUrl=%BaseUrl%%LastImg:~6% bitsadmin.exe /transfer GETWALLPAPER %ImgUrl% %SaveDest% timeout /t 01 reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d %savedest% /f timeout /t 01 for /l %%x in (1,1,80) do ( RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d %savedest% /f timeout /t 01 ) goto :EOF JScript */ function fetch(url) { var xhr=WSH.CreateObject("Microsoft.XMLHTTP"); var dom=WSH.CreateObject('htmlfile'); xhr.open("GET",WSH.Arguments(0),true); xhr.setRequestHeader('User-Agent','XMLHTTP/1.0'); xhr.send(''); while (xhr.readyState!=4) {WSH.Sleep(25)}; dom.write('&lt;meta http-equiv="x-ua-compatible" content="IE=9" /&gt;'); dom.write(xhr.responseText); return dom; } var dom=fetch(WSH.Arguments(0)); var link=dom.getElementsByTagName('IMG'); WSH.Echo(link[0].src); </code></pre> <p>It's working. However, I am unhappy about the <code>for /l %%x in (1,1,80) d</code> loop: it seems not to work without the loop. Any Idea ?</p>
[]
[ { "body": "<p><strong><em>First :</em></strong> I recommend you to change this line in your code in order to anybody can use it easily without changing or editing it.</p>\n\n<pre><code>set SaveDest=C:\\Users\\ME\\Desktop\\Wallpaper\\%dte%.jpg\n</code></pre>\n\n<p>by those lines :</p>\n\n<pre><code>set WallpaperFolder=%userprofile%\\Desktop\\Wallpaper\nIf not exist \"%WallpaperFolder%\" MD \"%WallpaperFolder%\"\nset SaveDest=%WallpaperFolder%\\%dte%.jpg\n</code></pre>\n\n<p><strong><em>Second :</em></strong> If you want to hide the output of the console you can redirect it to <code>NUL</code> </p>\n\n<p>for example : <code>reg add \"HKEY_CURRENT_USER\\Control Panel\\Desktop\" /v Wallpaper /t REG_SZ /d %savedest% /f&gt;nul</code></p>\n\n<p>And this line too : <code>timeout /t 1 /nobreak&gt;nul</code></p>\n\n<p><strong><em>Third :</em></strong> Refer to <a href=\"https://superuser.com/questions/398605/how-to-force-windows-desktop-background-to-update-or-refresh?answertab=active#tab-top\">How to force Windows desktop background to update or refresh</a></p>\n\n<p>You can write it simply by this line and avoid the loop : <code>RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters 1, True</code></p>\n\n<p>So, the whole code can be written like this :</p>\n\n<pre><code>@if (@a==@b) @end /*\n@echo off\nTitle Download NASA images to use as Windows wallpaper\ncolor 0A &amp; Mode 70,3\nSet BaseUrl=https://apod.nasa.gov/apod/\nset yr=%date:~8,2%\nset mn=%date:~3,2%\nset dy=%date:~0,2%\nset dte=%yr%%mn%%dy%\nset WallpaperFolder=%userprofile%\\Desktop\\Wallpaper\nIf not exist \"%WallpaperFolder%\" MD \"%WallpaperFolder%\"\nset SaveDest=%WallpaperFolder%\\%dte%.jpg\nSet Url=%baseUrl%ap%dte%.html\n\nsetlocal\nfor /f \"delims=\" %%I in ('cscript /nologo /e:jscript \"%~f0\" \"%Url%\"') do (\n echo %%I\n set LastImg=%%I\n)\n\nset ImgUrl=%BaseUrl%%LastImg:~6%\n\nbitsadmin.exe /transfer GETWALLPAPER \"%ImgUrl%\" \"%SaveDest%\"\necho(\necho Please wait a while ... Update UserSystemParameters \nreg add \"HKEY_CURRENT_USER\\Control Panel\\Desktop\" /v Wallpaper /t REG_SZ /d \"%savedest%\" /f&gt;nul\nTimeout /t 1 /nobreak&gt;nul\nRUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters 1, True\ngoto :EOF\n\nJScript */\nfunction fetch(url) {\n var xhr=WSH.CreateObject(\"Microsoft.XMLHTTP\");\n var dom=WSH.CreateObject('htmlfile');\n xhr.open(\"GET\",WSH.Arguments(0),true);\n xhr.setRequestHeader('User-Agent','XMLHTTP/1.0');\n xhr.send('');\n while (xhr.readyState!=4) {WSH.Sleep(25)};\n dom.write('&lt;meta http-equiv=\"x-ua-compatible\" content=\"IE=9\" /&gt;');\n dom.write(xhr.responseText);\n return dom;\n}\nvar dom=fetch(WSH.Arguments(0));\nvar link=dom.getElementsByTagName('IMG');\nWSH.Echo(link[0].src);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T14:17:00.463", "Id": "461422", "Score": "1", "body": "Thank you. very instructive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:03:51.520", "Id": "461926", "Score": "0", "body": "@a1a1a1a1a1 You can give a try for my vbscript version here [NASA_Wallpaper.vbs](https://pastebin.com/9QD2NfyQ)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-13T10:36:22.463", "Id": "235545", "ParentId": "213724", "Score": "3" } } ]
{ "AcceptedAnswerId": "235545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T13:03:26.960", "Id": "213724", "Score": "4", "Tags": [ "javascript", "http", "windows", "batch" ], "Title": "Download NASA images to use as Windows wallpaper" }
213724
<p>One of the big problems I have is cleanly converting from an internal datatype to an external datatype. We can all do it the not so clean way, however I think this add too much mess.</p> <p>I can use libraries that read from a filetype to a Python object, however some libraries don't allow you to convert the data from one type to another. Most libraries also don't allow converting from one structure to another, so if you need data to be nested when it comes flat, you have to perform the conversion manually.</p> <p>This library still uses these filetype libraries to convert to a Python object. It just offloads some of the work from these libraries. And adds some features I don't think will be added to these libraries.</p> <hr> <p>This library consists of two public classes; <code>Converter</code> and <code>Converters</code>. These work almost completely independently. A short explanation of most of the code is:</p> <ul> <li><code>Converters</code> defines some <code>property</code> functions, these interface with <code>Converter._obj</code> to convert to and from the base class.</li> <li><code>ron</code> is used to raise when <code>Converter._obj</code> returns a 'null' (A <code>BuilderObject</code>), this is as we build a <code>BuilderObject</code> before building the actual class. This allows you to initialize using <code>setattr</code>, rather than just passing a dictionary. Which I find to be a little cleaner at times.<br> This should be used whenever you get data from <code>Converter._obj</code>.</li> <li><code>BuilderObject</code> is a simple object that defaults nested objects to itself. This means we can build nested datatypes without having to build the objects themselves - as we don't have the data.</li> <li><code>Converter</code> is a small unobtrusive class to convert to and from the base class and itself. Providing <code>T</code> when using the class is required for the code to work.</li> </ul> <pre><code>from datetime import datetime from typing import Generic, TypeVar, Type, get_type_hints, Union, List, Optional, Tuple, Any __all__ = ['ron', 'Converter', 'Converters'] T = TypeVar('T') class BuilderObject: def __init__(self): super().__setattr__('__values', {}) def __getattr__(self, name): return super().__getattribute__('__values').setdefault(name, BuilderObject()) def __setattr__(self, name, value): super().__getattribute__('__values')[name] = value def __delattr__(self, name): del super().__getattribute__('__values')[name] def _build(base: Type[T], values: Union[BuilderObject, dict]) -&gt; T: """Build the object recursively, utilizes the type hints to create the correct types""" types = get_type_hints(base) if isinstance(values, BuilderObject): values = super(BuilderObject, values).__getattribute__('__values') for name, value in values.items(): if isinstance(value, BuilderObject) and name in types: values[name] = _build(types[name], value) return base(**values) def _get_args(obj: object, orig: Type) -&gt; Optional[Tuple[Type]]: """Get args from obj, filtering by orig type""" bases = getattr(type(obj), '__orig_bases__', []) for b in bases: if b.__origin__ is orig: return b.__args__ return None class Converter(Generic[T]): _obj: T def __init__(self, **kwargs) -&gt; None: self._obj = BuilderObject() for name, value in kwargs.items(): setattr(self, name, value) def build(self, exists_ok: bool=False) -&gt; T: """Build base object""" t = _get_args(self, Converter) if t is None: raise ValueError('No base') base_cls = t[0] if isinstance(self._obj, base_cls): if not exists_ok: raise TypeError('Base type has been built already.') return self._obj self._obj = _build(base_cls, self._obj) return self._obj @classmethod def from_(cls, b: T): """Build function from base object""" c = cls() c._obj = b return c def ron(obj: T) -&gt; T: """Error on null result""" if isinstance(obj, BuilderObject): raise AttributeError() return obj TPath = Union[str, List[str]] class Converters: @staticmethod def _read_path(path: TPath) -&gt; List[str]: """Convert from public path formats to internal one""" if isinstance(path, list): return path return path.split('.') @staticmethod def _get(obj: Any, path: List[str]) -&gt; Any: """Helper for nested `getattr`s""" for segment in path: obj = getattr(obj, segment) return obj @classmethod def property(cls, path: TPath, *, get_fn=None, set_fn=None): """ Allows getting data to and from `path`. You can convert/type check the data using `get_fn` and `set_fn`. Both take and return one value. """ p = ['_obj'] + cls._read_path(path) def get(self): value = ron(cls._get(self, p)) if get_fn is not None: return get_fn(value) return value def set(self, value: Any) -&gt; Any: if set_fn is not None: value = set_fn(value) setattr(cls._get(self, p[:-1]), p[-1], value) def delete(self: Any) -&gt; Any: delattr(cls._get(self, p[:-1]), p[-1]) return property(get, set, delete) @classmethod def date(cls, path: TPath, format: str): """Convert to and from the date format specified""" def get_fn(value: datetime) -&gt; str: return value.strftime(format) def set_fn(value: str) -&gt; datetime: return datetime.strptime(value, format) return cls.property(path, get_fn=get_fn, set_fn=set_fn) </code></pre> <p>An example of using this code is:</p> <pre><code>from dataclasses import dataclass from datetime import datetime from converters import Converter, Converters from dataclasses_json import dataclass_json @dataclass class Range: start: datetime end: datetime @dataclass class Base: date: datetime range: Range @dataclass_json @dataclass(init=False) class International(Converter[Base]): date: str = Converters.date('date', '%d/%m/%y %H:%M') start: str = Converters.date('range.start', '%d/%m/%y %H:%M') end: str = Converters.date('range.end', '%d/%m/%y %H:%M') class American(Converter[Base]): date: str = Converters.date('date', '%m/%d/%y %H:%M') start: str = Converters.date('range.start', '%m/%d/%y %H:%M') end: str = Converters.date('range.end', '%m/%d/%y %H:%M') if __name__ == '__main__': i = International.from_json('''{ "date": "14/02/19 12:00", "start": "14/02/19 12:00", "end": "14/02/19 12:00" }''') b = i.build() a = American.from_(b) FORMAT = '{1}:\n\tdate: {0.date}\n\tstart: {0.range.start}\n\tend: {0.range.end}' FORMAT_C = '{1}:\n\tdate: {0.date}\n\tstart: {0.start}\n\tend: {0.end}' print(FORMAT.format(b, 'b')) print(FORMAT_C.format(a, 'a')) print(FORMAT_C.format(i, 'i')) print('\nupdate b.date') b.date = datetime(2019, 2, 14, 12, 30) print(FORMAT.format(b, 'b')) print(FORMAT_C.format(a, 'a')) print(FORMAT_C.format(i, 'i')) print('\nupdate b.range.start') b.range.start = datetime(2019, 2, 14, 13, 00) print(FORMAT.format(b, 'b')) print(FORMAT_C.format(a, 'a')) print(FORMAT_C.format(i, 'i')) print('\njson dump') print(i.to_json()) </code></pre> <p>From a code review I mostly want to focus on increasing the readability of the code. I also want to keep <code>Converter</code> to contain all of the logic, whilst also being very transparent so that most libraries like <code>dataclasses_json</code> work with it. I don't care about performance just yet.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T14:28:27.417", "Id": "413392", "Score": "2", "body": "@BenoîtPilatte I don't think discussing this in the comments will achieve any good. Please feel free to post an answer if you wish. An explanation on my abuse of the 'hinting' system, an explanation of where this 'call stack hell' is and an explanation of why I want code to convert datatypes (the opposite of what I want) would be good to see in this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-26T22:23:05.370", "Id": "414499", "Score": "0", "body": "Say `Range` has a third attribute `step: int`, how would you refer to it in your external classes? `step: int = Converters.property('range.step')`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-26T22:27:54.573", "Id": "414500", "Score": "0", "body": "@MathiasEttinger Yeah assuming it's defined in `Range` too. If you need to convert to int from str then you can use `step: int = Converters.property('range.step', get_fn=str, set_fn=int)`." } ]
[ { "body": "<p>There are a couple of things that come to mind when reading your code. I'll write them down, in no particular order of importance.</p>\n\n<p>Your example imports your library like this:</p>\n\n<p><code>from converters import Converter, Converters</code></p>\n\n<p>That's a major code smell. You import both a <code>Converter</code> <em>and</em> <code>Converters</code> from a file named <code>converters</code>. If you have 3 things with the same name, you should name them better. Why do you have a <code>Converter</code> and a <code>Converters</code> class anyway? I'd expect one to be a collection of the other, but since <code>Converter</code> already takes a template and is generic, what the heck do I need it's multiple for? It's not intuitive and probably violates the Zen of Python on half a dozen principles.</p>\n\n<p>I see a lot of single-letter variables. While <code>T</code> is somewhat acceptable here, the rest is not. <code>i = International.from_json(</code> What? No. <code>i</code> is an index or some other integer, not something much more complicated than that. </p>\n\n<pre><code>b = i.build()\na = American.from_(b)\n</code></pre>\n\n<p>Please, no. <code>American</code> and <code>International</code> are terrible names for classes anyway. You could use it as a sub-class or sub-type or something, or an instance of a class if the class makes clear it's a date of some sort, but don't make an <code>American</code> class.</p>\n\n<p>Now we're talking about those classes anyway, did you notice the absurd amount of repetition?</p>\n\n<pre><code>class International(Converter[Base]):\n date: str = Converters.date('date', '%d/%m/%y %H:%M')\n start: str = Converters.date('range.start', '%d/%m/%y %H:%M')\n end: str = Converters.date('range.end', '%d/%m/%y %H:%M')\n\n\nclass American(Converter[Base]):\n date: str = Converters.date('date', datetime_format)\n start: str = Converters.date('range.start', datetime_format)\n end: str = Converters.date('range.end', datetime_format)\n</code></pre>\n\n<p>So, a class has 3 lines and <em>all</em> of those lines contain either <code>'%d/%m/%y %H:%M'</code> or <code>'%m/%d/%y %H:%M'</code>. Have you considered making something like this instead?</p>\n\n<pre><code>class TerriblyNamedGeneric(Converter[Base], datetime_format):\n date: str = Converters.date('date', datetime_format)\n start: str = Converters.date('range.start', datetime_format)\n end: str = Converters.date('range.end', datetime_format)\n</code></pre>\n\n<p>That's still not pretty and it can probably be done with even less repetition, but you get the idea.</p>\n\n<p>The rest of your code is riddled with ambiguity.</p>\n\n<pre><code>def from_(cls, b: T):\n \"\"\"Build function from base object\"\"\"\n c = cls()\n c._obj = b\n return c\n</code></pre>\n\n<p>Why is a build function named <code>from_</code>? What is a cls (if it's not short for <a href=\"https://en.wikipedia.org/wiki/CLS\" rel=\"noreferrer\">one of these</a>, pick a better name) and why is that entire function just a jumble of one-letter variable names?</p>\n\n<p>You say you want a review focussed on the readability. In short, I don't think it's that readable. It may work like a charm, but the readability leaves much to be desired.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-26T15:38:36.487", "Id": "414432", "Score": "1", "body": "Good answer, as discussed in chat I think `ObjectConverter` and `PropertyConverters` would be better names. I think `from_` is standard, and `cls` is standard in `classmethods`. But the rest about `from_` I agree with. Thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-26T22:10:44.887", "Id": "414495", "Score": "0", "body": "Why would `from converters import Converter, Converters` be inherently wrong? I often do `from datetime import datetime` or `from pprint import pprint` or `import socket; sock = socket.socket(…)`…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T14:26:09.157", "Id": "414597", "Score": "0", "body": "@MathiasEttinger We talked about that in chat. It's not so much wrong, as in it's unclear why you'd need to import *both* `Converter` and `Converters` from a library called `converters`. It's a naming problem. The whole thing leads to ambiguity. Plenty of libraries are plagued with it, I know. That doesn't make it right." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-26T14:59:22.500", "Id": "214326", "ParentId": "213725", "Score": "5" } }, { "body": "<p>Let's get from the simplest thing to change to the hardest one:</p>\n\n<h1>BuilderObject</h1>\n\n<p>This is actually a recursive dictionary, which is more easily achieved using either <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a> or by implementing <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__missing__\" rel=\"nofollow noreferrer\"><code>dict.__missing__</code></a>. Since you also want <code>__getattr__</code> to act like <code>__getitem__</code> and so on, I’d go the <code>dict</code> subclass route:</p>\n\n<pre><code>class BuilderObject(dict):\n def __missing__(self, item):\n self[item] = missing = BuilderObject()\n return missing\n\n def __getattr__(self, item):\n return self[item]\n\n def __setattr__(self, item, value):\n self[item] = value\n\n def __delattr__(self, item):\n del self[item]\n</code></pre>\n\n<p>Simpler to read and understand. I’m not fond of the name however, but couldn't come up with something better.</p>\n\n<h1>Converters</h1>\n\n<p>These are in fact <a href=\"https://docs.python.org/3/howto/descriptor.html\" rel=\"nofollow noreferrer\">descriptors</a> in disguise. Instead of writing the getter, setter and deleter functions to feed to <code>property</code>, you could as well write them as <code>__get__</code>, <code>__set__</code> and <code>__delete__</code> method on a custom class. Also <a href=\"https://docs.python.org/3/library/operator.html#operator.attrgetter\" rel=\"nofollow noreferrer\"><code>operator.attrgetter</code></a> is your friend, no need to rewrite it yourself:</p>\n\n<pre><code>class AttributeProxy:\n def __init__(self, path: str, *, get_fn=None, set_fn=None):\n self.__path = '_obj.' + path\n self.__parent, self.__attribute_name = self.__path.rsplit('.', 1)\n self.__getter = get_fn\n self.__setter = set_fn\n\n def __get__(self, instance, owner):\n if not issubclass(owner, Converter):\n raise RuntimeError('cannot use Property descriptors on non Converter types')\n if instance is None:\n return self\n value = operator.attrgetter(self.__path)(instance)\n if isinstance(value, BuilderObject):\n raise AttributeError\n if self.__getter is not None:\n value = self.__getter(value)\n return value\n\n def __set__(self, instance, value):\n if self.__setter is not None:\n value = self.__setter(value)\n setattr(operator.attrgetter(self.__parent)(instance), self.__attribute_name, value)\n\n def __delete__(self, instance):\n delattr(operator.attrgetter(self.__parent)(instance), self.__attribute_name)\n\n\nclass DateProxy(AttributeProxy):\n def __init__(self, path, format):\n super().__init__(\n path,\n get_fn=lambda value: value.strftime(format),\n set_fn=lambda value: datetime.strptime(value, format)\n )\n</code></pre>\n\n<h1>_get_args</h1>\n\n<p>The main purpose of this function is to check that, when one derives from <code>Converter</code>, they provide a specialization of <code>T</code>; and optionally retrieve that specialization. I find the implementation somewhat cryptic and potentially missing some edge cases. I fiddled with a metaclass so the check is performed very early in the program. This is the main advantage of the approach as you would get an error message right away, not latter on in an unrelated section of the code:</p>\n\n<pre><code>class CheckBaseExist(type):\n def __new__(mcls, name, bases, attrs):\n cls = super().__new__(mcls, name, bases, attrs)\n if not issubclass(cls, Generic):\n raise TypeError('CheckBaseExist metaclass should be used on typing.Generic subclasses')\n\n if Generic not in bases:\n # We already know that klass is a subclass of Generic so it must define __orig_bases__\n try:\n base, = cls.__orig_bases__\n except ValueError:\n raise TypeError('cannot use more than one specialization of a base CheckBaseExist class in the inheritance tree') from None\n if base.__origin__ is Generic:\n raise TypeError('no specialization provided when inheriting from a base CheckBaseExist class')\n else:\n generic_subclasses = ' or '.join(\n klass.__name__\n for klass in bases\n if klass is not Generic and issubclass(klass, Generic)\n )\n if generic_subclasses:\n raise TypeError(f'cannot use typing.Generic as a common base class with {generic_subclasses}')\n return cls\n</code></pre>\n\n<p>Not too fond of the name either… Usage being:</p>\n\n<pre><code>class Converter(Generic[T], metaclass=CheckBaseExist):\n _obj: T\n\n def __init__(self, **kwargs) -&gt; None:\n self._obj = BuilderObject()\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n def to_base(self, exists_ok: bool=False) -&gt; T:\n \"\"\"Build base object\"\"\"\n base_cls = self.__class__.__orig_bases__[0].__args__[0]\n if isinstance(self._obj, BuilderObject):\n self._obj = _build(base_cls, self._obj)\n elif not exists_ok:\n raise RuntimeError('Base type has been built already.')\n return self._obj\n\n @classmethod\n def from_base(cls, base: T):\n \"\"\"Build function from base object\"\"\"\n instance = cls()\n instance._obj = base\n return instance\n</code></pre>\n\n<p>This works as:</p>\n\n<ol>\n<li>we checked in the metaclass that <code>self.__class__.__orig_bases__</code> contains a single item;</li>\n<li><code>Generic[T]</code> ensures that <code>__args__</code> contains a single item.</li>\n</ol>\n\n<h1>_build</h1>\n\n<p>I really dislike the fact that this function relies on <code>typing.get_type_hints</code> but couldn't come up with something clean that doesn't use it, or at least does it optionally. Maybe an extra argument in the <code>AttributeProxy</code> constructor, defaulting to None. I’m not a huge fan of it, but you’ll have to provide type hints somehow anyway.</p>\n\n<p>This is important in case you want to convert to/from objects in external libraries that don't use those type hints, so you must implement a fallback mechanism.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T02:47:05.267", "Id": "414521", "Score": "0", "body": "Holy moley this is a sick answer. Thank you for staying up so late to write it! I'm going to need to digest it again tomorrow too to fully understand it. Whilst your pros for the meta class are clear, I'm not sure they outweigh the cons. 1. It'll make converting to Python <3.7 hard, as Generic has its own (iirc private) metaclass, and it'll mean it won't work with 'filetype libraries' that require metaclasses. I think I'll fix this by adding another class variable to hold the base, and have `CheckBaseExist` automagically set it. Allowing `Converter` and `GenericConverter` classes. (Thoughts?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T02:50:56.200", "Id": "414522", "Score": "0", "body": "I'm not sure \"This is important in case you want to convert to/from objects in external libraries that don't use those type hints\" is quite true. This is as it's passed `Base` not a `Converter`, and so it should be separated from these external libraries. Or have I misunderstood you here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T06:43:20.530", "Id": "414537", "Score": "0", "body": "@Peilonrayz No, it means that you can't do `Converter[socket.socket]` for instance, or anything that doesn't use type hints." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T02:19:14.820", "Id": "214372", "ParentId": "213725", "Score": "3" } } ]
{ "AcceptedAnswerId": "214372", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T13:06:47.827", "Id": "213725", "Score": "6", "Tags": [ "python", "python-3.x", "converting" ], "Title": "Internal and external datatype converter" }
213725
<p>I've written a python program to rank the names that appear in the file(s) based on their frequency. In other words, there are multiple files and want to rank the frequency of the names that appears the most first, then the least at the end. Each name can appear only once in each file. In other words, the same name cannot be repeated in the same file.</p> <p>Following is the program, that I've written, and wanted to hear your thoughts, on the style/efficiency and tips to improve the same</p> <pre><code>from pandas import DataFrame filenames = [ 'Q1.txt', 'Q2.txt' , 'Q3.txt' , 'Q4.txt'] pathToDataFiles = "C:\\DataFiles\\" outputHTMLFile =pathToDataFiles + "list.html" df = DataFrame( columns = ['Name', 'Q1', 'Q2', 'Q3', 'Q4' ]) currentQtr = 1 for filename in filenames: entireFilename = pathToDataFiles + filename # Get all the names from the file allNames = [line.rstrip('\n') for line in open(entireFilename)] # For each name from the latest .txt file for eachname in allNames: # If the name is in the dataframe then replace the current quarter with 'Y' if ( df['Name'].str.contains(eachname).any() ): rowNumber = df.loc[df['Name'] == eachname].index[0] df.iloc[[rowNumber],[currentQtr]] = 'Y' else: # It is a new name, thus, replace the current Qtr with 'Y'. Rest with be Nan emptyDataFrame =DataFrame( columns = ['Name', 'Q1', 'Q2', 'Q3', 'Q4' ]) emptyDataFrame = emptyDataFrame.append([{'Name':eachname}]) rowNumber = 0 emptyDataFrame.iloc[[rowNumber], [currentQtr]] = 'Y' df = df.append(emptyDataFrame) df.index = range(len(df)) currentQtr = currentQtr + 1 # Create a new column with 'Total' occurence of names df['Total'] = currentQtr - df.isnull().sum(axis=1) - 1 # Sort by total df = df.sort_values(by=['Total'], ascending=False) df.index = range(len(df)) # Fill all Nan with 'X' df = df.fillna('X') df.to_html(outputHTMLFile) </code></pre>
[]
[ { "body": "<p>I suggest using <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\">os.path.join</a> instead of <code>+</code> to handle dangling slashes, when concatenating file names.</p>\n\n<p>This variables:</p>\n\n<pre><code>filenames = [ 'Q1.txt', 'Q2.txt' , 'Q3.txt' , 'Q4.txt']\npathToDataFiles = \"C:\\\\DataFiles\\\\\"\n</code></pre>\n\n<p>could be better handled by using command line input like in <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>. And for <code>filename</code> you could even use <a href=\"https://docs.python.org/3/library/os.html#os.listdir\" rel=\"nofollow noreferrer\">os.listdir</a> to read all files from a directory. Both would give you more flexibility in using this script.</p>\n\n<p>Also, the variable <code>eachname</code> in <code>for eachname in allNames:</code> should be renamed in something like <code>name</code>, to prevent lines like <code>emptyDataFrame = emptyDataFrame.append([{'Name':eachname}])</code> from looking weird.</p>\n\n<p>There are a few incoherent whitespaces, too, and I think <code>Nan</code> is meant to be <code>NaN</code> (in comments).</p>\n\n<p>Apart from that, it looks like a good start to me. I hope my answer helps and have fun coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T16:48:59.977", "Id": "213735", "ParentId": "213733", "Score": "1" } }, { "body": "<p>Here are some suggestions:</p>\n\n<p><strong>Raw Strings</strong></p>\n\n<p>Python has <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals\" rel=\"nofollow noreferrer\"><em>raw strings</em></a> which make it much easier to use backslashes. The documentation is a bit scattered, but the upshot is that a raw string looks like <code>r'foo'</code> and backslashes don't need to be escaped. This makes raw strings the format of choice for writing Windows paths and regular expressions.</p>\n\n<p>I'd suggest you use something like this:</p>\n\n<pre><code>DATA_DIR = r'C:\\DataFiles'\n</code></pre>\n\n<p><strong>Python Paths</strong></p>\n\n<p>But the fact is that Python file operations will honor windows paths spelled using forward slashes (<code>/</code>) instead of backslashes (<code>\\</code>). So you could just as easily define that like this:</p>\n\n<pre><code>DATA_DIR = 'C:/DataFiles'\n</code></pre>\n\n<p><strong>Use <code>pathlib</code></strong></p>\n\n<p>Probably the most important thing you could do, however, is to start using <code>pathlib</code>. Don't bother with <code>os.path</code> for this, go directly to the good stuff! The <code>pathlib</code> module is part of the standard library, and does many things that \"just work.\" Including, of course, overloading the operator <code>/</code> to do concatenation:</p>\n\n<pre><code>from pathlib import Path\n\nDATA_DIR = Path('C:/DataFiles')\n\ntest = DATA_DIR / 'foo' # test = Path('C:/DataFiles/foo')\n</code></pre>\n\n<p><strong>[pro-tip]: Don't hard-code your file names, write code to find them</strong></p>\n\n<p>It seems easy to write something like <code>filenames = [ 'Q1.txt', 'Q2.txt' , 'Q3.txt' , 'Q4.txt']</code> and it <em>is,</em> until your boss says, \"Hey, could you add the last two calendar years to that report?\" and you're suddenly stuck trying to move files around and change your code and change the field names in your dataframe and change your HTML and change your spreadsheets and ...</p>\n\n<p>It's better if you <em>have only one source of truth</em> for things like this. In this case, let's use the filenames as the source of truth. Then we can use <code>glob</code> to match them:</p>\n\n<pre><code>from pathlib import Path\n\nDATA_DIR = Path('C:/DataFiles')\n\ndef get_data_files(data_path, pattern=\"*Q[0-9].txt\"):\n \"\"\" Return a list of data-file Path objects in the given directory\n where the name matches the pattern.\n\n Note that pattern uses Python glob rules, which allows for\n **/*.txt to recursively traverse subdirectories.\n \"\"\"\n # NB: Path(string) returns Path, Path(Path) returns Path FTW!\n filepaths = Path(data_dirspec).glob(pattern)\n return filepaths\n</code></pre>\n\n<p>Writing code like this lets you make one change - renaming <code>Q[1-4].txt</code> to <code>2019Q[1-4].txt</code> - and you still get the list of paths you need. </p>\n\n<p>Then the rest of the preamble changes to:</p>\n\n<pre><code>quarter_files = get_data_files(DATA_DIR)\n\nfor this_q in quarter_files:\n q_name = this_q.stem # 'Q1', 'Q2', etc.\n</code></pre>\n\n<p><strong>[pro-tip]: Use <code>with</code> for opening and closing files</strong></p>\n\n<p>There's an example right in the Python documentation for <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\">Reading and Writing Files</a> that shows how to use <code>with</code> for file I/O. It's built-in RAII support, if that means anything to you, and it's absolutely the correct way to do file I/O in most cases. Certainly in this one. Plus if you don't use it, every suggestion you get from anyone that (1) reads your code; and (2) knows how to code in Python is going to include \"use <code>with</code> for file I/O!\". So let's make this quick change:</p>\n\n<p>Change this:</p>\n\n<pre><code>allNames = [line.rstrip('\\n') for line in open(entireFilename)]\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>with open(this_q) as infile:\n all_names = [line.rstrip('\\n') for line in infile]\n</code></pre>\n\n<p>What's the difference? The difference is that after the <code>with</code> version, the <code>infile</code> is closed. Why does it matter? Two reasons: First, <code>with</code> handles success, failure, exceptions, and always makes sure to close the file. Second, <em>file handles</em> are a surprisingly limited resource, especially if you're debugging code in a REPL. Using <code>with</code> is a good way to never run out.</p>\n\n<p><strong>Let Python do Python</strong></p>\n\n<p>You wrote a lot of code to handle the management of names in your dataframe. But you overlooked the fact that Python has data structures other than dataframes that are easier to work with.</p>\n\n<pre><code>for eachname in allNames:\n # If the name is in the dataframe then replace the current quarter with 'Y'\n if ( df['Name'].str.contains(eachname).any() ):\n rowNumber = df.loc[df['Name'] == eachname].index[0]\n df.iloc[[rowNumber],[currentQtr]] = 'Y'\n else:\n # It is a new name, thus, replace the current Qtr with 'Y'. Rest with be Nan\n emptyDataFrame =DataFrame( columns = ['Name', 'Q1', 'Q2', 'Q3', 'Q4' ])\n emptyDataFrame = emptyDataFrame.append([{'Name':eachname}])\n rowNumber = 0\n emptyDataFrame.iloc[[rowNumber], [currentQtr]] = 'Y'\n df = df.append(emptyDataFrame)\n df.index = range(len(df))\n</code></pre>\n\n<p>First of all, you claim that names only appear once in any given quarter's data, if they appear at all. So your logic is about checking to see if a name appears in the dataframe because of some previous quarter.</p>\n\n<p>This is a good use for Python's <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"nofollow noreferrer\"><code>set</code></a> data type. You can test for containment and compute intersections and differences quite easily.</p>\n\n<pre><code>with open(this_q) as infile:\n names_this_q = {line.rstrip('\\n') for line in infile}\n</code></pre>\n\n<p>That is called a <em>set comprehension,</em> and it works similar to a <em>list comprehension</em>. (And yes, it rocks!) Sets are <em>O(1)</em> for lookup, so you can just use the <code>in</code> operator.</p>\n\n<pre><code>all_names = set() # Sadly, no literal for empty set\n\nfor this_q in quarter_files:\n with open(this_q) as infile:\n names_this_q = {line.rstrip('\\n') for line in infile}\n\n q_name = this_q.stem\n\n for name in names_this_q:\n if name in all_names:\n # Already in DF\n else:\n # Add it to DF\n</code></pre>\n\n<p>But you're really either updating an existing record, or accumulating new records. Why not capture all the new records into a python data structure and do one single dataframe update at the end? </p>\n\n<p>An even better question might be to ask if you need to use the dataframe for this at all? You are building what amounts to a boolean table. You could store the boolean values in a data structure built from <code>collections.defaultdict</code> and only convert it into a dataframe for the purpose of generating the HTML at the end.</p>\n\n<pre><code>def quarters_dict():\n \"\"\"Return a new dict of 'Qx':False for all quarter files Qx.\"\"\"\n return {qf.stem:False for qf in quarter_files}\n\n\nall_names = collections.defaultdict(quarters_dict)\n\nfor qfile in quarter_files:\n with open(this_q) as infile:\n names_this_q = {line.rstrip('\\n') for line in infile}\n\n q_name = this_q.stem\n for name in names_this_q:\n all_names[name][q_name] = True\n\n\nAnd now you have a table of name appearances. You can put `all_names` into a DataFrame and massage it however you like.\n</code></pre>\n\n<p><strong>Let Pandas do Pandas</strong></p>\n\n<p>Pandas is great at dealing with tables of data of known, basic types. It supports indexing, lookup, boolean, and database type operations. Try to see how you could use that.</p>\n\n<p>First, you are storing <code>Nan</code> and <code>'Y'</code> values in your columns: floating point and string data? The <code>Nan</code> means false and the <code>'Y'</code> means true. But there's already a True/False data type, and it is neither floating point nor string. Why not make your table a table of boolean values?</p>\n\n<p>Second, you are treating your names as a column. But they are really the index! So why not make them the index? If you do so, you can use <code>name in df</code> and not have to maintain a separate Python <code>set</code> object.</p>\n\n<p>Third, you are creating one-row dataframes to append values, and then resetting the index of your dataframe. You can just store to a new index! <code>df[new_name] = new_info</code></p>\n\n<p>Finally, the <code>df.to_html()</code> function takes a large number of parameters. Including formatting parameters that you can use to translate boolean values into <code>'X' or 'Y'</code>. </p>\n\n<p>Use the features of pandas as they were intended, and your code will get simpler, shorter, and faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:38:07.867", "Id": "413453", "Score": "0", "body": "Thanks Austin. Appreciate the time and effort for explaining in detail." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:08:38.060", "Id": "213744", "ParentId": "213733", "Score": "1" } } ]
{ "AcceptedAnswerId": "213744", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:49:26.677", "Id": "213733", "Score": "2", "Tags": [ "python", "python-3.x", "data-mining" ], "Title": "Python program to rank based on the frequency of names that appears in text files" }
213733
<p>I added Rock, Paper, Scissors to one of my programs. I'm new to python and PEP 8, so I want to see how to improve my work.</p> <pre><code>def rock_paper_scissors(name): play_rps = True while play_rps: rps = ["rock", 'paper', 'scissors'] player_rps = input("Rock, Paper, or Scissors: ").lower() com_rps = rps[random.randint(0,3)] print(com_rps) if com_rps == player_rps: print('Tie') if com_rps == 'rock' and player_rps == "scissors": print("Chatter Bot Wins!") if com_rps == 'scissors' and player_rps == "paper": print("Chatter Bot Wins!") if com_rps == 'paper' and player_rps == "rock": print("Chatter Bot Wins!") if player_rps == 'rock' and com_rps == "scissors": print(f"{name} Wins!") if player_rps == 'sicssors' and com_rps == "paper": print(f"{name} Wins!") if player_rps == 'paper' and com_rps == "rock": print(f"{name} Wins!") yn = input("Do you want to play again. Y/N: ").lower() if yn == 'n' or yn == 'no': play_rps = False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:29:56.410", "Id": "413451", "Score": "0", "body": "I forgot what pass meant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:12:29.207", "Id": "413466", "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": "<ol>\n<li>Move more of your code out of the function. Make a <code>find_winner</code> function.</li>\n<li>You don't need to add <code>_rps</code> to the end of every variable name. It only makes it harder to read the code.</li>\n<li>PEP 8 doesn't say which string delimiter to use, but says to stick to <em>one</em>. I use <code>'</code>, you may prefer <code>\"</code>.</li>\n<li>You can use <code>random.choice</code> rather than <code>random.randint</code> to select from a list.</li>\n<li><p>There is a bug in your code. I suggest you keep using string literals to a minimum to prevent this.</p>\n\n<blockquote>\n<pre><code>player_rps == 'sicssors' and com_rps == \"paper\"\n</code></pre>\n</blockquote></li>\n<li><p>You can simplify your <code>yn</code> check by using <code>in</code>.</p></li>\n</ol>\n\n<p>This in all got me:</p>\n\n<pre><code>WIN_VALUES = {\n 'rock': 'scissors',\n 'paper': 'rock',\n 'scissors': 'paper'\n}\n\n\ndef find_winner(choice1, choice2):\n if choice1 == choice2:\n return 0\n if WIN_VALUES[choice1] == choice2:\n return 1\n if WIN_VALUES[choice2] == choice1:\n return 2\n\n\ndef rock_paper_scissors(name):\n play = True\n while play:\n player = input('Rock, Paper, or Scissors: ').lower()\n com = random.choice(list(WIN_VALUES))\n print(com)\n\n winner = find_winner(com, player)\n if winner == 0:\n print('Tie')\n elif winner == 1:\n print('Chatter Bot Wins!')\n elif winner == 2:\n print(f'{name} Wins!')\n else:\n print(f'Invalid input {player}')\n\n yn = input('Do you want to play again. Y/N: ').lower()\n if yn in ('n', 'no'):\n play = False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:44:44.373", "Id": "413416", "Score": "0", "body": "The reason for the _rps is this is a small chunk of a muck bigger piece of code. That is also why I try'd to keep it in one function, but you helped a lot so thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:48:02.417", "Id": "413417", "Score": "1", "body": "@hackerHD Even so my comment about it still holds. The only reason I can think you'd do this is if you don't have a `main` function with your main code in it. If that's the case you should make a `main` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:56:33.690", "Id": "413418", "Score": "0", "body": "Here is a link to the full ChatterBot. https://codereview.stackexchange.com/questions/213741/chatterbotv2-1-coded-in-python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:19:37.800", "Id": "413429", "Score": "0", "body": "It's worth pointing out that variables appearing only inside the function don't interfere with other variables. So the names don't need the _rps suffix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:23:17.530", "Id": "413431", "Score": "0", "body": "@AustinHastings You're correct, I'm unsure why I didn't think that was the case for global variables." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:38:02.297", "Id": "213740", "ParentId": "213738", "Score": "2" } }, { "body": "<p>Here are some extra suggestions:</p>\n\n<ol>\n<li><p>Considering that this is a piece of a much larger system, I'd suggest that you make it a class. In fact, make it two classes: the game, and the input/output mechanism. That should facilitate writing unit tests. I'm not going to assume a class for my remaining suggestions, but the point stands.</p></li>\n<li><p>As @Peilonrayz pointed out, you need some more functions. I'll suggest that you focus on creating functions for general-purpose interaction with the user. This would let you re-use those same functions in other games, other parts of your bot, etc.</p>\n\n<pre><code>player_rps = input(\"Rock, Paper, or Scissors: \").lower()\n</code></pre>\n\n<p>This is a potential bug. What happens if I don't spell my answer right, or if I enter \"Gecko\" instead? So, write a function to get a choice from the user. Allow abbreviations. Something like:</p>\n\n<pre><code>def input_choice(choices, default=None):\n \"\"\" Presents a list of choices to the user and prompts her to enter one. If \n default is not None, an empty input chooses the default. Abbreviations are\n allowed if they identify exactly one choice. Case is ignored.\n\n Returns the chosen value as it appears in the choices list (no abbreviations).\n \"\"\"\n pass\n</code></pre></li>\n<li><p>Use <code>random.choice</code> to choose a random value from a sequence. You don't need to pick a number and then index with it:</p>\n\n<pre><code>rps = [\"rock\", 'paper', 'scissors']\nplayer_rps = input(\"Rock, Paper, or Scissors: \").lower()\ncom_rps = rps[random.randint(0,3)]\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>rps = \"Rock Paper Scissors\".split()\nplayer_rps = input_choice(rps)\ncom_rps = random.choice(rps)\n</code></pre></li>\n<li><p>You can merge your data to simplify your code. There are many paragraphs that look like this:</p>\n\n<pre><code>if com_rps == 'rock' and player_rps == \"scissors\":\n print(\"Chatter Bot Wins!\")\n</code></pre>\n\n<p>This is really a 2-inputs -> 1-output function, but you can use a dictionary for this just by concatenating the inputs:</p>\n\n<pre><code>i_win = \"Chatter Bot wins!\"\nu_win = f\"{name} wins!\"\n\nwinner = {\n \"Rock:Scissors\": i_win,\n \"Scissors:Paper\": i_win,\n \"Paper:Rock\": i_win,\n \"Scissors:Rock\": u_win,\n \"Paper:Scissors\": u_win,\n \"Rock:Paper\": u_win,\n}\n\ncontest = f\"{com_rps}:{player_rps}\"\nprint(winner.get(contest, \"It's a tie!\"))\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>@Peilonrayz pointed out that tuples were a better choice than strings, and he's right. So here's a slightly different version:</p>\n\n<pre><code>winners = { ('Rock', 'Scissors'), ('Scissors', 'Paper'), ('Paper', 'Rock'), }\n\nresult = \"Chatter Bot wins!\" if (com_rps, player_rps) in winners\n else f\"{name} wins!\" if (player_rps, com_rps) in winners\n else \"It's a tie!\"\n\nprint(result)\n</code></pre></li>\n<li><p>You need more functions:</p>\n\n<pre><code>yn = input(\"Do you want to play again. Y/N: \").lower()\n\nif yn == 'n' or yn == 'no':\n play_rps = False\n</code></pre>\n\n<p>This should be a function, like:</p>\n\n<pre><code>def input_yn(prompt, default=None):\n \"\"\" Prompts the user for a yes/no answer. If default is provided, then an \n empty response will be considered that value. Returns True for yes, \n False for no.\n \"\"\"\n pass\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:16:30.117", "Id": "413448", "Score": "1", "body": "It's more standard to use tuples than strings if you need multi-key dictionaries. `(\"Rock\": \"Scissors\"): i_win`. Also if you don't ensure that both `com_rps` and `player_rps` are valid then you'll be printing \"It's a tie!\" incorrectly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:06:30.143", "Id": "413464", "Score": "0", "body": "This worked after I edited a bit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:46:29.560", "Id": "213749", "ParentId": "213738", "Score": "0" } } ]
{ "AcceptedAnswerId": "213749", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:15:09.903", "Id": "213738", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "game", "rock-paper-scissors" ], "Title": "Rock, Paper, Scissors game made in python" }
213738
<p>I'm new to python and PEP 8, so I want to see how to improve my work. This is my first big project without a guide. This is 184 lines. I think I murdered PEP 8 and need help fixing that.</p> <pre><code>import random name = "null" jokes_list = ["Why did the chicken cross the road? To get to the other side.", "The only time incorrectly isn’t spelled incorrectly is when it’s spelled incorrectly.", "I intend to live forever… or die trying.", "A blind man walks into a bar….And a table, and a chair.", "A clear conscience is usually the sign of a bad memory", "Your life.", "Why don’t you ever see hippopotamus hiding in trees? Because they’re really good at it.", "What kind of shoes do ninjas wear? Sneakers.", "Why did the lifeguard kick the elephants out of the pool? They kept dropping their trunks.", "When is a door not a door? When it's ajar.", "Why do golfers wear two pairs of pants? In case they get a hole in one."] functions = "I have many functions including help, math, settings, jokes, games, and quit." def start_up(): print("powering on...") print("Hi I'm ChatterBot.") name = input("What is your name: ") print(f"Hi {name}.") return name def help(name): print(f"What do you need help with {name}.") sub_function = input("functions or : ").lower() if sub_function == 'functions': print(functions) else: print(f"I can't help you with that {name}.") def settings(name): print ("What setting") sub_sub_function = input("name or restart: ").lower() if sub_sub_function == 'name': name = input("What should I call you then: ") if sub_sub_function == 'restart': print("Powering down...") name = "Null" current_function = "Null" sub_function = "Null" sub_sub_function = "Null" num1 = "0" num2 = "0" start_up() else: print(f"That is not on of my settings {name}.") return name def math(name): op = input("What operation|+ - / *|: ") if op == '+': num1 = input("What is the first number: ") num2 = input("What is the second number: ") answer = int(num1) + int(num2) print(f"Your answer is: {answer}") if op == '-': num1 = input("What is the first number: ") num2 = input("What is the second number: ") answer = int(num1) - int(num2) print(f"Your answer is: {answer}") if op == '*': num1 = input("What is the first number: ") num2 = input("What is the second number: ") answer = int(num1) * int(num2) print(f"Your answer is: {answer}") if op == '/': num1 = input("What is the first number: ") num2 = input("What is the second number: ") answer = int(num1) + int(num2) print(f"Your answer is: {answer}") def jokes(name = name): print(jokes_list[random.randint(0,10)]) def games(names = name): print('What game do you want to play') game = input('High Or Low or Rock Paper scissors: ').lower() if game == 'highorlow' or game == 'high or low': high_or_low() if game == 'rockpaperscissors' or game == 'rock paper scissors': rock_paper_scissors(name) def high_or_low(): print('Loading...') print('High Or Low') yn = 'Null' yn = input('Do you need me to explain the rules. Y/N: ').lower() if yn == 'y' or yn == 'yes': print('I will think of a number between 1 - 100.') print('You will guess a number and I will tell you if it is higher or lower than my number.') print('This repeats until you guess my number.') play_hol = True num = random.randint(0,101) move_count = 0 while play_hol: try: move_count += 1 guess = input("What number do you guess: ") if int(guess) == num: print(f'You won in {move_count} moves.') play_hol = False if int(guess) &gt; num: print("Lower") if int(guess) &lt; num: print("Greater") except Exception as e: print(f"Pick a number ", e) def rock_paper_scissors(name): play_rps = True while play_rps: rps = ["rock", 'paper', 'scissors'] player_rps = input("Rock, Paper, or Scissors: ").lower() com_rps = rps[random.randint(0,3)] print(com_rps) if com_rps == player_rps: print('Tie') if com_rps == 'rock' and player_rps == "scissors": print("Chatter Bot Wins!") if com_rps == 'scissors' and player_rps == "paper": print("Chatter Bot Wins!") if com_rps == 'paper' and player_rps == "rock": print("Chatter Bot Wins!") if player_rps == 'rock' and com_rps == "scissors": print(f"{name} Wins!") if player_rps == 'sicssors' and com_rps == "paper": print(f"{name} Wins!") if player_rps == 'paper' and com_rps == "rock": print(f"{name} Wins!") yn = input("Do you want to play again. Y/N: ").lower() if yn == 'n' or yn == 'no': play_rps = False name = start_up() while True: print(f"What do you want to do {name}.") print(functions) current_function = input("Functions: ").lower() if current_function == 'help': help(name) if current_function == 'settings': name = settings(name) if current_function == 'quit': print("powering down...") quit() if current_function == 'math': math(name) if current_function == 'jokes': jokes(name) if current_function == 'games': games(name) else: print(f"That is not one of my functions {name}.") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:58:50.127", "Id": "413419", "Score": "0", "body": "Someone already pointed out how to improve the rock paper scissors.https://codereview.stackexchange.com/questions/213738/rock-paper-scissors-game-made-in-python/213740?noredirect=1#comment413417_213740" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:00:27.257", "Id": "413420", "Score": "0", "body": "I'd suggest replacing the RPS code here with your improved code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:21:02.763", "Id": "413430", "Score": "0", "body": "I'm having trouble adding the rock, paper scissors fix to my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:24:07.700", "Id": "413432", "Score": "0", "body": "@Peilonrayz I'm not the one who voted to close as \"not working\", but I see that asking for suggestions about what to add next is asking for advice about code that has not yet been implemented, and that would be problematic for Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:35:04.927", "Id": "413434", "Score": "0", "body": "I fixed that and see your point @200_success." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:47:57.320", "Id": "413473", "Score": "0", "body": "Here's .2 https://codereview.stackexchange.com/questions/213761/chatterbotv2-2-coded-in-python" } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><p>When I copy/paste the code into a file locally, I have problems with Python reading the source encoding. You didn't specify an encoding, and your joke text is full of non-ascii characters.</p>\n\n<p>I'd suggest that you store your jokes in a separate file, and read in that file either at startup or each time the joke function is called.</p></li>\n<li><p>You have to ask the user's name in two places: during startup, and when changing the name in the settings. Therefore, you need a <code>get_name()</code> function to be called both places.</p></li>\n<li><p>I'm not sure what the restart operation is about. But Python uses <code>None</code> to indicate no value, so that might be better than settings things to <code>\"Null\"</code>.</p></li>\n<li><p>Your math function is bad. Write an expression parser instead. ;-)</p></li>\n<li><p>Don't catch <code>Exception</code>. It's a bad practice. Catch the specific error you intend to handle.</p></li>\n<li><p>You have a bunch of bare code at the bottom of the file. Organize that into a <code>main</code> routine, and then do:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Doing this will allow you to import the module without going into the chatterbot directly, which means you can write unit tests for the various parts of the system.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:35:55.500", "Id": "413481", "Score": "0", "body": "What is a good expression parser that I can use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:47:39.427", "Id": "413484", "Score": "0", "body": "https://codereview.stackexchange.com/questions/213769/small-expression-parser-needed-for-python-code" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:12:31.590", "Id": "213750", "ParentId": "213741", "Score": "2" } } ]
{ "AcceptedAnswerId": "213750", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:56:04.093", "Id": "213741", "Score": "0", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "ChatterBotV2.1 coded in python" }
213741
<p>I need to deserialize an XML file, without using any sort of "reflection" (or meta-programming). Instead, I need to do it via a raw object, that knows of it's structure and can properly identify and deserialize itself.</p> <p>In this case, I have an XML file that looks like the following:</p> <pre><code>&lt;Test&gt; &lt;Item&gt; &lt;Group&gt; &lt;SubGroup test4="2018-09-01" test5="Y"&gt; &lt;/SubGroup&gt; &lt;/Group&gt; &lt;/Item&gt; &lt;Item&gt; &lt;Group&gt; &lt;SubGroup test="0" test2="t"&gt; &lt;/SubGroup&gt; &lt;SubGroup test3="0.0"&gt; &lt;/SubGroup&gt; &lt;/Group&gt; &lt;/Item&gt; &lt;/Test&gt; </code></pre> <p>And I have the following serialization classes:</p> <p><code>UtilityMethods.java</code>:</p> <pre><code>import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class UtilityMethods { public static byte getInt8(String input) { if (input == null || input.equals("")) { return 0; } else { return Byte.parseByte(input); } } public static short getInt16(String input) { if (input == null || input.equals("")) { return 0; } else { return Short.parseShort(input); } } public static int getInt32(String input) { if (input == null || input.equals("")) { return 0; } else { return Integer.parseInt(input); } } public static long getInt64(String input) { if (input == null || input.equals("")) { return 0L; } else { return Long.parseLong(input); } } public static Date getDate(String input) throws ParseException { if (input == null || input.equals("")) { return new Date(); } else { return new SimpleDateFormat("yyyy-MM-dd").parse(input); } } public static double getDouble(String input) { if (input == null || input.equals("")) { return 0.0; } else { return Double.parseDouble(input); } } public static boolean getBoolean(String input) { if (input == null || input.equals("")) { return false; } else { return (input.equals("y") ? true : input.equals("yes") ? true : false); } } public static ArrayList&lt;Node&gt; getNodesByTagName(Node rootNode, String tagName) { ArrayList&lt;Node&gt; result = new ArrayList&lt;&gt;(); NodeList subNodes = rootNode.getChildNodes(); for (int i = 0; i &lt; subNodes.getLength(); i++) { if (subNodes.item(i).getNodeName().equals(tagName)) { result.add(subNodes.item(i)); } } return result; } public static String getAttrValue(Node attr) { if (attr == null) { return null; } else { return attr.getNodeValue(); } } } </code></pre> <p><code>SubGroup.java</code>:</p> <pre><code>import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; public class SubGroup { private Date _test4; public Date get_test4() { return _test4; } public void set_test4(Date test4) { _test4 = test4; } private boolean _test5; public boolean get_test5() { return _test5; } public void set_test5(boolean test5) { _test5 = test5; } private String __Text; public String get__Text() { return __Text; } public void set__Text(String _Text) { __Text = _Text; } private String _test2; public String get_test2() { return _test2; } public void set_test2(String test2) { _test2 = test2; } private byte _test; public byte get_test() { return _test; } public void set_test(byte test) { _test = test; } private double _test3; public double get_test3() { return _test3; } public void set_test3(double test3) { _test3 = test3; } public void deserialize(String xml) throws ParserConfigurationException, IOException, SAXException, ParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes("utf-8"))); Element root = doc.getDocumentElement(); deserialize(doc.getElementsByTagName("SubGroup").item(0)); } public void deserialize(Node myNode) throws ParseException { NodeList nodes; _test4 = UtilityMethods.getDate(UtilityMethods.getAttrValue(myNode.getAttributes().getNamedItem("test4"))); _test5 = UtilityMethods.getBoolean(UtilityMethods.getAttrValue(myNode.getAttributes().getNamedItem("test5"))); __Text = myNode.getTextContent(); _test2 = UtilityMethods.getAttrValue(myNode.getAttributes().getNamedItem("test2")); _test = UtilityMethods.getInt8(UtilityMethods.getAttrValue(myNode.getAttributes().getNamedItem("test"))); _test3 = UtilityMethods.getDouble(UtilityMethods.getAttrValue(myNode.getAttributes().getNamedItem("test3"))); } } </code></pre> <p><code>Group.java</code>:</p> <pre><code>import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; public class Group { private ArrayList&lt;SubGroup&gt; _subGroup; public ArrayList&lt;SubGroup&gt; get_subGroup() { return _subGroup; } public void set_subGroup(ArrayList&lt;SubGroup&gt; subGroup) { _subGroup = subGroup; } public void deserialize(String xml) throws ParserConfigurationException, IOException, SAXException, ParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes("utf-8"))); Element root = doc.getDocumentElement(); deserialize(doc.getElementsByTagName("Group").item(0)); } public void deserialize(Node myNode) throws ParseException { NodeList nodes; _subGroup = new ArrayList&lt;&gt;(); for (Node node : UtilityMethods.getNodesByTagName(myNode, "SubGroup")) { SubGroup item; item = new SubGroup(); item.deserialize(node); _subGroup.add(item); } } } </code></pre> <p><code>Item.java</code>:</p> <pre><code>import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; public class Item { private Group _group; public Group get_group() { return _group; } public void set_group(Group group) { _group = group; } public void deserialize(String xml) throws ParserConfigurationException, IOException, SAXException, ParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes("utf-8"))); Element root = doc.getDocumentElement(); deserialize(doc.getElementsByTagName("Item").item(0)); } public void deserialize(Node myNode) throws ParseException { NodeList nodes; _group = new Group(); _group.deserialize(UtilityMethods.getNodesByTagName(myNode, "Group").get(0)); } } </code></pre> <p><code>Test.java</code>:</p> <pre><code>import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; public class Test { private ArrayList&lt;Item&gt; _item; public ArrayList&lt;Item&gt; get_item() { return _item; } public void set_item(ArrayList&lt;Item&gt; item) { _item = item; } public void deserialize(String xml) throws ParserConfigurationException, IOException, SAXException, ParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes("utf-8"))); Element root = doc.getDocumentElement(); deserialize(doc.getElementsByTagName("Test").item(0)); } public void deserialize(Node myNode) throws ParseException { NodeList nodes; _item = new ArrayList&lt;&gt;(); for (Node node : UtilityMethods.getNodesByTagName(myNode, "Item")) { Item item; item = new Item(); item.deserialize(node); _item.add(item); } } } </code></pre> <p>Here, the <code>Test</code> class should be able to accept the entire XML string, or a node pointing to the start of the <code>&lt;Test&gt;</code> node, that it can then use to deserialize into itself.</p> <p>Another note is that this assumes the XML is well-formed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T14:53:47.220", "Id": "413992", "Score": "0", "body": "\"that knows of it's structure and can properly identify and deserialize itself.\" Why? Sounds very arbitrary." } ]
[ { "body": "<p>Quick skim simplifications:</p>\n\n<ul>\n<li><p>The way you return in <code>UtilityMethods</code> allows you to not use an explicit <code>else</code>-block. e.g. for <code>getInt8</code>:</p>\n\n<pre><code>if (input == null || input.equals(\"\")) {\n return 0;\n}\nreturn Byte.parseByte(input);\n</code></pre></li>\n<li><p>the return statement for <code>getBoolean</code> should make you stumble. Instead of a nested ternary, use a simple or:</p>\n\n<pre><code>return input.equals(\"y\") || input.equals(\"yes\");\n</code></pre>\n\n<p>Note that you're currently assuming the value will always be lowers-case. That may not be true :)</p></li>\n<li><p><code>getNodesByTagName</code> is a bit of a misnomer. You're only searching through the child nodes themselves. As such, this could be more easily expressed in a stream using <code>filter</code>, if only NodeList was <code>Iterable</code> (<em>~sigh</em>). As it stands, the only thing I would advise is to return a <code>List</code> instead of an <code>ArrayList</code> (program against interfaces), as well as a rename to something like <code>childrenWithTagName</code> or something like that.</p>\n\n<p>If you wanted to search through the whole document tree below the root node, you may want to look into <code>XPath</code> instead.</p></li>\n<li><p><code>getAttrValue</code> is a bit of a misnomer as well. Nodes in an xml-document have attributes which have values. Those attributes are only defined on <code>Element</code>s. The nodeValue is but one possible attribute of an element, in theory any element can contain any number of attributes.</p>\n\n<p>As it stands this method is a thin wrapper over <code>getNodeValue</code> that allows you to avoid null pointers.</p></li>\n<li><p>Generally speaking: use <code>List</code> over <code>ArrayList</code> in declarations,</p></li>\n</ul>\n\n<hr>\n\n<p>I personally don't very much like the way you named the fields in your class, but I assume that this has some very good reason and at least you're being consistent about it :)<br>\nI just wanted to get that off my chest and with that, I'm done.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:56:36.747", "Id": "213907", "ParentId": "213743", "Score": "1" } } ]
{ "AcceptedAnswerId": "213907", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:05:55.900", "Id": "213743", "Score": "4", "Tags": [ "java", "xml", "serialization", "meta-programming" ], "Title": "Deserializing an XML Object without Reflection / Meta-Programming" }
213743
<p>I'm beginning to learn WPF and wanted to do a quick exercise. The code is as simple as it gets but I tried to evaluate each and every possible edge case. Any improvement is welcome, thanks.</p> <p><strong>C#:</strong></p> <pre><code>using System; using System.Globalization; using System.Windows; using System.Windows.Controls; namespace Calculator { /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : Window { double firstNumber, secondNumber, resultNumber = 0; bool calcDone = false; Operations operation = Operations.None; string separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; public MainWindow() { InitializeComponent(); //Assign to the decimal button the separator from the current culture dec.Content = separator; } //List the possible numeric operations private enum Operations { None, Division, Multiplication, Subtraction, Sum } //Manage number buttons input private void NumberButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; if (calcDone) //calculation already done { result.Content = $"{button.Content}"; calcDone = false; } else //calculation not yet done { if (result.Content.ToString() == "0") { result.Content = $"{button.Content}"; } else { result.Content = $"{result.Content}{button.Content}"; } } } //Manage operation buttons input private void OperationButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; //Evaluate button pressed switch (button.Content.ToString()) { case "AC": result.Content = "0"; break; case "+/-": if (!(result.Content.ToString() == "0")) { result.Content = Convert.ToDouble(result.Content) * -1; } break; case "%": if (!(result.Content.ToString() == "0")) { result.Content = Convert.ToDouble(result.Content) / 100; } break; case "÷": firstNumber = Convert.ToDouble(result.Content); operation = Operations.Division; result.Content = "0"; break; case "×": firstNumber = Convert.ToDouble(result.Content); operation = Operations.Multiplication; result.Content = "0"; break; case "-": firstNumber = Convert.ToDouble(result.Content); operation = Operations.Subtraction; result.Content = "0"; break; case "+": firstNumber = Convert.ToDouble(result.Content); operation = Operations.Sum; result.Content = "0"; break; case "=": switch (operation) { case Operations.Division: if (calcDone) { if (!(result.Content.ToString() == "ERROR")) { result.Content = Convert.ToDouble(result.Content) / secondNumber; } } else { //Check if division by 0 if (result.Content.ToString() == "0") { result.Content = "ERROR"; calcDone = true; } else { secondNumber = Convert.ToDouble(result.Content); resultNumber = firstNumber / secondNumber; result.Content = resultNumber; calcDone = true; } } break; case Operations.Multiplication: if (calcDone) { result.Content = Convert.ToDouble(result.Content) * secondNumber; } else { secondNumber = Convert.ToDouble(result.Content); resultNumber = firstNumber * secondNumber; result.Content = resultNumber; calcDone = true; } break; case Operations.Subtraction: if (calcDone) { result.Content = Convert.ToDouble(result.Content) - secondNumber; } else { secondNumber = Convert.ToDouble(result.Content); resultNumber = firstNumber - secondNumber; result.Content = resultNumber; calcDone = true; } break; case Operations.Sum: if (calcDone) { result.Content = Convert.ToDouble(result.Content) + secondNumber; } else { secondNumber = Convert.ToDouble(result.Content); MessageBox.Show($"{firstNumber} + {secondNumber}"); resultNumber = firstNumber + secondNumber; result.Content = resultNumber; calcDone = true; } break; } break; default: if (!result.Content.ToString().Contains(separator)) { result.Content = $"{result.Content}{button.Content}"; } break; } } } } </code></pre> <p><strong>XAML:</strong></p> <pre><code>&lt;Window x:Class="Calculator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Calculator" mc:Ignorable="d" Title="MainWindow" Height="500" Width="300"&gt; &lt;Grid Margin="8"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="1.5*"/&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Label x:Name="result" Content="0" Grid.ColumnSpan="4" HorizontalAlignment="Right" VerticalAlignment="Bottom" FontSize="50"/&gt; &lt;Button Content="AC" Margin="2" Grid.Column="0" Grid.Row="1" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="+/-" Margin="2" Grid.Column="1" Grid.Row="1" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="%" Margin="2" Grid.Column="2" Grid.Row="1" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="÷" Margin="2" Grid.Column="3" Grid.Row="1" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="7" Margin="2" Grid.Column="0" Grid.Row="2" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="8" Margin="2" Grid.Column="1" Grid.Row="2" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="9" Margin="2" Grid.Column="2" Grid.Row="2" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="×" Margin="2" Grid.Column="3" Grid.Row="2" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="4" Margin="2" Grid.Column="0" Grid.Row="3" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="5" Margin="2" Grid.Column="1" Grid.Row="3" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="6" Margin="2" Grid.Column="2" Grid.Row="3" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="-" Margin="2" Grid.Column="3" Grid.Row="3" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="1" Margin="2" Grid.Column="0" Grid.Row="4" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="2" Margin="2" Grid.Column="1" Grid.Row="4" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="3" Margin="2" Grid.Column="2" Grid.Row="4" FontSize="20" Click="NumberButton_Click"/&gt; &lt;Button Content="+" Margin="2" Grid.Column="3" Grid.Row="4" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="0" Margin="2" Grid.Column="0" Grid.Row="5" FontSize="20" Grid.ColumnSpan="2" Click="NumberButton_Click"/&gt; &lt;Button x:Name="dec" Content="" Margin="2" Grid.Column="2" Grid.Row="5" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;Button Content="=" Margin="2" Grid.Column="3" Grid.Row="5" FontWeight="bold" Click="OperationButton_Click"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:54:25.863", "Id": "413441", "Score": "3", "body": "Welcome to CodeReview. Could you please post the XAML part, so that the code is complete?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:15:36.197", "Id": "413447", "Score": "0", "body": "Sure! Didn't think about adding it because it's extremely simple but for completeness sake I'm adding it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T21:19:22.147", "Id": "413462", "Score": "2", "body": "Even if it's extremely simple, having this code readily available allows us to copy and paste it into our IDE and try running your program, to see whether the improvements we're going to suggest really work. As a result, you get better quality reviews. :)" } ]
[ { "body": "<ul>\n<li>It's common to write down access modifier for fields</li>\n<li>Defining one field per line makes the code more readable because you dont have to scan each declaration line for multiple variables</li>\n<li><p>Initialization of integers with '0' is not required because '0' is its default.</p>\n\n<pre><code> private double firstNumber;\n private double secondNumber;\n private double resultNumber;\n private bool calcDone = false;\n private Operations operation = Operations.None;\n private string separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;\n</code></pre></li>\n</ul>\n\n<hr>\n\n<blockquote>\n<pre><code>result.Content = $\"{button.Content}\";\n</code></pre>\n</blockquote>\n\n<p>can be simplified by</p>\n\n<pre><code>result.Content = button.Content;\n</code></pre>\n\n<hr>\n\n<p>There are multiple occurences of <code>result.Content.ToString() == \"0\"</code>. Maybe it makes sense to put it in a property and use the the property instead:</p>\n\n<pre><code>private bool IsInputEmpty =&gt; result.Equals(\"0\");\n</code></pre>\n\n<hr>\n\n<p><strong>Using MVVM</strong></p>\n\n<p>In WPF it is common to prefer <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel\" rel=\"noreferrer\">MVVM</a> over code behind. It is nonessential for such an simple application like a calculator - But for pracice it would be a nice exercise to convert it to MMVM using <a href=\"https://www.codeproject.com/Articles/238657/How-to-use-Commands-in-WPF-2\" rel=\"noreferrer\">commands and data binding</a>.</p>\n\n<hr>\n\n<p><strong>Use OOP to abstract your logic and separate state</strong></p>\n\n<p>Your solution consists of big nested switch statements and global state (firstNumber, secondNumber, resultNumber, calcDone, operation). That kind of solutions are really hard to maintain because each case of the switch has access to the whole state, some cases require a defined state and it is not clear what are the transisions from one state to another.</p>\n\n<p>It is better to think about more abstract concepts and try to design them via the power of object oriented programming ;). Actually there are many patterns that have proven themselves.. In your case I would check the <a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"noreferrer\">State Pattern</a></p>\n\n<p>For the caluclator, meaningful stats may be</p>\n\n<ul>\n<li>EmtpyInput</li>\n<li>OneNumberEntered</li>\n<li>OneNumberAndOperatorEntered</li>\n<li>ResultShown</li>\n</ul>\n\n<p>properties / behavior of states:</p>\n\n<ul>\n<li>There is <strong>only one active state</strong> (the initial state is EmptyInput)</li>\n<li>Each state has only the required attributes (e.g. EmptyInput has no attributes, OneNumberEntered has the entered number as attribute).</li>\n<li>Each state can not be created without the attributes it needs. Therefore it is not possible to create invalid states</li>\n<li>Each state can say which input can be handled and which not (e.g. corresponding buttons can be disabled)</li>\n<li>Each state can change the active state.</li>\n</ul>\n\n<p>A simple impl. could look like:</p>\n\n<pre><code>public interface IContext\n{\n void ChangeState(State state);\n}\n\npublic abstract class State\n{\n public State(IContext context)\n {\n this.Context = context;\n }\n\n protected IContext Context { get; }\n\n public abstract void HandleInput(string input);\n\n public abstract bool CanHandleInput(string input);\n}\n\npublic class EmptyInput : State\n{\n public EmptyInput(IContext context) : base(context)\n {}\n\n public override bool CanHandleInput(string input) =&gt; \"0123456789\".Contains(input);\n\n public override void HandleInput(string input)\n {\n this.Context.ChangeState(new OneNumberEntered(context, input));\n }\n}\n</code></pre>\n\n<p>The ViewModel or the MainWindow should implement the IContext interface, hold the active state and pass all input to the active state. That approach is understandable and maintainable because the complexity has been separated in different simple states and the problem of \"handling input\" can be handled for each state with the corresponding context information separatly.\n ....</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T07:07:14.417", "Id": "213938", "ParentId": "213745", "Score": "6" } }, { "body": "<p>Inspired by JanDotNet's answer, I have made an attempt at improving the OP's code using best practices. I am using both the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel\" rel=\"nofollow noreferrer\">M-V-VM</a> and <a href=\"https://en.wikipedia.org/wiki/Finite-state_machine\" rel=\"nofollow noreferrer\">State Machine</a> pattern.</p>\n\n<p><strong>View</strong></p>\n\n<p>The calculator view is no longer a part of <code>MainWindow</code>.</p>\n\n<p><em>MainWindow</em></p>\n\n<pre><code>&lt;Window x:Class=\"Calculator.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:view=\"clr-namespace:Calculator.Views\"\n Title=\"Calculator\" Height=\"500\" Width=\"300\"&gt;\n &lt;Grid&gt;\n &lt;view:CalculatorView /&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p><em>CalculatorView</em></p>\n\n<p>Styles, commands, command parameters are refactored into best practices. Styles are moved into <a href=\"https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/resourcedictionary-and-xaml-resource-references\" rel=\"nofollow noreferrer\">resource dictionaries</a>. Commands are plumbed with the command pattern of <a href=\"https://docs.telerik.com/data-access/quick-start-scenarios/wpf/quickstart-wpf-viewmodelbase-and-relaycommand\" rel=\"nofollow noreferrer\">Telerik</a>. Command parameters are type-casted for convenience in order for the view model and model not to parse strings.</p>\n\n<pre><code>&lt;UserControl x:Class=\"Calculator.Views.CalculatorView\"\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 xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:view=\"clr-namespace:Calculator.Views\"\n xmlns:viewModel=\"clr-namespace:Calculator.ViewModels\"\n xmlns:model=\"clr-namespace:Calculator.Models\"\n mc:Ignorable=\"d\" \n d:DesignHeight=\"500\" d:DesignWidth=\"300\"&gt;\n &lt;Grid Margin=\"8\"&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition/&gt;\n &lt;ColumnDefinition/&gt;\n &lt;ColumnDefinition/&gt;\n &lt;ColumnDefinition/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"1.5*\"/&gt;\n &lt;RowDefinition/&gt;\n &lt;RowDefinition/&gt;\n &lt;RowDefinition/&gt;\n &lt;RowDefinition/&gt;\n &lt;RowDefinition/&gt;\n &lt;/Grid.RowDefinitions&gt;\n\n &lt;Label x:Name=\"result\" Content=\"0\" Grid.ColumnSpan=\"4\" HorizontalAlignment=\"Right\" VerticalAlignment=\"Bottom\" FontSize=\"50\"/&gt;\n\n &lt;Button Content=\"AC\" Grid.Column=\"0\" Grid.Row=\"1\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.ClearAll}\" /&gt;\n &lt;Button Content=\"+/-\" Grid.Column=\"1\" Grid.Row=\"1\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Negate}\" /&gt;\n &lt;Button Content=\"%\" Grid.Column=\"2\" Grid.Row=\"1\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Modulo}\" /&gt;\n &lt;Button Content=\"÷\" Grid.Column=\"3\" Grid.Row=\"1\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Divide}\" /&gt;\n\n &lt;Button Content=\"7\" Grid.Column=\"0\" Grid.Row=\"2\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"7\" /&gt;\n &lt;Button Content=\"8\" Grid.Column=\"1\" Grid.Row=\"2\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"8\" /&gt;\n &lt;Button Content=\"9\" Grid.Column=\"2\" Grid.Row=\"2\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"9\" /&gt;\n &lt;Button Content=\"×\" Grid.Column=\"3\" Grid.Row=\"2\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Multiply}\" /&gt;\n\n &lt;Button Content=\"4\" Grid.Column=\"0\" Grid.Row=\"3\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"4\" /&gt;\n &lt;Button Content=\"5\" Grid.Column=\"1\" Grid.Row=\"3\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"5\" /&gt;\n &lt;Button Content=\"6\" Grid.Column=\"2\" Grid.Row=\"3\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"6\" /&gt;\n &lt;Button Content=\"-\" Grid.Column=\"3\" Grid.Row=\"3\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Subtract}\" /&gt;\n\n &lt;Button Content=\"1\" Grid.Column=\"0\" Grid.Row=\"4\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"1\" /&gt;\n &lt;Button Content=\"2\" Grid.Column=\"1\" Grid.Row=\"4\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"2\" /&gt;\n &lt;Button Content=\"3\" Grid.Column=\"2\" Grid.Row=\"4\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"3\" /&gt;\n &lt;Button Content=\"+\" Grid.Column=\"3\" Grid.Row=\"4\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Add}\" /&gt;\n\n &lt;Button Content=\"0\" Grid.Column=\"0\" Grid.Row=\"5\" Grid.ColumnSpan=\"2\"\n Style=\"{StaticResource NumericButton}\" Command=\"{Binding NumericCommand}\" \n CommandParameter=\"0\" /&gt;\n &lt;Button x:Name=\"dec\" Content=\".\" Grid.Column=\"2\" Grid.Row=\"5\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.DecimalSeperator}\" /&gt;\n &lt;Button Content=\"=\" Grid.Column=\"3\" Grid.Row=\"5\"\n Style=\"{StaticResource OperationButton}\" Command=\"{Binding OperationCommand}\" \n CommandParameter=\"{x:Static model:Operation.Equals}\" /&gt;\n &lt;/Grid&gt;\n&lt;/UserControl&gt;\n</code></pre>\n\n<p><em>CalculatorView (code-behind)</em></p>\n\n<p>This is the entrypoint for plumbing the view model and model to the view. The view model attaches itself as <code>Datacontext</code> on the view (inside constructor of the view model). </p>\n\n<pre><code>public partial class CalculatorView : UserControl, ICalculatorView\n {\n private CalculatorViewModel viewModel;\n\n public CalculatorView() {\n InitializeComponent();\n this.viewModel = new CalculatorViewModel(this, new SimpleCalculator());\n }\n\n public void Display(string value) {\n result.Content = value;\n }\n }\n</code></pre>\n\n<p><strong>ViewModel</strong></p>\n\n<p>The view model is responsible for dispatching user events to the model and displaying evaluated data from the model to the view.</p>\n\n<p><em>CalculatorViewModel</em></p>\n\n<pre><code>public class CalculatorViewModel : ViewModelBase&lt;ICalculatorView&gt;\n {\n private ICommand operationCommand;\n private ICommand numericCommand;\n private ICalculator calculator;\n\n public CalculatorViewModel(ICalculatorView view, ICalculator calculator)\n : base(view) \n {\n Guard.NotNull(calculator);\n this.calculator = calculator;\n }\n\n protected virtual void OnOperationCommand(Operation operation) {\n calculator.HandleOperationEvent(operation);\n View.Display(calculator.CurrentToken);\n }\n\n protected virtual void OnNumericCommand(int digit) {\n calculator.HandleNumericEvent(digit);\n View.Display(calculator.CurrentToken);\n }\n\n public ICommand OperationCommand {\n get {\n return this.operationCommand ?? (this.operationCommand\n = new RelayCommand&lt;Operation&gt;(this.OnOperationCommand));\n }\n }\n\n public ICommand NumericCommand {\n get {\n return this.numericCommand ?? (this.numericCommand\n = new RelayCommand&lt;int&gt;(this.OnNumericCommand));\n }\n }\n }\n</code></pre>\n\n<p><strong>Model</strong></p>\n\n<p>The model is a simple calculator that uses states to process user input. Note that this part is the most complex and could still get improved:</p>\n\n<ul>\n<li>error handling (perhaps an error state)</li>\n<li>unit tests (state machines tend to have alot of edge cases!)</li>\n</ul>\n\n<p><em>SimpleCalculator</em></p>\n\n<pre><code> /// &lt;remarks&gt;\n /// Implemented as a simple subset of an UML state machine: https://en.wikipedia.org/wiki/UML_state_machine\n /// with event processing, extended state and mealy/moore operations.\n /// &lt;/remarks&gt;\n public class SimpleCalculator : ICalculator\n {\n public SimpleCalculator() {\n Transition(new InitialState(this));\n }\n\n #region Event Processing\n\n public void HandleOperationEvent(Operation operation) {\n state.HandleOperationEvent(operation);\n }\n\n public void HandleNumericEvent(int digit) {\n state.HandleNumericEvent(digit);\n }\n\n public Operation DeferredOperation { get; internal set; }\n\n #endregion\n\n #region Extended State\n\n // only important if you want to send the evaluated result to some other API\n public decimal Result {\n get;\n internal set;\n }\n\n // this is what will be outputted on the view after each user input event\n public string CurrentToken {\n get;\n internal set;\n }\n\n #endregion\n\n #region State Machine\n\n private State state;\n\n internal void Transition(State newState) {\n Guard.NotNull(newState);\n if (state != null)\n state.Exit();\n state = newState;\n state.Enter();\n }\n\n protected decimal CurrentResult {\n get {\n return string.IsNullOrEmpty(CurrentToken) ? 0m\n : decimal.Parse(CurrentToken.EndsWith(State.DecimalSeperator) \n ? CurrentToken.Substring(0, CurrentToken.Length - 1) : CurrentToken,\n State.Formatter);\n }\n }\n\n protected void Negate() {\n if (CurrentResult != 0) {\n if (CurrentToken.StartsWith(State.NegateSymbol)) {\n CurrentToken = CurrentToken.Substring(1);\n }\n else {\n CurrentToken = State.NegateSymbol + CurrentToken;\n }\n }\n }\n\n protected void HandleDeferredOperation() {\n switch (DeferredOperation) {\n case Operation.Add:\n Result += CurrentResult;\n break;\n case Operation.Subtract:\n Result -= CurrentResult;\n break;\n case Operation.Multiply:\n Result *= CurrentResult;\n break;\n case Operation.Divide:\n Result /= CurrentResult;\n break;\n case Operation.Modulo:\n Result %= CurrentResult;\n break;\n default:\n break;\n }\n Result = Math.Round(Result, 8);\n DeferredOperation = Operation.None;\n CurrentToken = Result.ToString(State.Formatter);\n }\n\n internal abstract class State\n {\n protected SimpleCalculator context;\n internal const string DecimalSeperator = \".\";\n internal const string NegateSymbol = \"-\";\n internal readonly static IFormatProvider Formatter = new CultureInfo(\"en-US\", false);\n\n protected internal State(SimpleCalculator context) {\n Guard.NotNull(context);\n this.context = context;\n }\n\n protected void ChangeState(State newState) {\n context.Transition(newState);\n }\n\n protected void ChangeToDecimalInputState(Operation operation) {\n var decimalState = new DecimalInputState(context);\n ChangeState(decimalState);\n decimalState.HandleOperationEvent(operation);\n }\n\n protected void ChangeToNumericInputState(int digit) {\n var newState = new NumericInputState(context);\n ChangeState(newState);\n newState.HandleNumericEvent(digit);\n }\n\n protected void ChangeToBinaryOperationState(Operation operation) {\n var binaryState = new BinaryOperationState(context);\n ChangeState(binaryState);\n binaryState.HandleOperationEvent(operation);\n }\n\n internal virtual bool HandleOperationEvent(Operation operation) \n {\n switch (operation) {\n case Operation.ClearAll:\n ChangeState(new InitialState(context));\n return true;\n case Operation.Equals:\n ChangeState(new EqualState(context));\n return true;\n case Operation.DecimalSeperator:\n ChangeToDecimalInputState(operation);\n return true;\n case Operation.Add:\n case Operation.Subtract:\n case Operation.Multiply:\n case Operation.Divide:\n case Operation.Modulo:\n ChangeToBinaryOperationState(operation);\n return true;\n case Operation.Negate:\n context.Negate();\n return true;\n }\n\n return false;\n }\n\n internal virtual bool HandleNumericEvent(int digit) {\n this.ChangeToNumericInputState(digit);\n return true; \n }\n\n internal virtual void Enter() {}\n internal virtual void Exit() { }\n }\n\n internal sealed class InitialState : State\n {\n internal InitialState(SimpleCalculator context)\n : base(context) {\n }\n\n internal override bool HandleOperationEvent(Operation operation) {\n switch (operation) {\n case Operation.ClearAll:\n // let's stay in the current state, rather then triggering an\n // external self transition\n return true;\n default:\n return base.HandleOperationEvent(operation);\n }\n }\n\n internal override void Enter() {\n context.Result = 0m;\n context.CurrentToken = string.Empty;\n context.DeferredOperation = Operation.None;\n }\n }\n\n private sealed class EqualState : State\n {\n internal EqualState(SimpleCalculator context)\n : base(context) {\n }\n\n internal override void Enter() {\n context.HandleDeferredOperation();\n }\n\n internal override bool HandleOperationEvent(Operation operation) {\n switch (operation) {\n case Operation.Negate:\n // ignore\n return true;\n default:\n return base.HandleOperationEvent(operation);\n }\n }\n }\n\n internal sealed class DecimalInputState : State\n {\n internal DecimalInputState(SimpleCalculator context)\n : base(context) {\n }\n\n internal override bool HandleOperationEvent(Operation operation) {\n switch (operation) {\n case Operation.DecimalSeperator:\n // ignore attempt to set another decimal seperator\n if (!string.IsNullOrEmpty(context.CurrentToken)\n &amp;&amp; !context.CurrentToken.Contains(State.DecimalSeperator)) \n {\n context.CurrentToken += State.DecimalSeperator;\n }\n return true;\n default:\n return base.HandleOperationEvent(operation);\n }\n }\n\n internal override bool HandleNumericEvent(int digit) {\n if (context.CurrentResult == 0) {\n // only output the decimal seperator once a number event is received\n context.CurrentToken = \"0\";\n }\n if (!context.CurrentToken.Contains(State.DecimalSeperator)) {\n context.CurrentToken += State.DecimalSeperator;\n }\n // append the digit to the current token\n context.CurrentToken += digit.ToString();\n return true;\n }\n\n internal override void Enter() {\n context.CurrentToken = string.Empty;\n base.Enter();\n }\n\n internal override void Exit() {\n if (context.DeferredOperation == Operation.None) {\n context.Result = 0m;\n context.DeferredOperation = Operation.Add;\n }\n }\n }\n\n private sealed class NumericInputState : State\n {\n internal NumericInputState(SimpleCalculator context)\n : base(context) {\n }\n\n internal override bool HandleNumericEvent(int digit) {\n if (context.CurrentResult == 0 &amp;&amp; digit == 0) {\n // ignore 0 as prepend\n return true;\n }\n // append the digit to the current token\n context.CurrentToken += digit.ToString();\n return true;\n }\n\n internal override void Enter() {\n context.CurrentToken = string.Empty;\n base.Enter();\n }\n\n internal override void Exit() {\n if (context.DeferredOperation == Operation.None) {\n context.Result = 0m;\n context.DeferredOperation = Operation.Add;\n }\n }\n }\n\n private sealed class BinaryOperationState : State\n {\n internal BinaryOperationState(SimpleCalculator context)\n : base(context) {\n }\n\n internal override void Enter() {\n context.HandleDeferredOperation();\n }\n\n internal override bool HandleOperationEvent(Operation operation) {\n switch (operation) {\n case Operation.Negate:\n // ignore\n return true;\n case Operation.Add:\n case Operation.Subtract:\n case Operation.Multiply:\n case Operation.Divide:\n case Operation.Modulo:\n // store the deferred event\n context.DeferredOperation = operation;\n return true;\n default:\n return base.HandleOperationEvent(operation);\n }\n }\n }\n\n #endregion\n }\n</code></pre>\n\n<p><strong>Infrastructure</strong></p>\n\n<p>An appendix of other classes and resources used.</p>\n\n<pre><code>public enum Operation\n {\n None,\n ClearAll,\n Negate,\n Modulo,\n Divide,\n Multiply,\n Subtract,\n Add,\n DecimalSeperator,\n Equals,\n }\n\npublic interface ICalculator\n {\n void HandleOperationEvent(Operation operation);\n void HandleNumericEvent(int digit);\n decimal Result { get; }\n string CurrentToken { get; }\n }\n\npublic interface ICalculatorViewModel\n {\n ICalculatorView View { get; }\n }\n\npublic interface ICalculatorView : IView\n {\n void Display(string value);\n }\n\npublic interface IViewModel : INotifyPropertyChanged, IDisposable\n {\n IView View { get; }\n }\n\npublic interface IViewModel&lt;TView&gt; : IViewModel where TView : IView\n {\n new TView View { get; }\n }\n\npublic interface IView\n {\n object DataContext { get; set; }\n }\n\npublic abstract class ViewModelBase&lt;TView&gt; : IViewModel&lt;TView&gt;\n where TView : IView\n {\n public event PropertyChangedEventHandler PropertyChanged;\n private readonly TView view;\n\n public TView View {\n get {\n return this.view;\n }\n }\n\n protected ViewModelBase(TView view) {\n Guard.NotNull(view);\n this.view = view;\n this.View.DataContext = this;\n }\n\n protected virtual void RaisePropertyChanged(string propertyName) {\n var handler = this.PropertyChanged;\n if (handler != null) {\n handler(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n IView IViewModel.View {\n get { return View; }\n }\n\n ~ViewModelBase() {\n Dispose(false);\n }\n\n public void Dispose() {\n Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing) {\n if (disposing) {\n this.PropertyChanged = null;\n }\n }\n }\n\npublic class RelayCommand : ICommand\n {\n public event EventHandler CanExecuteChanged {\n add { \n CommandManager.RequerySuggested += value;\n }\n remove { \n CommandManager.RequerySuggested -= value; \n }\n }\n\n private Action methodToExecute;\n private Func&lt;bool&gt; canExecuteEvaluator;\n\n public RelayCommand(Action methodToExecute, Func&lt;bool&gt; canExecuteEvaluator) {\n Guard.NotNull(methodToExecute);\n this.methodToExecute = methodToExecute;\n this.canExecuteEvaluator = canExecuteEvaluator;\n }\n\n public RelayCommand(Action methodToExecute)\n : this(methodToExecute, null) {\n }\n\n public bool CanExecute(object parameter) {\n return this.canExecuteEvaluator == null || this.canExecuteEvaluator.Invoke();\n }\n\n public void Execute(object parameter) {\n this.methodToExecute.Invoke();\n }\n }\n\n public class RelayCommand&lt;TParameter&gt; : ICommand\n {\n public event EventHandler CanExecuteChanged {\n add {\n CommandManager.RequerySuggested += value;\n }\n remove {\n CommandManager.RequerySuggested -= value;\n }\n }\n\n private Action&lt;TParameter&gt; methodToExecute;\n private Func&lt;TParameter, bool&gt; canExecuteEvaluator;\n\n public RelayCommand(Action&lt;TParameter&gt; methodToExecute, Func&lt;TParameter, bool&gt; canExecuteEvaluator) {\n Guard.NotNull(methodToExecute);\n this.methodToExecute = methodToExecute;\n this.canExecuteEvaluator = canExecuteEvaluator;\n }\n\n public RelayCommand(Action&lt;TParameter&gt; methodToExecute)\n : this(methodToExecute, null) {\n }\n\n private TParameter ConvertType(object parameter) {\n return parameter == null ? default(TParameter) \n : (TParameter)Convert.ChangeType(parameter, typeof(TParameter));\n }\n\n public bool CanExecute(object parameter) {\n return this.canExecuteEvaluator == null\n || this.canExecuteEvaluator.Invoke(ConvertType(parameter));\n }\n\n public void Execute(object parameter) {\n this.methodToExecute.Invoke(ConvertType(parameter));\n }\n }\n\ninternal static class Guard\n {\n [DebuggerStepThrough]\n public static void NotNull(object value) {\n if (value == null) {\n throw new ArgumentNullException(\"The value must be set.\");\n }\n }\n }\n\nAppResources.xaml -&gt;\n\n&lt;ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;ResourceDictionary.MergedDictionaries&gt;\n &lt;ResourceDictionary Source=\"Style.xaml\" /&gt;\n &lt;/ResourceDictionary.MergedDictionaries&gt;\n&lt;/ResourceDictionary&gt;\n\nStyle.xaml -&gt;\n\n&lt;ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n\n &lt;Style x:Key=\"CalculatorButton\" TargetType=\"{x:Type Button}\"&gt;\n &lt;Setter Property=\"Margin\" Value=\"2\" /&gt;\n &lt;/Style&gt;\n\n &lt;Style x:Key=\"OperationButton\" TargetType=\"{x:Type Button}\" BasedOn=\"{StaticResource CalculatorButton}\"&gt;\n &lt;Setter Property=\"FontWeight\" Value=\"bold\" /&gt;\n &lt;/Style&gt;\n\n &lt;Style x:Key=\"NumericButton\" TargetType=\"{x:Type Button}\" BasedOn=\"{StaticResource CalculatorButton}\"&gt;\n &lt;Setter Property=\"FontSize\" Value=\"20\" /&gt;\n &lt;/Style&gt;\n\n&lt;/ResourceDictionary&gt;\n\nApp.xaml -&gt;\n\n&lt;Application x:Class=\"Calculator.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n StartupUri=\"MainWindow.xaml\"&gt;\n &lt;Application.Resources&gt;\n &lt;ResourceDictionary Source=\"Resources/AppResources.xaml\" /&gt;\n &lt;/Application.Resources&gt;\n&lt;/Application&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T18:13:58.220", "Id": "220521", "ParentId": "213745", "Score": "2" } } ]
{ "AcceptedAnswerId": "213938", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:25:36.827", "Id": "213745", "Score": "5", "Tags": [ "c#", "calculator", "wpf" ], "Title": "Simple calculator in C# WPF" }
213745
<p>From the HackerRank question definition:</p> <blockquote> <p>The word google can be spelled in many different ways.</p> <p>E.g. google, g00gle, g0oGle, g&lt;>0gl3, googl3, GooGIe etc...</p> <p>Because</p> <p>g = G</p> <p>o = O = 0 = () = [] = &lt;></p> <p>l = L = I</p> <p>e = E = 3</p> <p>That's the problem here to solve.</p> <p>And the match has to be only this single word, nothing more, nothing less.</p> <p>E.g.</p> <p>"g00gle" = True, "g00gle " = False, "g google" = False, "GGOOGLE" = False, "hey google" = False</p> </blockquote> <p><strong>What I'm looking in review</strong>: How can I make my code more pythonic? </p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re g = ["g", "G"] o = ["o", "O", "0", "()", "[]", "&lt;&gt;"] l = ["l", "L", "I"] e = ["e", "E", "3"] regex = (g, o, o, g, l, e) regex = ((re.escape(y) for y in x) for x in regex) regex = ("(?:{})".format("|".join(x)) for x in regex) regex = "^{}$".format("".join(regex)) print(bool(re.match(regex, input()))) </code></pre>
[]
[ { "body": "<p>Honestly there's not much code to comment on, it's also a programming challenge, so there's not much incentive to make it any better than it is. I too would have done it your way.</p>\n\n<p>The only objective criticism I have is I'd just add a function <code>regex_options</code> to build the non-capturing group.</p>\n\n<p>Other than that I'd apply this to the creation of <code>g</code>, <code>o</code>, <code>l</code> and <code>e</code>. As I think it's a little cleaner. But you may want to perform it before <code>\"\".join</code>, and after <code>regex = (g, o, o, g, l, e)</code>.</p>\n\n<pre><code>import re\n\n\ndef regex_options(options):\n options = (re.escape(o) for o in options)\n return \"(?:{})\".format(\"|\".join(options))\n\n\ng = regex_options([\"g\", \"G\"])\no = regex_options([\"o\", \"O\", \"0\", \"()\", \"[]\", \"&lt;&gt;\"])\nl = regex_options([\"l\", \"L\", \"I\"])\ne = regex_options([\"e\", \"E\", \"3\"])\n\nregex = \"^{}$\".format(\"\".join((g, o, o, g, l, e)))\n\nprint(bool(re.match(regex, input())))\n</code></pre>\n\n<p>If this were professional code, I'd suggest using an <code>if __name__ == '__main__':</code> block, and possibly a <code>main</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:56:30.750", "Id": "413456", "Score": "2", "body": "I like this solution better, because it doesn't repeatedly redefine `regex` and change its type." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T19:52:02.360", "Id": "213753", "ParentId": "213746", "Score": "6" } } ]
{ "AcceptedAnswerId": "213753", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:32:51.680", "Id": "213746", "Score": "4", "Tags": [ "python", "python-3.x", "programming-challenge", "regex" ], "Title": "Regex to find variants of \"Google\"" }
213746
<p>I have very large method who insert child of <code>TreeView</code>, basically I do two different querys and set little changes I.E. firs foreach insert first child of parent and the second foreach insert child of child created before. </p> <p>Foreach query just change conditional <code>AND [ParentDesignKey] IS NULL</code>, but inside it variables are too similar.</p> <p>So here I have only two different foreach, but I need add 4 more childs of first foreach(second foreach), and I don't want very large method. Is there any way to optimize this?</p> <p>Full method:</p> <pre><code>private void AssignDesign(DataTable designItemList, DataTable designFolioList, TreeNode parent, string designName, string legacyKey, int indexProject) { var iDesign = 0; foreach (var currentDesignItem in designItemList.Select($"[Design Name] = '{designName}' AND [Project Number] = {legacyKey} AND [ParentDesignKey] IS NULL")) { var designItemName = currentDesignItem["DesignItemName"] as string; var designItemKey = currentDesignItem["DesignKey"] as int?; var designItemStatus = currentDesignItem["Design Status"] as string; var designItemIsLocked = currentDesignItem["IsLocked"] as bool?; var designItemStatusKey = currentDesignItem["StatusKey"] as int?; var designItemCreated = currentDesignItem["Design Created"] as DateTime?; var designItemRunCount = currentDesignItem["RunCount"] as int?; var designItemRunUnConCount = currentDesignItem["RunUnconCnt"] as int?; var designItemShopsStatus = currentDesignItem["ShopsStatus"] as int?; var designItemShopStatusExtended = currentDesignItem["ShopStatusExtended"] as string; var designItemFolio = designFolioList.Select($"[DesignKey] ={designItemKey}").FirstOrDefault()["Folio"].ToString(); if (designItemName is null || designItemShopsStatus is null || designItemShopStatusExtended is null || designItemKey is null || designItemStatus is null || designItemStatusKey is null || designItemCreated is null || designItemRunCount is null || designItemRunUnConCount is null || designItemIsLocked is null) continue; var projectIndex = parent.Index; parent.Nodes[indexProject].Nodes.Add(designItemName); parent.Nodes[indexProject].Nodes[iDesign].Tag = $"{designItemKey.Value}|{projectIndex}|BDCD"; parent.Nodes[indexProject].Nodes[iDesign].Name = "Design"; parent.Nodes[indexProject].Nodes[iDesign].ToolTipText = $"Design: {designItemName} - Folio: {designItemFolio}"; parent.Nodes[indexProject].Nodes[iDesign].ContextMenuStrip = contextMenuDesign; //load icon for design item this.LoadDesignStatusNodeIcon(parent.Nodes[indexProject].Nodes, iDesign, designItemStatusKey.Value, designItemIsLocked.Value); var parentNodes = parent.Nodes[indexProject].Nodes[iDesign].Nodes; parentNodes.Add(new TreeNode($"{designItemCreated.Value.ToLongDateString()} ({designItemCreated.Value.ToString("yyMMdd")})", 8, 8) { Name = "Design Created", ToolTipText = "Created Date" }); parentNodes.Add(new TreeNode(designItemStatus, 18, 18) { Name = "Design Status", ToolTipText = "Design Status", Tag = $"{designItemStatusKey.Value}|{designItemIsLocked}" }); var imgKey = LoadShopsNodeIcon(designItemShopsStatus.Value); parentNodes.Add(new TreeNode(designItemShopStatusExtended, imgKey, imgKey) { Name = "Shops Drawing Status", ToolTipText = "Shops Drawing Status", Tag = designItemShopsStatus.Value }); if (designItemRunCount.Value == 0 &amp;&amp; designItemRunUnConCount.Value &gt; 0) { parentNodes.Add(new TreeNode("Unconsolidated Runs: " + designItemRunUnConCount.Value) { Name = "Unconsolidated Runs", ToolTipText = "Unconsolidated Runs", Tag = designItemRunUnConCount.Value }); } else { parentNodes.Add(new TreeNode("Run Count: " + designItemRunCount.Value) { Name = "Run Count", ToolTipText = "Run Count", Tag = designItemRunCount.Value }); } var iChangeOrderDesign = 0; foreach (var item in designItemList.Select($"[Design Name] = '{designName}' AND [Project Number] = {legacyKey} AND [ParentDesignKey] = {designItemKey}")) { var changeOrderDesignItemName = item["DesignItemName"] as string; var changeOrderDesignItemKey = item["DesignKey"] as int?; var changeOrderDesignItemStatus = item["Design Status"] as string; var changeOrderDesignItemIsLocked = item["IsLocked"] as bool?; var changeOrderDesignItemStatusKey = item["StatusKey"] as int?; var changeOrderDesignItemCreated = item["Design Created"] as DateTime?; var changeOrderDesignItemRunCount = item["RunCount"] as int?; var changeOrderDesignItemRunUnConCount = item["RunUnconCnt"] as int?; var changeOrderDesignItemShopsStatus = item["ShopsStatus"] as int?; var changeOrderDesignItemShopStatusExtended = item["ShopStatusExtended"] as string; var changeOrderDesignItemFolio = designFolioList.Select($"[DesignKey] ={changeOrderDesignItemKey}").FirstOrDefault()["Folio"].ToString(); var changeOrderParentDesignKey = item["ParentDesignKey"] as int?; if (changeOrderDesignItemName is null || changeOrderDesignItemShopsStatus is null || changeOrderDesignItemShopStatusExtended is null || changeOrderDesignItemKey is null || changeOrderDesignItemStatus is null || changeOrderDesignItemStatusKey is null || changeOrderDesignItemCreated is null || changeOrderDesignItemRunCount is null || changeOrderDesignItemRunUnConCount is null || changeOrderDesignItemIsLocked is null) continue; //Create lowest level and assign their tree nodes projectIndex = parent.Index; TreeNode tn = parent.Nodes[indexProject].Nodes[iDesign].Nodes.Add(changeOrderDesignItemName); parent.Nodes[indexProject].Nodes[iDesign].Nodes[tn.Index].Tag = $"{changeOrderDesignItemKey.Value}|{projectIndex}|CO"; parent.Nodes[indexProject].Nodes[iDesign].Nodes[tn.Index].Name = "Design"; parent.Nodes[indexProject].Nodes[iDesign].Nodes[tn.Index].ToolTipText = $"Change Order: {changeOrderDesignItemName} - Folio: {changeOrderDesignItemFolio}"; parent.Nodes[indexProject].Nodes[iDesign].Nodes[tn.Index].ContextMenuStrip = contextMenuDesign; //load icon for changeOrderDesign item var changeOrderparentNodes = parent.Nodes[indexProject].Nodes[iDesign].LastNode.Nodes; changeOrderparentNodes.Add(new TreeNode($"{changeOrderDesignItemCreated.Value.ToLongDateString()} ({changeOrderDesignItemCreated.Value.ToString("yyMMdd")})", 8, 8) { Name = "Change Order Design Created", ToolTipText = "Created Date" }); changeOrderparentNodes.Add(new TreeNode(changeOrderDesignItemStatus, 18, 18) { Name = "Design Status", ToolTipText = "Design Status", Tag = $"{changeOrderDesignItemStatusKey.Value}|{changeOrderDesignItemIsLocked}" }); var changeOrderimgKey = LoadShopsNodeIcon(changeOrderDesignItemShopsStatus.Value); changeOrderparentNodes.Add(new TreeNode(changeOrderDesignItemShopStatusExtended, changeOrderimgKey, changeOrderimgKey) { Name = "Shops Drawing Status", ToolTipText = "Shops Drawing Status", Tag = changeOrderDesignItemShopsStatus.Value }); if (changeOrderDesignItemRunCount.Value == 0 &amp;&amp; changeOrderDesignItemRunUnConCount.Value &gt; 0) { changeOrderparentNodes.Add(new TreeNode("Unconsolidated Runs: " + changeOrderDesignItemRunUnConCount.Value) { Name = "Unconsolidated Runs", ToolTipText = "Unconsolidated Runs", Tag = changeOrderDesignItemRunUnConCount.Value }); } else { changeOrderparentNodes.Add(new TreeNode("Run Count: " + changeOrderDesignItemRunCount.Value) { Name = "Run Count", ToolTipText = "Run Count", Tag = changeOrderDesignItemRunCount.Value }); } this.LoadChangeOrderNodeIcon(parent.Nodes[indexProject].Nodes[iDesign].Nodes[tn.Index], iChangeOrderDesign, changeOrderDesignItemStatusKey.Value, changeOrderDesignItemIsLocked.Value); } iDesign++; } } </code></pre> <p><strong>UPDATE</strong></p> <p>In order to do a more simple method I do a recursion and set variables depending of item received:</p> <pre><code>private void AssignDesign(DataTable designItemList, DataTable designFolioList, TreeNode parent, string designName, string legacyKey, int indexProject, string DesignType, string Condition, int currDesign) { var iDesign = 0; foreach (var currentDesignItem in designItemList.Select($"[Design Name] = '{designName}' AND [Project Number] = {legacyKey} AND [ParentDesignKey] {Condition}")) { var designItemName = currentDesignItem["DesignItemName"] as string; var designItemKey = currentDesignItem["DesignKey"] as int?; var designItemStatus = currentDesignItem["Design Status"] as string; var designItemIsLocked = currentDesignItem["IsLocked"] as bool?; var designItemStatusKey = currentDesignItem["StatusKey"] as int?; var designItemCreated = currentDesignItem["Design Created"] as DateTime?; var designItemRunCount = currentDesignItem["RunCount"] as int?; var designItemRunUnConCount = currentDesignItem["RunUnconCnt"] as int?; var designItemShopsStatus = currentDesignItem["ShopsStatus"] as int?; var designItemShopStatusExtended = currentDesignItem["ShopStatusExtended"] as string; var designItemFolio = designFolioList.Select($"[DesignKey] ={designItemKey}").FirstOrDefault()["Folio"].ToString(); var changeOrderParentDesignKey = currentDesignItem["ParentDesignKey"] as int?; //var designConfirmDeliveryDate = currentDesignItem["ConfirmDeliveryDate"] as DateTime?; if (designItemName is null || designItemShopsStatus is null || designItemShopStatusExtended is null || designItemKey is null || designItemStatus is null || designItemStatusKey is null || designItemCreated is null || designItemRunCount is null || designItemRunUnConCount is null || designItemIsLocked is null) continue; //Create lowest level and assign their tree nodes var projectIndex = parent.Index; TreeNodeCollection parentNodes; if (DesignType == "BDCD") { parent.Nodes[indexProject].Nodes.Add(designItemName); parent.Nodes[indexProject].Nodes[iDesign].Tag = $"{designItemKey.Value}|{projectIndex}|BDCD"; parent.Nodes[indexProject].Nodes[iDesign].Name = "Design"; parent.Nodes[indexProject].Nodes[iDesign].ToolTipText = $"Design: {designItemName} - Folio: {designItemFolio}"; parent.Nodes[indexProject].Nodes[iDesign].ContextMenuStrip = contextMenuDesign; this.LoadDesignStatusNodeIcon(parent.Nodes[indexProject].Nodes, iDesign, designItemStatusKey.Value, designItemIsLocked.Value); parentNodes = parent.Nodes[indexProject].Nodes[iDesign].Nodes; } else { TreeNode tn = parent.Nodes[indexProject].Nodes[currDesign].Nodes.Add(designItemName); parent.Nodes[indexProject].Nodes[currDesign].Nodes[tn.Index].Tag = $"{designItemKey.Value}|{projectIndex}|CO"; parent.Nodes[indexProject].Nodes[currDesign].Nodes[tn.Index].Name = "Design"; parent.Nodes[indexProject].Nodes[currDesign].Nodes[tn.Index].ToolTipText = $"Change Order: {designItemName} - Folio: {designItemFolio}"; parent.Nodes[indexProject].Nodes[currDesign].Nodes[tn.Index].ContextMenuStrip = contextMenuDesign; this.LoadChangeOrderNodeIcon(parent.Nodes[indexProject].Nodes[currDesign].Nodes[tn.Index], currDesign, designItemStatusKey.Value, designItemIsLocked.Value); parentNodes = parent.Nodes[indexProject].Nodes[currDesign].LastNode.Nodes; } //load icon for design item var dateName = string.Empty; switch (DesignType) { case "BDCD": dateName = "Design Created"; break; case "CO": dateName = "Change Order Design Created"; break; } parentNodes.Add(new TreeNode($"{designItemCreated.Value.ToLongDateString()} ({designItemCreated.Value.ToString("yyMMdd")})", 8, 8) { Name = dateName, ToolTipText = "Created Date" }); parentNodes.Add(new TreeNode(designItemStatus, 18, 18) { Name = "Design Status", ToolTipText = "Design Status", Tag = $"{designItemStatusKey.Value}|{designItemIsLocked}" }); var imgKey = LoadShopsNodeIcon(designItemShopsStatus.Value); parentNodes.Add(new TreeNode(designItemShopStatusExtended, imgKey, imgKey) { Name = "Shops Drawing Status", ToolTipText = "Shops Drawing Status", Tag = designItemShopsStatus.Value }); if (designItemRunCount.Value == 0 &amp;&amp; designItemRunUnConCount.Value &gt; 0) { parentNodes.Add(new TreeNode("Unconsolidated Runs: " + designItemRunUnConCount.Value) { Name = "Unconsolidated Runs", ToolTipText = "Unconsolidated Runs", Tag = designItemRunUnConCount.Value }); } else { parentNodes.Add(new TreeNode("Run Count: " + designItemRunCount.Value) { Name = "Run Count", ToolTipText = "Run Count", Tag = designItemRunCount.Value }); } var lastItem = string.Empty; foreach (var item in designItemList.Select($"[Design Name] = '{designName}' AND [Project Number] = {legacyKey} AND [ParentDesignKey] = {designItemKey}")) { if (lastItem != parent.Text) { AssignDesign(designItemList, designFolioList, parent, designName, legacyKey, indexProject, "CO", $"= {designItemKey}", iDesign); } lastItem = parent.Text; } iDesign++; } } </code></pre> <p>But as you can see I send filter of query in method recursion:</p> <p>First foreach:</p> <pre><code>AssignDesign(tvTable, designFolioList, parent, designName, currentProjectNumber, iDesign, "BDCD","IS NULL", 0); </code></pre> <p>Second foreach (recursion)</p> <pre><code> AssignDesign(designItemList, designFolioList, parent, designName, legacyKey, indexProject, "CO", $"= {designItemKey}", iDesign); </code></pre> <p>In first one I send <code>"IS NULL"</code> and in second one <code>$"= {designItemKey}"</code></p> <p>Is there any way to do query one time only instead two times with different filters?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T18:37:45.570", "Id": "213747", "Score": "1", "Tags": [ "c#" ], "Title": "Optimize TreeView method" }
213747
<p>This was written for a coding challenge for a company I recently starting working for. I'm looking for any suggestions on how to clean up the code, as well as any issues anyone thinks may occur as it is written now. Fairly new to React.js, always looking to improve.</p> <p>Currently the data is passed through the app component where I render the Nav Container (functional stateless component). The Nav container creates the classNames and passes data + classNames to the NestedNav that I've put below.</p> <p>It started to feel a little sloppy while mapping twice below the render, not sure if that's a problem?</p> <p>The data object example shows how I modeled my data. This example has a parent with children that also have children. </p> <ul> <li>The parentClass is for the outer parent.</li> <li>The nestedParentClass is for the children of the outer parent.</li> <li>The childClass is reserved for any children of the nestedParent.</li> </ul> <pre><code>export const data = [ { id: 1, icon: &lt;FontAwesomeIcon className='i' icon={faHeartbeat} /&gt;, title: 'SAFETY', children: [ {title: 'Reporting', children: [ {id: 11, title: 'I-21 Injury Reporting', url: '/safety/report'}, {id: 12, title: 'ASAP Reporting', url: '/safety/asap-report'}, {id: 13, title: 'General ASAP Information', url: '/safety/general'}, {id: 14, title: 'Flight Attendant Incident Report', url: '/safety/flight-attendant-incident'}, ]}, {title: 'Agriculture and Customs', children: [ {id: 15, title: 'Product Safety Data Search', url: '/safety/data-search'}]}, {id: 16, title: 'Known Crewmember', url: '/safety/known-cremember'}, {id: 17, title: 'Product Safety Data Search', url: '/safety/data-search'}, ], }, ] </code></pre> <pre><code>class NestedNav extends Component { constructor(props) { super(props) this.state = { selected: '', nestSelect: '', children: [], active: '', } } handleClick = (title) =&gt; { this.setState({ selected: '', nestSelect: '', children: [], active: '', }) } render() { const {data, parentClass, nestedParentClass} = this.props const renderedChildElements = this.state.children const active = this.state.active === 'true' ? 'true' : '' const mappedChildren = (child, title) =&gt; { let childElement if(child) { childElement = child.map((child, i) =&gt; &lt;li key={i} id={child.id} className={nestedParentClass + (this.state.nestSelect === child.title ? 'nest-selected' : '')} url={child.url}&gt;&lt;Link to={'/'}&gt;{child.title}&lt;/Link&gt; {child.children ? &lt;FontAwesomeIcon onClick={() =&gt; mappedChildren(child.children, this.state.select)} className='i button' icon={faArrowCircleDown} /&gt; : null} &lt;/li&gt;) this.setState({ selected: title, children: childElement, active: 'true', }) } return '' } const navListItems = data.map((collection, i) =&gt; &lt;li key={i} id={collection.id} className={parentClass + (this.state.selected === collection.title ? 'selected' : '')} url={collection.url}&gt;&lt;i onClick={this.handleClick}&gt;{collection.icon}&lt;/i&gt;&lt;Link to={'/'}&gt;&lt;span&gt;{collection.title}&lt;/span&gt;&lt;/Link&gt; {collection.children ? &lt;FontAwesomeIcon onClick={() =&gt; mappedChildren(collection.children, collection.title)} className='i button' icon={faArrowCircleRight} /&gt; : null} &lt;/li&gt;) return ( &lt;div className={'nested-nav'}&gt; &lt;div className={'container-two-' + active}&gt; &lt;h2&gt;{this.state.selected}&lt;/h2&gt; {this.state.children} &lt;/div&gt; &lt;div className='container-one'&gt;{navListItems}&lt;/div&gt; &lt;/div&gt; ) } } export default NestedNav </code></pre>
[]
[ { "body": "<p>it's clear and readable but i would like to point out some things :</p>\n\n<p><a href=\"https://stackoverflow.com/questions/41369296/react-functions-inside-render\">Avoid using functions inside Render()</a></p>\n\n<blockquote>\n <p>A function in the render method will be created each render which is a\n slight performance hit. t's also messy if you put them in the render, which is a much > bigger reason</p>\n</blockquote>\n\n<p>Use the <code>child.id</code> instead of <code>key</code> as <code>index</code> when you <code>map</code> through an array in <code>render()</code> because <a href=\"https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318\" rel=\"nofollow noreferrer\">Index as a key is an anti-pattern</a>.</p>\n\n<p>Keep your code as <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> as possible, the initialState can be an object outside the class instead of writing it twice or more, especially if it's a big object.</p>\n\n<p>Optional : use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a> to indicate which keys you will use in the function.</p>\n\n<pre><code>const initialState = {\n selected: '',\n nestSelect: '',\n children: [],\n active: '',\n}\n\nclass NestedNav extends Component {\n constructor(props) {\n super(props)\n this.state = initialState\n }\n\n handleClick = title =&gt; {\n this.setState({ ...initialState })\n }\n\n mappedChildren = (child, selectedTitle) =&gt; {\n const { nestedParentClass } = this.props\n let childElement\n\n if (child) {\n childElement = child.map(({ id, title, children, url }) =&gt; &lt;li\n key={id}\n id={id}\n className={nestedParentClass + (this.state.nestSelect === title ? 'nest-selected' : '')}\n url={url}&gt;&lt;Link to={'/'}&gt;{title}&lt;/Link&gt;\n {children ?\n &lt;FontAwesomeIcon\n onClick={() =&gt; this.mappedChildren(children, this.state.select)}\n className='i button'\n icon={faArrowCircleDown} /&gt; : null}\n &lt;/li&gt;)\n this.setState({\n selected: selectedTitle,\n children: childElement,\n active: 'true',\n })\n }\n return ''\n }\n\n navListItems = data =&gt; data.map(({ id, url, children, title, icon }) =&gt; {\n const { parentClass } = this.props\n return (&lt;li\n key={id}\n id={id}\n className={parentClass + (this.state.selected === title ? 'selected' : '')}\n url={url}&gt;&lt;i onClick={this.handleClick}&gt;{icon}&lt;/i&gt;&lt;Link to={'/'}&gt;&lt;span&gt;{title}&lt;/span&gt;&lt;/Link&gt;\n {children ?\n &lt;FontAwesomeIcon\n onClick={() =&gt; this.mappedChildren(children, title)}\n className='i button'\n icon={faArrowCircleRight} /&gt; : null}\n &lt;/li&gt;)\n });\n\n render() {\n const { data } = this.props\n const active = this.state.active === 'true' ? 'true' : ''\n\n return (\n &lt;div className={'nested-nav'}&gt;\n &lt;div className={'container-two-' + active}&gt;\n &lt;h2&gt;{this.state.selected}&lt;/h2&gt;\n {this.state.children}\n &lt;/div&gt;\n &lt;div className='container-one'&gt;{this.navListItems(data)}&lt;/div&gt;\n &lt;/div&gt;\n )\n }\n}\nexport default NestedNav\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T03:11:44.223", "Id": "213779", "ParentId": "213754", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T21:18:23.003", "Id": "213754", "Score": "4", "Tags": [ "javascript", "programming-challenge", "recursion", "functional-programming", "react.js" ], "Title": "React.js Nested Nav Bar" }
213754
<p>I am coming to a problem where I am writing a function that accepts a pointer to a C-string as its argument. The function should count the number of vowels appearing in the string and return that number. Then, I am writing another function that accepts a pointer to a C-string as its argument. This function should count the number of consonants appearing in the string and return that number. </p> <p>Am I violating any of the following restrictions?</p> <ul> <li>No global variables</li> <li>No labels or go-to statements</li> <li>No infinite loops, examples include: for(;;), while(1), while(true), do{//code}while(1);</li> <li>No break statements to exit loops</li> </ul> <p>Here is my code: </p> <pre><code>#include&lt;iostream&gt; using namespace std; //Function prototypes int Vowel_count( char *str); int Consonant_count(char *str); int main() { char String[30]; char choice; int Nvowels,Nconsonant; //Input a string cout&lt;&lt;"Enter a string:"; cin.getline(String ,30); do { //Displaying Menu cout&lt;&lt;"\nMENU"&lt;&lt;endl; cout&lt;&lt;" (A) Count the number of vowels in the string"&lt;&lt;endl; cout&lt;&lt;" (B) Count the number of Consonants in the string"&lt;&lt;endl; cout&lt;&lt;" (C) Count both the vowels and consonants in the string"&lt;&lt;endl; cout&lt;&lt;" (D) Enter another string"&lt;&lt;endl; cout&lt;&lt;" (E) Exit program"&lt;&lt;endl; //Inputting choice cout&lt;&lt;"Enter choice"; cin&gt;&gt;choice; switch(choice) { case 'A': //Function call to get number of Vowels Nvowels=Vowel_count(String); cout&lt;&lt;"Number of vowels is:"&lt;&lt;Nvowels&lt;&lt;endl; break; case 'B': //Function call to get number of consonants Nconsonant=Consonant_count(String); //Outputting number of Consonants cout&lt;&lt;"Number of Consonants is:"&lt;&lt;Nconsonant&lt;&lt;endl; break; case 'C': //Function call to get number of Vowels Nvowels=Vowel_count(String); //Function call to get number of consonants Nconsonant=Consonant_count(String); //Outputting Both Vowels and Consonants cout&lt;&lt;"Number of vowels is:"&lt;&lt;Nvowels&lt;&lt;endl; cout&lt;&lt;"Number of Consonants is:"&lt;&lt;Nconsonant&lt;&lt;endl; break; case 'D': //Inputting another string cout&lt;&lt;"Enter another String:"; fflush(stdin); cin.getline(String ,30); break; case 'E': exit(0); break; }//End of Switch }while(choice !='E');//End Do while //Pause system for a while system("pause"); }//End main //Function Definitions int Vowel_count( char *str) { int count=0;//Local variable //Checks for all characters in C-string while(*str!='\0') { if(*str=='a'||*str=='e'||*str=='i'||*str=='o'||*str=='u') count++; str++; }//End While //Returns count value to function call return count; }//End of Vowel_count int Consonant_count(char *str) { int count=0; //Checks for all characters in C-string while(*str!='\0') { //Checks for consonants if(*str!='a'&amp;&amp;*str!='e'&amp;&amp;*str!='i'&amp;&amp;*str!='o'&amp;&amp;*str!='u') count++; str++; }//End While //Returns count value to function call return count; } </code></pre>
[]
[ { "body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). </p>\n\n<h2>Don't use <code>system(\"pause\")</code></h2>\n\n<p>There are two reasons not to use <code>system(\"cls\")</code> or <code>system(\"pause\")</code>. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely <strong>must</strong> care about. Specifically, if some program is defined and named <code>cls</code> or <code>pause</code>, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions <code>cls()</code> and <code>pause()</code> and then modify your code to call those functions instead of <code>system</code>. Then rewrite the contents of those functions to do what you want using C++. For example, for <code>pause</code> you might use this:</p>\n\n<pre><code>void pause()\n{\n std::string;\n std::cout &lt;&lt; \"Press enter to continue...\\n\";\n std::cin &gt;&gt; foo;\n}\n</code></pre>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently. </p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Use string concatenation</h2>\n\n<p>The menu includes these lines:</p>\n\n<pre><code>cout&lt;&lt;\"\\nMENU\"&lt;&lt;endl;\ncout&lt;&lt;\" (A) Count the number of vowels in the string\"&lt;&lt;endl;\ncout&lt;&lt;\" (B) Count the number of Consonants in the string\"&lt;&lt;endl;\ncout&lt;&lt;\" (C) Count both the vowels and consonants in the string\"&lt;&lt;endl;\ncout&lt;&lt;\" (D) Enter another string\"&lt;&lt;endl;\ncout&lt;&lt;\" (E) Exit program\"&lt;&lt;endl;\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 &lt;&lt; \n \"\\nMENU\\n\"\n \" (A) Count the number of vowels in the string\\n\"\n \" (B) Count the number of Consonants in the string\\n\"\n \" (C) Count both the vowels and consonants in the string\\n\"\n \" (D) Enter another string\\n\"\n \" (E) Exit program\\n\"\n \"Enter choice\\n\";\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>Check your <code>if</code> statements for proper braces</h2>\n\n<p>I suspect that the <code>if</code> statement in the <code>Vowel_count()</code> routine is not what you intended to write. It's written like this:</p>\n\n<pre><code>if(*str=='a'||*str=='e'||*str=='i'||*str=='o'||*str=='u')\n count++;\n str++;\n</code></pre>\n\n<p>but because there are no braces, what's actually being executed is this:</p>\n\n<pre><code>if(*str=='a'||*str=='e'||*str=='i'||*str=='o'||*str=='u') {\n count++;\n}\nstr++;\n</code></pre>\n\n<p>That is the correct operation, but it's confusing to the reader. I recommend using the braces always to avoid ambiguity or confusion.</p>\n\n<h2>Use <code>const</code> where possible</h2>\n\n<p>The <code>Vowel_count</code> and <code>Consonant_count</code> functions do not (and should not) alter the passed <code>char *</code>, so that parameter should be passed as <code>const</code>.</p>\n\n<h2>Fix the bug</h2>\n\n<p>If the user enters the string <code>\"My dog has fleas.\"</code>, the program will report 4 vowels and 13 consonants, but that's not actually correct. The <code>'y'</code> in \"My\" is a vowel in this usage and the spaces and period are not consonants.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:57:15.340", "Id": "413475", "Score": "0", "body": "Thanks @Edward for the helpful tips. I will def. fix it. But, does it apply to the restrictions I have above? Or Program free from those restrictions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:26:14.623", "Id": "413479", "Score": "0", "body": "Yes, it appears to comply with the stated restrictions. Also, I should mention that those restrictions are *generally good programming practices*, so keep them in mind for future programs as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:18:33.137", "Id": "413522", "Score": "0", "body": "Determining whether `y` is acting as a consonant or as a vowel adds complexity, but perhaps it's an interesting problem for a [tag:beginner]..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:53:39.290", "Id": "213765", "ParentId": "213756", "Score": "2" } }, { "body": "<pre><code> char String[30];\n char choice;\n int Nvowels,Nconsonant;\n</code></pre>\n\n<p>Don't define a variable before it is needed. Doing so increases the cognitive load on readers that trace through your code and keep mental records of every variable, their possible values, and whether they've even been set. This artifact from older languages also encourages lazy reuse of variables beyond their original intent. Define variables as you need them and keep the scope of each variable as narrow as required.</p>\n\n<p>Use descriptive names. The larger the scope in which a variable exists, the more important it is to give that variable a name that indicates to the reader what it represents. <code>String</code> <span class=\"math-container\">\\$\\rightarrow\\$</span> <code>input_sentence</code>. <code>Nvowels</code> <span class=\"math-container\">\\$\\rightarrow\\$</span> <code>vowel_count</code>.</p>\n\n<hr>\n\n<pre><code> cin.getline(String ,30);\n</code></pre>\n\n<p>If a user inputs 30 or more characters, <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/getline\" rel=\"nofollow noreferrer\"><code>std::istream::getline</code></a> will set the <code>failbit</code>. If <em>end-of-file</em> is reached before the delimiter is encountered, <code>std::istream::getline</code> will set the <code>eofbit</code>. You should check if <code>std::cin</code> is in a readable state and reset the state if it's not, otherwise you'll have an infinite loop when an error is encountered.</p>\n\n<hr>\n\n<pre><code> cout&lt;&lt;\"\\nMENU\"&lt;&lt;endl;\n cout&lt;&lt;\" (A) Count the number of vowels in the string\"&lt;&lt;endl;\n cout&lt;&lt;\" (B) Count the number of Consonants in the string\"&lt;&lt;endl;\n cout&lt;&lt;\" (C) Count both the vowels and consonants in the string\"&lt;&lt;endl;\n cout&lt;&lt;\" (D) Enter another string\"&lt;&lt;endl;\n cout&lt;&lt;\" (E) Exit program\"&lt;&lt;endl;\n</code></pre>\n\n<p>Whitespace is great for readability as they help separate operators and language constructs.</p>\n\n<p>Avoid <code>std::endl</code>. If you need to explicitly flush the cache, then explicitly stream the manipulator <a href=\"https://en.cppreference.com/w/cpp/io/manip/flush\" rel=\"nofollow noreferrer\"><code>std::flush</code></a> and comment why a flush is necessary. If you simply need a <em>end-of-line</em> character, prefer '\\n' or \"\\n\".</p>\n\n<p>Edward covered string concatenation via the compiler, but I'd like to also point out that C++11 introduced <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">raw string literals</a>.</p>\n\n<pre><code> std::cout &lt;&lt; R\"(\nMENU\n (A) Count the number of vowels in the string\n (B) Count the number of Consonants in the string\n (C) Count both the vowels and consonants in the string\n (D) Enter another string\n (E) Exit program\nEnter Choice\n\");\n</code></pre>\n\n<hr>\n\n<pre><code> cin&gt;&gt;choice;\n</code></pre>\n\n<p>As with <code>std::istream::getline</code>, <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt\" rel=\"nofollow noreferrer\"><code>std::istream::operator&gt;&gt;</code></a> needs to be checked to ensure a read was successful. If extraction failed, you should probably notify the user and attempt to recover.</p>\n\n<hr>\n\n<pre><code> case 'A':\n //Function call to get number of Vowels\n case 'B':\n //Function call to get number of consonants\n //Outputting number of Consonants\n case 'C':\n //Function call to get number of Vowels\n</code></pre>\n\n<p>Keep comments crisp. Everything I need to know as far as what is being done is already there in the form of code to be compiled. Comments should be reserved for explaining why the code was written the way it was (the intent). Adding verbosity slows down understanding.</p>\n\n<p>To assist with the readability, consider mapping the character inputs to enumerations. You can read up on enum serialization, but just to give you an idea of how it can help readability:</p>\n\n<pre><code>enum class Selected {\n count_vowels = 'A',\n count_consonants,\n count_both,\n reset_sentence,\n exit\n};\n\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, Selected op) {\n // exercise for the reader. \n}\n\nint main() {\n // ...\n Selected user_choice;\n std::cout &lt;&lt; \"Enter choice: \";\n std::cin &gt;&gt; user_choice;\n\n switch (user_choice) {\n case Selected::count_vowels:\n // ...\n case Selected::count_consonants:\n // ...\n case Selected::count_both:\n // ...\n case Selected::reset_sentence:\n // ...\n case Selected::exit:\n // ...\n case default:\n // Handle user-input error (out of range, end of file)\n</code></pre>\n\n<hr>\n\n<pre><code> fflush(stdin);\n</code></pre>\n\n<p>Using <a href=\"https://en.cppreference.com/w/cpp/io/c/fflush\" rel=\"nofollow noreferrer\"><code>std::fflush</code></a> on an input stream is <a href=\"https://en.cppreference.com/w/cpp/language/ub\" rel=\"nofollow noreferrer\"><strong><em>undefined behavior</em></strong></a>. If you were trying to reset the buffer of <code>std::cin</code>, see <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/ignore\" rel=\"nofollow noreferrer\"><code>std::cin::ignore</code></a>.</p>\n\n<hr>\n\n<pre><code> case 'E': \n exit(0);\n break;\n }\n } while (choice != 'E');\n\n system(\"pause\");\n</code></pre>\n\n<p>Once the the program encounters <code>exit(0)</code>, all of the remaining code (<code>break;</code> <span class=\"math-container\">\\$\\rightarrow\\$</span> <code>while (choice != 'E')</code> <span class=\"math-container\">\\$\\rightarrow\\$</span> <code>system(\"pause\");</code>) is unreachable. If you intend to immediately return from a function (or in this case exit the program), you don't need to loop until <code>choice</code> is <span class=\"math-container\">\\$E\\$</span>. This is one of those times where <code>while (true)</code> is actually appropriate if you didn't have the restriction.</p>\n\n<p><code>system(\"pause\")</code> is slow, platform-dependent, and insecure. Consider re-evaluating your development environment, from having permanent access to a console or utilizing the breakpoint of a debugger.</p>\n\n<hr>\n\n<pre><code>int Consonant_count(char *str) {\n // ...\n if (*str != 'a' &amp;&amp; *str != 'e' &amp;&amp; *str != 'i' &amp;&amp; *str != 'o' &amp;&amp; *str != 'u')\n count++;\n str++;\n</code></pre>\n\n<p>Prefer scoping your single-line statement blocks with braces. Adding code in a hurry </p>\n\n<pre><code>if (condition)\n statement;\n statementIntendedToBeScoped???\n</code></pre>\n\n<p>or commenting</p>\n\n<pre><code>if (condition)\n // statement\nstatementThatIsNowScopedToCondition\n</code></pre>\n\n<p>can lead to errors. Scoping with braces addresses this issue.</p>\n\n<pre><code>if (condition) {\n statement\n}\nstatementDefinitelyNotScoped\n\nif (condition) {\n // statement\n}\nstatementDefinitelyNotScoped\n</code></pre>\n\n<hr>\n\n<pre><code>if (*str != 'a' &amp;&amp; *str != 'e' &amp;&amp; *str != 'i' &amp;&amp; *str != 'o' &amp;&amp; *str != 'u')\n</code></pre>\n\n<p>Keep in mind the various possible values a type can represent. A character (<code>char</code>) can represent the set of consonants and vowels (A-Z, a-z). It can also represent digits, punctuation, control characters, whitespace, etc. The conditional in <code>Consonant_count</code> is returning true or false if the current character is any ASCII character (not any alphabetic character) that is not any of <code>aeiou</code>. Clearly control structures, punctuation, and whitespaces are not consonants.</p>\n\n<p>In both of your functions, how do you handle uppercase vowel inputs?</p>\n\n<p>Rather than check each individual vowel, consider a lookup technique. You could create a table (one for vowel, one for consonant) that maps each character to true or false. There is also a bit mapping alternative that builds on the lookup table approach, where you exploit the layout of the ascii table to do very fast lookups via bit shifts and masks.</p>\n\n<pre><code>bool is_vowel(char ch) {\n auto lowercase_pos = (ch | 0x20) - 96;\n if (static_cast&lt;unsigned char&gt;(lowercase_pos) &gt; 31) {\n return false;\n }\n constexpr std::uint32_t vowel_mask = (1 &lt;&lt; 1) | (1 &lt;&lt; 5) | (1 &lt;&lt; 9) | (1 &lt;&lt; 15) | (1 &lt;&lt; 21);\n return (vowel_mask &amp; (std::uint32_t{1} &lt;&lt; lowercase_pos)) != 0;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>specific_count(range)\n count = 0\n for each element in the range\n if element is what we're looking for\n count = count + 1\n return count\n</code></pre>\n\n<p>Learn the various <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\"><code>&lt;algorithm&gt;</code>s</a>. You'll notice that both your functions have the same structure as the pseudocode above. It turns out, this is a common algorithm in C++ (<a href=\"https://en.cppreference.com/w/cpp/algorithm/count\" rel=\"nofollow noreferrer\"><code>std::count_if</code></a>). You should be aware of this library as you learn more about functions and specifically lambdas (objects that behave like functions and can be passed around into functions as arguments).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:17:11.773", "Id": "213792", "ParentId": "213756", "Score": "3" } }, { "body": "<p>You can use standard algorithms to implement vowel or consonant count, e.g.,</p>\n\n<pre><code>int vowel_count(const std::string&amp; s)\n{\n return std::count_if(s.begin(), s.end(), [](char c) { \n return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }\n );\n}\n</code></pre>\n\n<p>Clearly, you can apply the same idea for counting consonants (or even implement that in terms of vowel counting, i.e., every character that is <em>not</em> a vowel <em>is</em> a consonant, but this requires you to trust the input to be sane).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T18:41:11.267", "Id": "213829", "ParentId": "213756", "Score": "0" } } ]
{ "AcceptedAnswerId": "213765", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:08:11.323", "Id": "213756", "Score": "5", "Tags": [ "c++", "beginner", "strings" ], "Title": "Functions to count vowels and consonants in strings" }
213756
<ul> <li>Some JavaScript libraries relies on window <code>innerWidth</code> and <code>innerHeight</code> to do their calculations</li> <li><code>window.innerWidth</code> is not 100% reliable, which may lead to bugs</li> <li><code>matchMedia().matches</code> is 100% accurate but it returns a boolean value</li> <li>come around: use <code>matchMedia</code> to verify <code>window.innerWidth</code> value; if it returns false use <code>matchMedia</code> to do a binary search until it finds the correct value</li> </ul> <p>I faced that issue with some libs that relies on <code>window.innerWidth</code>. In cases where I had some media queries the return value of <code>window.innerWidth</code> used by the library would be off and that library would have issues with incorrect value.</p> <p>I've seen that <code>matchMedia().matches</code> always return the correct value, but it returns a boolean value, not the width value. I've not seen a solution so far for that (maybe some of you know a better solution?), so I came up with a solution using <code>matchMedia</code>.</p> <p>I created a function <code>getCorrectDimension</code> that performs a binary search around the window <code>innerWidth</code> (or <code>innerHeight</code>) to find the correct value if its value is wrong as you can see below:</p> <pre><code>const binarySearch = dim =&gt; function bin(start, end) { const guess = Math.floor((start + end)/2) // this checks if we have the correct value, if not it will keep calling itself until there's a match if(window.matchMedia(`(${dim}: ${guess}px)`).matches) { return guess } // since it is not a match, then we need to recalibrate the range and call again. // for that we check the boolean value using with min-width (height) rule. return window.matchMedia(`(min-${dim}: ${guess}px)`).matches ? bin(guess, end) : bin(start, guess) } const getCorrectDimension = (dim = 'width', range = 300) =&gt; { if(dim !== 'width' &amp;&amp; dim !== 'height') { throw Error('`getCorrectDimension` accepts "width" or "height" as parameter') } let prop = 'inner' + dim.charAt(0).toUpperCase() + dim.slice(1) // here checks if the window.innerWidth or Height it's the correct one if(window.matchMedia(`(${dim}: ${window[prop]}px)`).matches) { return window[prop] } // here, since the value is wrong we use binarySearch to find its correct value const start = window[prop] - range &gt;= 0 ? window[prop] - range : 0 const end = window[prop] + range return binarySearch(dim)(start, end) } </code></pre>
[]
[ { "body": "<p><strike>I have never seen <code>innerWidth</code> or <code>innerHeight</code> report the wrong value. There are a few bugs listed for chrome and firefox but they are all closed.</strike></p>\n<p><strike>Could you provide any evidence?</strike></p>\n<h1>UPDATE</h1>\n<p>Media query matches down to fractions of a CSS pixel while <code>innerWidth</code> returns integer CSS pixel values. This is a problem when <code>devicePixelRatio !== devicePixelRatio | 0</code></p>\n<p>I tried to find a cover all solution, but too much time need to complete so I withdraw the answers content.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:24:51.520", "Id": "413608", "Score": "0", "body": "example of the issue: at [link](https://css-tricks.com/almanac/properties/a/animation/) if you attach an event listener like `window.addEventListener('resize', () => console.log(window.innerWidth))`, you can see `window.innerWidth` value make jumps around 950px, a place with a media query breakpoint. you can play around and look into other sites. I started to look recently into this when checking an issue opened at `react-sizes` [link](https://github.com/renatorib/react-sizes/issues/32)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T23:21:34.143", "Id": "413615", "Score": "0", "body": "@buzatto The only way i can get `innerWidth` to not match the media query is to use a zoom that results in a fractional pixel size such that `matchMedia(`(min-width: ${innerWidth-1}px) and (max-width: ${innerWidth+1}px)`).matches` is true but `matchMedia(`(width: ${innerWidth}px)`).matches` is false. It's not `innerWidth` that is at fault but the media query. The spec is ambiguous, I will update answer when i have done further research. As it stands searching for a matching integer size will fail if `devicePixelRatio !== devicePixelRatio | 0` or the scroll bar size has the same condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T01:27:20.897", "Id": "413628", "Score": "0", "body": "you said that it had bugs related to chrome and firefox before, but not anymore. I mostly use chrome on daily basis, I tested now on firefox and edge, no apparent issue on them everything is fine, but on chrome there is 16 px jump on average on that example link. I also have a personal project and only on chrome I see jumps as well, not on firefox or edge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T02:44:19.383", "Id": "413634", "Score": "0", "body": "@buzatto Your code as it is in the question can fail if the `range` argument is smaller than the error eg `innerWidth` reports 1000, media query passes 1016 and `range` is 10. Also fails on latest Chrome (win10) on some `devicePixelRatio` non integer values. Eg `devicePixelRatio = 1.100000036` (menu setting 110%) the media query matched 1427.6px but not 1428px the closest integer value (I forget the exact values). When it fails it throws a call stack overflow." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:50:16.217", "Id": "213793", "ParentId": "213760", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:38:11.067", "Id": "213760", "Score": "4", "Tags": [ "javascript", "dom", "layout" ], "Title": "window.innerWidth - workaround for when it returns the wrong value" }
213760
<p>My goal is to move a 'monster' (<code>mX, mY</code>) in a 2d grid towards the player (<code>pX, pY</code>). The monster can move 8 directions.</p> <p>I have working code for this, but I'm very new to Python and have a strong inclination it is awful and there is faster ways to do it.</p> <p>I do this by creating a 3 x 3 array around the monsters position (array slot 4), and filling it with the distance from that array position to the player. Then I check if any are lower than the monsters current distance, and if so, move the monster to it.</p> <p><a href="https://i.stack.imgur.com/xUCzH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xUCzH.png" alt="enter image description here"></a></p> <p>Here is my current code, apologies if it makes you puke, I'm still learning the ropes.</p> <pre><code># get the distance between the monster and player dist = math.hypot(pX - mX, pY - mY) if dist &gt; 1.5 and dist &lt; 10: # make an 'array' grid to store updated distances in goto = np.full((3, 3), 10, dtype=float) # if each position in the array passes a # collision check, add each new distance if collisionCheck(mID, (mX-1), (mY-1), mMap) == 0: goto[0][0] = round(math.hypot(pX - (mX-1), pY - (mY-1)), 1) if collisionCheck(mID, mX, (mY-1), mMap) == 0: goto[0][1] = round(math.hypot(pX - mX, pY - (mY-1)), 1) if collisionCheck(mID, (mX+1), (mY-1), mMap) == 0: goto[0][2] = round(math.hypot(pX - (mX+1), pY - (mY-1)), 1) if collisionCheck(mID, (mX-1), mY, mMap) == 0: goto[1][0] = round(math.hypot(pX - (mX-1), pY - mY), 1) # goto[1][1] is skipped since that is the monsters current position if collisionCheck(mID, (mX+1), mY, mMap) == 0: goto[1][2] = round(math.hypot(pX - (mX+1), pY - mY), 1) if collisionCheck(mID, (mX-1), (mY+1), mMap) == 0: goto[2][0] = round(math.hypot(pX - (mX-1), pY - (mY+1)), 1) if collisionCheck(mID, mX, (mY+1), mMap) == 0: goto[2][1] = round(math.hypot(pX - mX, pY - (mY+1)), 1) if collisionCheck(mID, (mX+1), (mY+1), mMap) == 0: goto[2][2] = round(math.hypot(pX - (mX+1), pY - (mY+1)), 1) # get the lowest distance, and its key lowest = goto.min() lowestKey = goto.argmin() # if the lowest distance is lower than monsters current position, move if lowest &lt; dist: if lowestKey == 0: newX = mX - 1 newY = mY - 1 if lowestKey == 1: newY = mY - 1 if lowestKey == 2: newX = mX + 1 newY = mY - 1 if lowestKey == 3: newX = mX - 1 if lowestKey == 5: newX = mX + 1 if lowestKey == 6: newY = mY + 1 newX = mX - 1 if lowestKey == 7: newY = mY + 1 if lowestKey == 8: newX = mX + 1 newY = mY + 1 </code></pre> <p>What is the cleanest, simplest, and fastest way to do what I'm doing? This is going to loop through many monsters at once!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:50:16.877", "Id": "413474", "Score": "0", "body": "Could you add more description, how big is the board, is the player always in the 3x3 grid?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:59:14.990", "Id": "413476", "Score": "0", "body": "The board could be any size, this just creates a temporary array around the monster to decide which square it will move to" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:02:28.170", "Id": "413477", "Score": "0", "body": "Is there anything the monster can collide with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:05:27.867", "Id": "413478", "Score": "0", "body": "The collisioncheck() routine returns a 0 or a 1. Its an external def that checks if any other monsters, players or walls are at that position." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:48:09.177", "Id": "413485", "Score": "0", "body": "Hopefully I've not messed up my math when converting to this comment, but you can use: `d = math.degrees(math.atan((pY - mY) / (pX - mY)))` and `'N NE E SE S SW W NW'.split()[int((d + 22.5) // 45)]` to know which direction you want to go if there are no collisions." } ]
[ { "body": "<p>Some thoughts from a non-game-developer:</p>\n\n<ul>\n<li>The second and subsequent <code>if lowestKey</code> should use <code>elif</code> to short-circuit the evaluation when it finds a match.</li>\n<li>I believe algorithms such as A* (A-star) are very well suited to find the shortest path between two points on a 2-dimensional map.</li>\n<li>Running this code through a linter such as <code>flake8</code> will show how to make your code more pythonic.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:50:03.003", "Id": "213763", "ParentId": "213762", "Score": "1" } }, { "body": "<p>Especially in a game where you have many monsters, and obstacles on the field, I suggest that you take a different approach.</p>\n\n<p>Create a \"parallel grid\" that has the same size as the map, but has integers as values. Set all the values to some impossible value.</p>\n\n<p>Now write a recursive \"fill\" algorithm that does the following:</p>\n\n<pre><code>def fill_distance_map(m, row, col, value):\n \"\"\"Fill a distance map with increasing values, starting at a point.\"\"\"\n if m[row][col] &lt;= value:\n return\n\n m[row][col] = value\n\n for new_pos in surrounding(row, col):\n fill_distance_map(m, *new_pos, value + 1)\n</code></pre>\n\n<p>(Note: you will likely find that a \"breadth-first\" version is more efficient than this \"depth-first\" code. But not as easy to understand. :-)</p>\n\n<p>The idea is to create a \"gradient\" map, which measures the distance from some target. The lower the number stored in the map, the closer to the target. Obviously, invalid squares should be filtered out during the generation process, as this will change the distance values (consider a wall, where if you can't pass \"through\" the wall you have to walk around it- the distance to the \"other side\" can be quite long).</p>\n\n<p>Once you have this map, it's the same for <em>all</em> of your monsters - it's based on the current position of the target (player) and so the monsters can share it. You can then decide on monster movement by just picking the minimum value of all the positions they could move to. And you only have to update the map when the player moves, or when the monsters are about to move, depending on which is more convenient for you.</p>\n\n<p>Here's an example: (P = 0 is the player, # = wall, M = monster)</p>\n\n<pre><code> # # # # # # # # # # # # # # # # # # # #\n . . . . . . . . . # 2 1 1 1 2 3 4 5 6 #\n . . P . . . # . . # 2 1 P 1 2 3 # 5 6 #\n . . # # # # # # . # 2 1 # # # # # # 6 #\n . . # . . . . # . # 2 2 # 12 11 11 11 # 7 #\n . . # . M . . # . # 3 3 # 12 M 10 10 # 8 #\n . . # # # # . # . # 4 4 # # # # 9 # 9 #\n . . . . . . . # . # 5 5 5 6 7 8 9 # 10 #\n # # # # # # # # # # # # # # # # # # # #\n</code></pre>\n\n<p>Note that I generated this assuming that diagonal moves have a cost of 1, just like cardinal moves. But you could change the <code>surrounding()</code> function to only consider cardinal moves and it wouldn't break anything - it would just change some numbers.</p>\n\n<p>And here is some code that prints those maps (but not side-by-side):</p>\n\n<pre><code>game_board = [\n line.strip() for line in \"\"\"\n # # # # # # # # # #\n . . . . . . . . . #\n . . P . . . # . . #\n . . # # # # # # . #\n . . # . . . . # . #\n . . # . M . . # . #\n . . # # # # . # . #\n . . . . . . . # . #\n # # # # # # # # # #\n \"\"\".split('\\n') if line.strip()\n]\n\nGame_map = [\n [ch for ch in row[::3]] for row in game_board\n]\n\ndef find_cell(m, value):\n \"\"\"Find a cell containing value in map m. Return row, col position.\"\"\"\n for r, row in enumerate(m):\n for c, cell in enumerate(row):\n if cell == value:\n return (r, c)\n\ndef make_distance_map(m, fill=-1):\n \"\"\"Make a distance map, filled with some number.\"\"\"\n nrows = len(m)\n ncols = len(m[0])\n\n return [[fill] * ncols for _ in range(nrows)]\n\ndef print_map(m, legend={}):\n for r, row in enumerate(m):\n for c, ch in enumerate(row):\n if (r,c) in legend:\n cell = legend[(r,c)]\n else:\n cell = legend.get(ch, ch)\n\n if isinstance(cell, str):\n cell = f\" {cell}\"\n else:\n cell = f\"{cell:2d}\"\n\n print(cell, end=' ')\n print()\n\ndef surrounding(row, col):\n \"\"\"Yield all valid surrounding map positions.\"\"\"\n\n min_r = 0 if row == 0 else row - 1\n max_r = row + 1 if row &lt; len(Game_map) - 1 else row\n\n min_c = 0 if col == 0 else col - 1\n max_c = col + 1 if col &lt; len(Game_map[0]) - 1 else col\n\n\n for srow, map_row in enumerate(Game_map[min_r:max_r+1], start=min_r):\n for scol, ch in enumerate(map_row[min_c:max_c+1], start=min_c):\n if (row, col) == (srow, scol):\n # Don't yield current position\n continue\n\n if ch in \"#\":\n # Don't yield wall positions\n continue\n\n yield srow, scol\n\ndef fill_distance_map(m, row, col, value):\n \"\"\"Fill a distance map with increasing values, starting at a point.\"\"\"\n if m[row][col] &lt;= value:\n return\n\n m[row][col] = value\n\n for new_pos in surrounding(row, col):\n fill_distance_map(m, *new_pos, value + 1)\n\nFILL=100_000\ndistance_map = make_distance_map(Game_map, fill=FILL)\nprint_map(Game_map)\nprint(\"\\n\\n\")\n\nplayer_pos = find_cell(Game_map, 'P')\nmonster_pos = find_cell(Game_map, 'M')\nfill_distance_map(distance_map, *player_pos, 0)\nprint_map(distance_map, legend={FILL:'#', player_pos:'P', monster_pos:'M'})\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:34:08.537", "Id": "213821", "ParentId": "213762", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T22:42:10.280", "Id": "213762", "Score": "1", "Tags": [ "python", "array" ], "Title": "Selecting lowest position from 'array'" }
213762
<p>I've been working on this one for a while. Took me a while to figure out all the logic rules for dates and months.</p> <p>The goal of this method is to return the number of years, months, days, hours, minutes, seconds, and milliseconds between two times. </p> <p>I'm going to be implementing this algorithm in a Xamarin app I'm making that shows an active countdown, but that's neither here nor there in terms of getting this coded properly.</p> <p>A few "business rules" I wanted to try to abide by.</p> <ol> <li>When two dates are an exact amount of time apart, express that in the return object. IE, 1/31/2019 to 1/31/2020 is 1 year. Not 11 months, 30 days. Likewise 3/15/2019 to 4/15/2019 is 1 month, not 31 days</li> <li><p>As this will be used in a countdown program, there should not be any "lost days" in the countdown. </p> <p>For example, when going from 02/27/2019 to 04/07/2019, the result should be counted as 1 month, 8 days (counting the days first), and not 1 month 11 days (counting the month first). </p> <p>The reason for this is that as time advances, going from 2/28/2019 to 03/01/2019 would result in an output of 1 month 10 days for the first date. But on the second date, it would result in 1 month 6 days which wouldn't make sense as you are losing a few days in the middle there.</p></li> <li><p>The return object is not bound by any calendar "business rules". Meaning a return object of 2 months and 30 days is valid. However, the number of days should never meet or exceed the number of days in the calendar month immediately following the start date. This is a product of the counting down of days to zero described above.</p></li> </ol> <p><strong>CODE</strong></p> <pre><code>/// &lt;summary&gt; /// Calculates the difference in years, months, days, hours, seconds, and milliseconds between a start date and time and end date and time. /// &lt;/summary&gt; /// &lt;param name="startDate"&gt;The start date and time&lt;/param&gt; /// &lt;param name="endDate"&gt;The end date and time&lt;/param&gt; /// &lt;returns&gt;A TimeRemaining object which represents the difference between the two times in years, months, days, hours, seconds, and milliseconds&lt;/returns&gt; /// &lt;remarks&gt;If startDate is greater than or equal to end date, returns 0 for all TimeRemaining fields&lt;/remarks&gt; public static TimeDifference SubtractDates(DateTime startDate, DateTime endDate) { if (startDate &lt;= endDate) { //identify median months between two dates List&lt;DateTime&gt; medianMonths = new List&lt;DateTime&gt;(); //start with the first calendar month after the start date int monthsIterator = 1; DateTime iterativeMonth = startDate.AddMonths(monthsIterator); //total full months (we are going to return this) int months = 0; //continue counting months until you reach or surpass the end date while (iterativeMonth &lt; endDate) { months++; monthsIterator++; //we use the iterator applied against the start month //to account for edge cases like a start date of 1/31/2019 and a //deadline of 3/31/2019. // //when adding "1 month" to 1/31/2019, c# will return 2/28/2019, so when you //iterate the next month after, it will be 3/28/2019 instead of 3/31/2019. iterativeMonth = startDate.AddMonths(monthsIterator); } //construct false "end date" with the same day of the month in the month immediately following the start date //get year and month of faux date int fauxIterator = 0; //this accounts for "lost month" when you have start days that are numerically larger than end days //example start: 02/27/2019; end: 04/07/2019 if (startDate.Day &gt; endDate.Day) { fauxIterator++; } // get the faux year and month. int fauxYear = startDate.AddMonths(fauxIterator).Year; int fauxMonth = startDate.AddMonths(fauxIterator).Month; //get the days in the faux month int fauxDaysInMonth = DateTime.DaysInMonth(fauxYear, fauxMonth); //for endDates that have a day value numerically larger than the number of days in a given month, //perform a "bonus" month to account for the month that is completely traversed // //example start: 02/27/2019; end: 04/07/2019 bool bonus = false; if (endDate.Day &gt; fauxDaysInMonth) { fauxIterator++; fauxYear = startDate.AddMonths(fauxIterator).Year; fauxMonth = startDate.AddMonths(fauxIterator).Month; bonus = true; } //reset faux days in month after first test fauxDaysInMonth = DateTime.DaysInMonth(fauxYear, fauxMonth); //get the faux date and total days between the start date //and the faux date // //this will include the traversed month if applicable DateTime faux = new DateTime(fauxYear, fauxMonth, endDate.Day, endDate.Hour, endDate.Minute, endDate.Second, endDate.Millisecond); //track the original faux day to handle 'lost days' if faux date is less than start date int originalFauxDay = faux.Day; //if faux is less than start date, advance the month to correct the days //this will only happen when fauxIterator == 0, but testing for //that introduces other problems for legitimate close dates if (faux &lt; startDate) { fauxIterator++; fauxYear = startDate.AddMonths(fauxIterator).Year; fauxMonth = startDate.AddMonths(fauxIterator).Month; //add the month to get the faux day as well. This is //important if working with an edge case like 01/31 int fauxDay = startDate.AddMonths(fauxIterator).Day; faux = new DateTime(fauxYear, fauxMonth, fauxDay, endDate.Hour, endDate.Minute, endDate.Second, endDate.Millisecond); } //if days were lost in the immediately preceeding if clause //correct for the lost days here by finding the number of lost days // //solves test case of //start: 1/31/2019 1200 //end: 3/31/2019 0000 int fauxCorrectionOffset = 0; if(originalFauxDay &gt; faux.Day) { fauxCorrectionOffset = originalFauxDay - faux.Day; } int days = 0; days = (faux - startDate).Days + fauxCorrectionOffset; //order is important, so if a traversed month was included, //remove the traversed month days first if (bonus) { //since the faux date is currently on the second month (first after the traversed one) //skip back to the traversed month to remove its days faux = faux.AddMonths(-1); fauxDaysInMonth = DateTime.DaysInMonth(faux.Year, faux.Month); days = days - fauxDaysInMonth; } //prepare to continue calculations with the original faux month //these two lines will only affect the outcome if a bonus (traversed) month was //included in the previous calculations faux = faux.AddMonths(1); fauxDaysInMonth = DateTime.DaysInMonth(faux.Year, faux.Month); //if endDate day is numerically higher than the number of days in the second month, //and the days remaining are more than are in the second faux month //remove the days of the second month if (endDate.Day &gt;= fauxDaysInMonth &amp;&amp; bonus &amp;&amp; days &gt;= fauxDaysInMonth) { days = days - fauxDaysInMonth; } //handles edge cases where a startDate and endDate are //an exact number of months or years apart // //Ticks is also a part of the criteria so that when the dates are the same, //months is not falsely iterated. if ((days == 0) &amp;&amp; ((endDate - startDate).Hours == 0) &amp;&amp; ((endDate - startDate).Minutes == 0) &amp;&amp; ((endDate - startDate).Seconds == 0) &amp;&amp; ((endDate - startDate).Milliseconds == 0) &amp;&amp; ((endDate - startDate).Ticks &gt; 0)) { months++; } //integer division to get number of whole years int years = months / 12; //mod months to get number of total months after years months = months % 12; //use timespan against original dates to //compute hours, minutes, seconds, and milliseconds TimeSpan pureDiff = endDate - startDate; //save days in 'countdown month' //save the days in month. This is what the output is counting down from int daysInCountdownMonth = 0; if (startDate.Day &gt;= endDate.Day &amp;&amp; !(days == 0)) { daysInCountdownMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month); } else { daysInCountdownMonth = DateTime.DaysInMonth(startDate.AddMonths(-1).Year, startDate.AddMonths(-1).Month); if(daysInCountdownMonth &lt; endDate.Day) { //correct with offset //this should account for situations where the end date day is numerically larger //than the number of days in the preceeding month int offset = endDate.Day - daysInCountdownMonth; daysInCountdownMonth = daysInCountdownMonth + offset; } } return new TimeDifference(years, months, days, pureDiff.Hours, pureDiff.Minutes, pureDiff.Seconds, pureDiff.Milliseconds, daysInCountdownMonth); } else { return new TimeDifference(0, 0, 0, 0, 0, 0, 0, 0); } } </code></pre> <p>By request, here is the code for the TimeRemaining class. Very straightforward, but not nearly as well documented.</p> <pre><code>/// &lt;summary&gt; /// Class that represents the difference between two times /// &lt;/summary&gt; public class TimeDifference : IEquatable&lt;TimeDifference&gt; { private int _days; private int _hours; private int _millliseconds; private int _minutes; private int _months; private int _seconds; private int _years; private int _daysInMonth; private const int DAYS_IN_WEEK = 7; public TimeDifference() { this.Years = 0; this.Months = 0; this.Days = 0; this.Hours = 0; this.Minutes = 0; this.Seconds = 0; this.Milliseconds = 0; this.DaysInMonth = 0; } public TimeDifference(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds, int daysInMonth) { this.Years = years; this.Months = months; this.Days = days; this.Hours = hours; this.Minutes = minutes; this.Seconds = seconds; this.Milliseconds = milliseconds; this.DaysInMonth = daysInMonth; } public static bool operator ==(TimeDifference left, TimeDifference right) { bool status = false; if (left.Years == right.Years &amp;&amp; left.Months == right.Months &amp;&amp; left.Days == right.Days &amp;&amp; left.Hours == right.Hours &amp;&amp; left.Minutes == right.Minutes &amp;&amp; left.Seconds == right.Seconds &amp;&amp; left.Milliseconds == right.Milliseconds) { status = true; } return status; } public static bool operator !=(TimeDifference left, TimeDifference right) { bool status = false; if (left.Years != right.Years || left.Months != right.Months || left.Days != right.Days || left.Hours != right.Hours || left.Minutes != right.Minutes || left.Seconds != right.Seconds || left.Milliseconds != right.Milliseconds) { status = true; } return status; } public bool Equals(TimeDifference other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return this.Years.Equals(other.Years) &amp;&amp; this.Months.Equals(other.Months) &amp;&amp; this.Days.Equals(other.Days) &amp;&amp; this.Hours.Equals(other.Hours) &amp;&amp; this.Minutes.Equals(other.Minutes) &amp;&amp; this.Seconds.Equals(other.Seconds) &amp;&amp; this.Milliseconds.Equals(other.Milliseconds); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() &amp;&amp; Equals((TimeDifference)obj); } public override int GetHashCode() { unchecked { int hashCode = Years.GetHashCode(); hashCode = (hashCode * 397) ^ Months.GetHashCode(); hashCode = (hashCode * 397) ^ Days.GetHashCode(); hashCode = (hashCode * 397) ^ Hours.GetHashCode(); hashCode = (hashCode * 397) ^ Minutes.GetHashCode(); hashCode = (hashCode * 397) ^ Seconds.GetHashCode(); hashCode = (hashCode * 397) ^ Milliseconds.GetHashCode(); hashCode = (hashCode * 397) ^ DaysInMonth.GetHashCode(); return hashCode; } } public override string ToString() { return Years + "y " + Months + "m " + Days + "d " + Hours + "h " + Minutes + "min " + Seconds + "s " + Milliseconds.ToString("000") + "ms"; } public int Hours { get { return this._hours; } set { this._hours = value; } } public int Milliseconds { get { return this._millliseconds; } set { this._millliseconds = value; } } public int Minutes { get { return this._minutes; } set { this._minutes = value; } } public int Months { get { return this._months; } set { this._months = value; } } public int Days { get { return this._days; } set { this._days = value; } } public int DaysInMonth { get { return this._daysInMonth; } set { this._daysInMonth = value; } } public int Weeks { get { return Days / DAYS_IN_WEEK; } } public int DaysRemainder { get { return Days % DAYS_IN_WEEK; } } public int Seconds { get { return this._seconds; } set { this._seconds = value; } } public int Years { get { return this._years; } set { this._years = value; } } } </code></pre> <p><strong>Tests and Edge Cases</strong></p> <p>I have also written unit tests which verify the code is working in the following scenarios. If you can think of any edge cases that will break the algorithm, please post them!</p> <ul> <li>Start Date: 02/27/2019<br/> End Date: 04/07/2019<br/> Result: 1 month, 8 days</li> <li>Start Date: 02/27/2020 <em>(accounts for leap year)</em><br/> End Date: 04/07/2020<br/> Result: 1 month, 9 days</li> <li>Start Date: 03/31/2019<br/> End Date: 03/31/2019<br/> Result: 0 for all</li> <li>Start Date: 03/31/2020<br/> End Date: 03/31/2020<br/> Result: 0 for all</li> <li>Start Date: 01/31/2019<br/> End Date: 03/31/2020<br/> Result: 1 year, 2 months</li> <li>Start Date: 02/1/2019<br/> End Date: 03/31/2020<br/> Result: 1 year, 1 month, 30 days</li> <li>Start Date: 02/2/2019<br/> End Date: 03/31/2020<br/> Result: 1 year, 1 month, 29 days</li> <li>Start Date: 02/3/2019<br/> End Date: 03/31/2020<br/> Result: 1 year, 1 month, 28 days</li> <li>Start Date: 02/4/2019<br/> End Date: 03/31/2020<br/> Result: 1 year, 1 month, 27 days</li> <li>Start Date: 03/31/2019<br/> End Date: 03/31/2020<br/> Result: 1 year</li> <li>Start Date: 04/1/2019<br/> End Date: 03/31/2020<br/> Result: 11 months, 30 days</li> <li>Start Date: 02/28/2020<br/> End Date: 02/28/2020<br/> Result: 0 for all</li> <li>Start Date: 02/29/2020<br/> End Date: 02/29/2020<br/> Result: 0 for all</li> <li>Start Date: 03/15/2019<br/> End Date: 04/15/2019<br/> Result: 1 month</li> <li>Start Date &amp; Time: 10/19/2019 11:00 am <br/> End Date &amp; Time: 10/20/2019 11:00 am <br/> Result: 1 day</li> <li>Start Date &amp; Time: 2/19/2019 11:00 am <br/> End Date &amp; Time: 10/20/2019 11:00 am <br/> Result: 8 months, 1 day</li> <li>Start Date &amp; Time: 2/19/2019 10:00 am <br/> End Date &amp; Time: 10/20/2019 11:00 am <br/> Result: 8 months, 1 day, 1 hour</li> <li>Start Date &amp; Time: 2/20/2019 11:30 am <br/> End Date &amp; Time: 10/20/2019 11:00 am <br/> Result: 7 months, 27 days, 23 hours, 30 minutes</li> </ul> <p>I welcome any and all feedback! Especially if you see logical flaws or edge cases I haven't accounted for. However, I'm not terribly concerned with dates in the extreme past or future. Most everything I'm dealing with here will be in the 20th-21st century.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T01:05:26.867", "Id": "413625", "Score": "2", "body": "Can you provide the code for the `TimeRemaining` class or struct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:04:20.437", "Id": "413672", "Score": "2", "body": "FYI https://nodatime.org/ is what I would recommend for such scenarios, because it takes into account all kinds of odd rules etc. https://nodatime.org/2.4.x/userguide/arithmetic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:45:51.397", "Id": "413725", "Score": "0", "body": "@RickDavin - See Edit #3." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T04:04:15.240", "Id": "413793", "Score": "0", "body": "@RickDavin - TimeRemaining is now TimeDifference. See changes in Edit 4." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T04:06:19.337", "Id": "413794", "Score": "3", "body": "Appending incremental edits just confuses the question. Since nobody has posted an answer yet, you can just edit the code to reflect your latest version. (Alternatively, you could post a self-answer instead, but then you would not be allowed to edit the question anymore.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T09:11:51.247", "Id": "413810", "Score": "3", "body": "You have made so many incremental edits that I no longer can follow your question..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:54:40.280", "Id": "413860", "Score": "0", "body": "@200_success - you are both right that I've gotten carried away with the edits. If you still care to take a look, the code in the OP is up to date and what I'm really looking for review on. The edits just summarize changes I've made to the OP. Sorry about that. If no one provides an answer after a few more days I'll answer the question myself and move all the edits in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:54:51.890", "Id": "413861", "Score": "0", "body": "@t3chb0t - see previous comment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T15:32:31.243", "Id": "413867", "Score": "1", "body": "I've inlined to make the post legible. It would still be an improvement to replace the weird-locale text descriptions of the unit tests with actual unit test code (in particular, so that people suggesting changes can test them first)." } ]
[ { "body": "<blockquote>\n<pre><code>public static TimeDifference SubtractDates(DateTime startDate, DateTime endDate)\n{\n if (startDate &lt;= endDate)\n {\n ... snip 170 lines ...\n }\n else\n {\n return new TimeDifference(0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Apart from the fact that 177 lines is too long for a single method, it's cleaner to handle input validation directly at the top, not indent the main flow and then respond to the validation failure at the bottom. (Also, the test is a bit too conservative). Try:</p>\n\n<blockquote>\n<pre><code>public static TimeDifference SubtractDates(DateTime startDate, DateTime endDate)\n{\n if (startDate &gt;= endDate)\n {\n return new TimeDifference(0, 0, 0, 0, 0, 0, 0, 0);\n }\n\n ... snip 170 lines ...\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code> //identify median months between two dates\n List&lt;DateTime&gt; medianMonths = new List&lt;DateTime&gt;();\n</code></pre>\n</blockquote>\n\n<p>Huh? That variable doesn't seem to be touched anywhere else.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> //start with the first calendar month after the start date\n int monthsIterator = 1;\n DateTime iterativeMonth = startDate.AddMonths(monthsIterator);\n\n //total full months (we are going to return this)\n int months = 0;\n\n //continue counting months until you reach or surpass the end date\n while (iterativeMonth &lt; endDate)\n {\n months++;\n monthsIterator++;\n\n //we use the iterator applied against the start month \n //to account for edge cases like a start date of 1/31/2019 and a \n //deadline of 3/31/2019.\n //\n //when adding \"1 month\" to 1/31/2019, c# will return 2/28/2019, so when you \n //iterate the next month after, it will be 3/28/2019 instead of 3/31/2019.\n iterativeMonth = startDate.AddMonths(monthsIterator);\n }\n</code></pre>\n</blockquote>\n\n<p>Two things:</p>\n\n<ol>\n<li>What's the point of <code>monthsIterator</code>? It seems to me that you could remove it and just use <code>months + 1</code> in its place.</li>\n<li>Why work forwards? Given the \"lost days\" business rule, it seems to me to be far more logical to work backwards.</li>\n</ol>\n\n<hr>\n\n<p>That's as far as I can get before getting completely confused and giving up on understanding the code. I might be able to get further if it were refactored into short self-contained methods and if the comments explained the high-level \"Why?\" rather than the low-level \"What?\".</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class TimeDifference : IEquatable&lt;TimeDifference&gt;\n{\n private int _days;\n private int _hours;\n ... etc ...\n\n public int Hours\n {\n get\n {\n return this._hours;\n }\n set\n {\n this._hours = value;\n }\n }\n\n ... etc ...\n</code></pre>\n</blockquote>\n\n<p>I can't see any reason not to use automatic properties - and if you use Visual Studio, it's probably telling you the same thing.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public TimeDifference()\n {\n this.Years = 0;\n this.Months = 0;\n this.Days = 0;\n this.Hours = 0;\n this.Minutes = 0;\n this.Seconds = 0;\n this.Milliseconds = 0;\n this.DaysInMonth = 0;\n }\n</code></pre>\n</blockquote>\n\n<p>This is equivalent to</p>\n\n<pre><code> public TimeDifference()\n {\n }\n</code></pre>\n\n<p>which is somewhat easier to read.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static bool operator ==(TimeDifference left, TimeDifference right)\n {\n bool status = false;\n if (left.Years == right.Years &amp;&amp;\n left.Months == right.Months &amp;&amp;\n left.Days == right.Days &amp;&amp;\n left.Hours == right.Hours &amp;&amp;\n left.Minutes == right.Minutes &amp;&amp;\n left.Seconds == right.Seconds &amp;&amp;\n left.Milliseconds == right.Milliseconds)\n {\n status = true;\n }\n return status;\n }\n</code></pre>\n</blockquote>\n\n<p>This is missing <code>null</code> checks. Also, I find it easier to read</p>\n\n<pre><code>return boolean-expression;\n</code></pre>\n\n<p>than</p>\n\n<pre><code>var result = false;\nif (boolean-expression)\n{\n result = true;\n}\nreturn result;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public static bool operator !=(TimeDifference left, TimeDifference right)\n {\n bool status = false;\n if (left.Years != right.Years ||\n left.Months != right.Months ||\n left.Days != right.Days ||\n left.Hours != right.Hours ||\n left.Minutes != right.Minutes ||\n left.Seconds != right.Seconds ||\n left.Milliseconds != right.Milliseconds)\n {\n status = true;\n }\n return status;\n }\n</code></pre>\n</blockquote>\n\n<p>Duplicating <code>==</code> is a potential source of bugs. Far better to write</p>\n\n<pre><code> public static bool operator !=(TimeDifference left, TimeDifference right) =&gt; !(left == right);\n</code></pre>\n\n<p>In fact, in my opinion it was an error in the language design that <code>==</code> and <code>!=</code> are both required to be implemented: I think that only <code>==</code> should be required, and <code>!=</code> should always be converted into <code>!(... == ...)</code> by the compiler.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool Equals(TimeDifference other)\n {\n if (ReferenceEquals(null, other))\n {\n return false;\n }\n if (ReferenceEquals(this, other))\n {\n return true;\n }\n\n return this.Years.Equals(other.Years)\n &amp;&amp; this.Months.Equals(other.Months)\n &amp;&amp; this.Days.Equals(other.Days)\n &amp;&amp; this.Hours.Equals(other.Hours)\n &amp;&amp; this.Minutes.Equals(other.Minutes)\n &amp;&amp; this.Seconds.Equals(other.Seconds)\n &amp;&amp; this.Milliseconds.Equals(other.Milliseconds);\n }\n</code></pre>\n</blockquote>\n\n<p>This is the <em>third</em> essential copy of the same code. Don't repeat yourself.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public override bool Equals(object obj)\n {\n if (ReferenceEquals(null, obj))\n {\n return false;\n }\n if (ReferenceEquals(this, obj))\n {\n return true;\n }\n\n return obj.GetType() == GetType() &amp;&amp; Equals((TimeDifference)obj);\n }\n</code></pre>\n</blockquote>\n\n<p><code>GetType()</code> is a bit over the top IMO.</p>\n\n<pre><code>public override bool Equals(object obj) =&gt; Equals(obj as TimeDifference);\n</code></pre>\n\n<p>is all you really need. If you're worried about someone making a subclass which breaks the symmetry of <code>Equals</code>, make the class <code>sealed</code>. (In fact, that's probably a good idea anyway: it's a strong hint to the compiler).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public override int GetHashCode()\n {\n unchecked\n {\n int hashCode = Years.GetHashCode();\n hashCode = (hashCode * 397) ^ Months.GetHashCode();\n hashCode = (hashCode * 397) ^ Days.GetHashCode();\n hashCode = (hashCode * 397) ^ Hours.GetHashCode();\n hashCode = (hashCode * 397) ^ Minutes.GetHashCode();\n hashCode = (hashCode * 397) ^ Seconds.GetHashCode();\n hashCode = (hashCode * 397) ^ Milliseconds.GetHashCode();\n hashCode = (hashCode * 397) ^ DaysInMonth.GetHashCode();\n return hashCode;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>I'm surprised that this should require <code>unchecked</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:18:36.090", "Id": "413869", "Score": "0", "body": "Lots of great content here. Thank you! I'm going to look over all your critiques and have already implemented a few!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:21:45.953", "Id": "413870", "Score": "0", "body": "Do you have any suggestions about what to split out into extra methods? I'm not opposed to the idea, I just don't know where it makes sense to do so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:58:51.333", "Id": "413876", "Score": "0", "body": "Pick the comment which covers the most lines of code (perhaps \"*construct false \"end date\" with the same day of the month in the month immediately following the start date*\"?). That's probably a method... Alternatively, if you rework in line with my observation about going backwards rather than forwards, the structure might be something like `diff.Years = ExtractYears(startDate, endDate); endDate -= TimeSpan.FromYears(diff.Years); diff.Months = ExtractMonths(startDate, endDate); endDate = ...`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T15:58:34.807", "Id": "213971", "ParentId": "213767", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:01:34.727", "Id": "213767", "Score": "5", "Tags": [ "c#", "algorithm", "datetime", "timer" ], "Title": "Algorithm to find the number of years, months, days, etc between two dates" }
213767
<p>I have written a python script using regex to extrapolate a poorly formatted text file data table into an actual data table. I am currently printing the output using . C:\my file location\file.csv in the command prompt. Is there a better way to cause my script to run for an entire directory of files and programmatically output each to a .csv file?</p> <p>Here is the code:</p> <pre><code>import re data = open('C:\file.txt', 'rU') output = [['DEALER CODE', 'DEALER NAME', 'DEALER PHONE', 'DATE', 'CHG DESCRIPTION', 'VIN', 'CURRENT', 'OVER 30-DAYS', 'OVER 60-DAYS', 'OVER 90-DAYS', 'OVER 120-DAYS', 'AGE']] for line in data: dealer_code = re.search(r'(\w\d\d\d\d\d )', line) dealer_code_phone_search = re.search(r'(\d\d\d-\d\d\d-\d\d\d\d)', line) if dealer_code and "/" not in line: line = line.replace('\n','') dealer_code_number = line.split()[0] if dealer_code_phone_search: dealer_code_phone = dealer_code_phone_search.group(0) dealer_name = ''.join(line.split(dealer_code_number)[1:]).strip().split(dealer_code_phone)[0].strip() else: dealer_code_phone = '' dealer_name = ''.join(line.split(dealer_code_number)[1:]).strip() elif "/" in line: line = line.replace('\n','') vin = re.search(r'(\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w)', line) if vin: date = line.split(vin.group(0))[0].split()[0] descp = ' '.join(line.split(vin.group(0))[0].split()[1:]) rest = line.split(vin.group(0))[1].split() vin = vin.group(0) new_line = [dealer_code_number, dealer_name, dealer_code_phone, date, descp, vin] for i in rest: new_line.append(i) output.append(new_line) for line in output: print(','.join(line)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:15:50.480", "Id": "413553", "Score": "1", "body": "There are some pieces of your code that are either really clever, or really unnecessary. Can you show a few examples of the input data?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:48:06.007", "Id": "213770", "Score": "3", "Tags": [ "python", "regex", "csv" ], "Title": "Generate CSV from multiple files on Regex Python Output" }
213770
<p><strong>Context:</strong> I'm currently toying with the <a href="https://developers.google.com/maps/documentation/geocoding/start" rel="nofollow noreferrer">Google Geocode API</a> to break down address strings into a more machine-friendly format. The problem is that neither the user input or API output are 100% consistent, and I would receive less entries in the JSON response than expected. For example, requesting "Times Square NY" gives me 6 address components</p> <pre><code>"address_components" : [ { "long_name" : "Manhattan", "short_name" : "Manhattan", "types" : [ "political", "sublocality", "sublocality_level_1" ] }, { "long_name" : "New York", "short_name" : "New York", "types" : [ "locality", "political" ] }, { "long_name" : "New York County", "short_name" : "New York County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "New York", "short_name" : "NY", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "10036", "short_name" : "10036", "types" : [ "postal_code" ] } </code></pre> <p>But, for some reason, "Times Circle NY" gives me 8 address components (notice, for example, how "Times Square NY" does not contain a <code>route</code> entry):</p> <pre><code>{ "long_name" : "10", "short_name" : "10", "types" : [ "street_number" ] }, { "long_name" : "Columbus Circle", "short_name" : "Columbus Cir", "types" : [ "route" ] }, { "long_name" : "Manhattan", "short_name" : "Manhattan", "types" : [ "political", "sublocality", "sublocality_level_1" ] }, { "long_name" : "New York", "short_name" : "New York", "types" : [ "locality", "political" ] }, { "long_name" : "New York County", "short_name" : "New York County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "New York", "short_name" : "NY", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "10019", "short_name" : "10019", "types" : [ "postal_code" ] } </code></pre> <p><strong>My code:</strong> To work with the JSON in a more reasonable format, for ex. getting rid of the <code>short_name</code> or accessing a field by component type, I've written an object constructor that goes like this:</p> <pre><code>class Address { constructor(googleJson) { try { this.state= googleJson["results"][0]["address_components"].filter(el =&gt; JSON.stringify(el["types"]) === JSON.stringify(["administrative_area_level_1", "political"]))[0]["short_name"]; } catch (e) { this.state= ""; } try { this.city= googleJson["results"][0]["address_components"].filter(el =&gt; JSON.stringify(el["types"]) === JSON.stringify(["administrative_area_level_2", "political"]))[0]["long_name"]; } catch (e) { this.city= ""; } try { this.lat = googleJson["results"][0]["geometry"]["location"]["lat"].toString(); } catch (e) { this.lat = ""; } // And so on... </code></pre> <p>And it works perfectly fine, does its job, but half of my code is just these try/catch pairs. Is there any smarter way to attempt to read multiple potentially empty JSON fields without so much code repetition?</p> <p>Also, since I'm here, I found the filter I wrote inside each try/catch to be quite legible, but I fear the constructor as a whole would be <span class="math-container">\$O(n \times m)\$</span>. What other way could I read the JSON in <span class="math-container">\$O(n + m)\$</span> and maintain legibility?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T23:52:50.857", "Id": "213771", "Score": "2", "Tags": [ "javascript", "json", "google-maps" ], "Title": "Parsing potentially nonexistant JSON fields in JavaScript" }
213771
<p>I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!</p> <pre><code>import hashlib import mysql.connector from tkinter import * from tkinter import messagebox from cryptography.fernet import Fernet chat = Tk() #Api I am using to create the GUI for the application #Connect to MySQL database try: loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file retrivedKey = loginFRetrieve.read() loginFRetrieve.close() loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials retrivedLC = loginFRetrieve.read() loginFRetrieve.close() cipher = Fernet(retrivedKey) retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file retrivedLC = retrivedLC.decode('utf-8') lC = retrivedLC.split() mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3]) del(lC) except mysql.connector.Error as err: chat.withdraw() messagebox.showerror("Database Error", "Failed to connect to database") exit() mycursor = mydb.cursor() #hashPass hashes and returns a string of characters using SHA-256 algorithm def hashPass(hP): shaSignature = \ hashlib.sha256(hP.encode()).hexdigest() return shaSignature #userExists checks a database too see if username exists in the database def userExists(userName): mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName) userResult = mycursor.fetchall() if userResult: return True return False #Creates a new user in the connected SQL database. def newUser(nU, nP): if userExists(nU) == False: mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU) mycursor.fetchall() r = hashPass(nP) sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)" val = (nU, r) mycursor.execute(sql, val) mydb.commit() chat.title(string="User created") else: messagebox.showwarning("User Creation Error", "User already exists") #Checks the connected SQL database for an existing user. def existingUser(uN, pW): if userN.get() != "": if userExists(uN) == True: encryptedPass = hashPass(pW) mycursor.execute("SELECT * FROM logins") passResult = mycursor.fetchall() for row in passResult: if row[1] == uN and row[2] == encryptedPass: chat.title(string="Login Successful!") elif row[1] == uN and row[2] != encryptedPass: messagebox.showerror("Login Error", "Password does not match our records") else: messagebox.showerror("Login Error", "User does not exist") else: messagebox.showwarning("Login Error", "Please enter a username") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T07:24:25.397", "Id": "413505", "Score": "0", "body": "Does this code work? What's `userN`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:15:36.853", "Id": "413536", "Score": "0", "body": "@200_success I left a lot of the code for the GUI elements out. The userN is the text from the user name text box of the GUI." } ]
[ { "body": "<h3>Encryption isn't Hashing</h3>\n<pre><code>encryptedPass = hashPass(pW)\n</code></pre>\n<p>You're not encrypting the password, you're hashing it.</p>\n<p>For passwords you should not be hashing them with the SHA2 family. Instead, use <a href=\"https://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">bcrypt</a>.</p>\n<h3>Sanitize input</h3>\n<p>From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example <code>userExists()</code> and the first query in <code>newUser()</code>. Instead, you're using simple string formatting to substitute values <strong>directly</strong>.</p>\n<p>You should be passing the variables as arguments to <a href=\"https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html\" rel=\"nofollow noreferrer\"><code>execute()</code></a> every time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T01:44:51.547", "Id": "413488", "Score": "0", "body": "Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T01:59:05.553", "Id": "413489", "Score": "0", "body": "@Mr.clean I am not very familiar with Python. It looks _okay_, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could `del` other variables used in it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:18:30.510", "Id": "413521", "Score": "0", "body": "Please note that while bcrypt is better than plain SHA256 hashing (as is done now), Argon2 would be a more modern choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:12:30.437", "Id": "413535", "Score": "0", "body": "@SEJPM what’s your thoughts on my code from a security perspective? Also what makes sha256 insecure for password hashing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:53:29.630", "Id": "413562", "Score": "0", "body": "@Mr.clean [this answer](https://security.stackexchange.com/a/31846/71460) should explain password-hashing. It's a bit dated, so doesn't talk about Argon2 yet, but is otherwise really good. The only other interesting thing I could spot was the code putting the credential's key _unencrypted in a file right next to the ciphertext_." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T01:24:48.280", "Id": "213776", "ParentId": "213774", "Score": "2" } } ]
{ "AcceptedAnswerId": "213776", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T00:38:57.977", "Id": "213774", "Score": "1", "Tags": [ "python", "python-3.x", "mysql", "cryptography", "authentication" ], "Title": "Using encryption/hashing to create a secure login" }
213774
<p>I have encountered to this question and applied a brute force algorithm off top of my head and couldn't find a better optimized solution.</p> <p>I was hoping I could get some insight to implement a better optimized code in terms of complexity. My solution has <span class="math-container">\$O(n^2)\$</span> time and space complexity.</p> <pre><code>class Solution: def longestPalindrome(self, s: 'str') -&gt; 'str': if s=="": return "" else: ## Find all the substrings arr=[] for i in range(len(s)): char = s[i] arr.append(char) for j in range(i+1, len(s)-1): char+=s[j] arr.append(char) ##Find the palindrome with a longest length max_length = 0 for j in range(len(arr)): if self.isPalindrome(arr[j]): if len(arr[j]) &gt; max_length: max_length = len(arr[j]) index = arr[j] return index def isPalindrome(self,s:'str')-&gt;'str': if s == s[::-1]: return True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T02:07:25.300", "Id": "413490", "Score": "1", "body": "For a linear search of the [longest palindromic substring](https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher.27s_algorithm), reference [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher.27s_algorithm)." } ]
[ { "body": "<p>As mentioned in the comments, you can check the Manacher's algorithm. Here's the link for python code of the algorithm: <a href=\"https://zkf85.github.io/2019/03/26/leetcode-005-longest-palindrome#approach-5-manachers-algorithm-on\" rel=\"nofollow noreferrer\">https://zkf85.github.io/2019/03/26/leetcode-005-longest-palindrome#approach-5-manachers-algorithm-on</a></p>\n\n<p>This is the solution mentioned on the above link in python:</p>\n\n<pre><code>class Solution5:\ndef longestPalindrome(self, s: str) -&gt; str:\n N = len(s) \n if N &lt; 2: \n return s\n N = 2*N+1 # Position count \n L = [0] * N \n L[0] = 0\n L[1] = 1\n C = 1 # centerPosition \n R = 2 # centerRightPosition \n i = 0 # currentRightPosition \n iMirror = 0 # currentLeftPosition \n maxLPSLength = 0\n maxLPSCenterPosition = 0\n start = -1\n end = -1\n diff = -1\n\n for i in range(2, N): \n # get currentLeftPosition iMirror for currentRightPosition i \n iMirror = 2*C-i \n L[i] = 0\n diff = R - i \n # If currentRightPosition i is within centerRightPosition R \n if diff &gt; 0: \n L[i] = min(L[iMirror], diff) \n\n # Attempt to expand palindrome centered at currentRightPosition i \n # Here for odd positions, we compare characters and \n # if match then increment LPS Length by ONE \n # If even position, we just increment LPS by ONE without \n # any character comparison \n try:\n while ((i + L[i]) &lt; N and (i - L[i]) &gt; 0) and \\ \n (((i + L[i] + 1) % 2 == 0) or \\ \n (s[(i + L[i] + 1) // 2] == s[(i - L[i] - 1) // 2])): \n L[i]+=1\n except Exception as e:\n pass\n\n if L[i] &gt; maxLPSLength: # Track maxLPSLength \n maxLPSLength = L[i] \n maxLPSCenterPosition = i \n\n # If palindrome centered at currentRightPosition i \n # expand beyond centerRightPosition R, \n # adjust centerPosition C based on expanded palindrome. \n if i + L[i] &gt; R: \n C = i \n R = i + L[i] \n\n start = (maxLPSCenterPosition - maxLPSLength) // 2\n end = start + maxLPSLength - 1\n return s[start:end+1]\n</code></pre>\n\n<p>The above approach is the most optimized approach and it's time complexity is O(n) which I think is the best.</p>\n\n<p>I hope this helps you!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-05T23:41:48.870", "Id": "443062", "Score": "0", "body": "Welcome to Code Review! A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](https://meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted](https://codereview.stackexchange.com/help/deleted-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-17T11:57:16.860", "Id": "445611", "Score": "0", "body": "Fix indentation" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-05T23:20:45.647", "Id": "227542", "ParentId": "213775", "Score": "1" } }, { "body": "<h1>Unnecessary <code>else</code> after <code>return</code></h1>\n\n<p>In the body of an <code>if</code>, if you end up returning something in that body, an <code>else</code> is not required. A return will exit the body of the function, so the code in the <code>else</code> won't be run. So, you can simply move the code in the <code>else</code> to the outside, after the <code>if</code>. This may have been confusing, but take a look at the updated code to see what I'm talking about.</p>\n\n<h1><code>enumerate()</code></h1>\n\n<p>Instead of using <code>range(len())</code>, use <code>enumerate()</code>. This will allow you to access both the index and the value at that position, and <code>enumerate</code> works for other iterables as well. It's useful here because instead of writing <code>arr[j]</code> over and over, you can simply write <code>value</code>, which is the value at <code>arr[j]</code>.</p>\n\n<h1><code>_</code> for unused loop variables</h1>\n\n<p>Also touching on <code>enumerate</code>- When you only want to use one of the values (in your code, you have both cases present), use an <code>_</code> in that place. This indicates to you and other readers that that variable is to be ignored, and isn't necessary.</p>\n\n<h1>Parameter Spacing</h1>\n\n<p>When using <code>:</code> in parameters, make sure there is <em>exactly one space</em> after the <code>:</code>.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>Make sure to space out your operators when assigning and performing arithmetic on variables. It makes it much easier to read, and looks nicer.</p>\n\n<h1><code>return True</code></h1>\n\n<p>Instead of explicitly returning <code>true</code> if the <code>if</code> condition is true, simply return that condition. It will return the boolean value that is returned from that condition.</p>\n\n<h1>function_naming</h1>\n\n<p>I know you can't change the function names (assuming this is coming from a code challenge website), but remember that method names are to be in <code>snake_case</code>, not <code>camelCase</code> or <code>PascalCase</code>. This is in reference to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP-8 Method Naming Guidelines</a>. Thanks to <a href=\"https://codereview.stackexchange.com/users/120114/s%E1%B4%80%E1%B4%8D-on%E1%B4%87%E1%B4%8C%E1%B4%80\">@SᴀᴍOnᴇᴌᴀ</a> for pointing this out to me.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>class Solution:\n\n def longestPalindrome(self, s: 'str') -&gt; 'str':\n if s == \"\":\n return \"\"\n ## Find all the substrings\n arr = []\n for i, value in enumerate(s):\n char = value\n arr.append(char)\n for j in range(i + 1, len(s) - 1):\n char += s[j]\n arr.append(char)\n\n ##Find the palindrome with a longest length\n max_length = 0\n for _, value in enumerate(arr):\n if self.isPalindrome(value):\n if len(value) &gt; max_length:\n max_length = len(value)\n index = value\n return index\n\n\n def isPalindrome(self, s: 'str')-&gt;'str':\n return s == s[::-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T06:16:53.560", "Id": "445357", "Score": "0", "body": "“_method names are to be in `snake_case`_” do you mean idiomatic python, e.g. per the [PEP 8 style guide](https://www.python.org/dev/peps/pep-0008/#id45)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T06:49:28.443", "Id": "445359", "Score": "0", "body": "Yes @SᴀᴍOnᴇᴌᴀ, many of my suggestions were based off that guide, and some other practices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T18:38:52.160", "Id": "445490", "Score": "0", "body": "Okay would you mind updating your statement, to be explicit about what is valid verses what is idiomatic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T19:41:38.303", "Id": "445496", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ Updated accordingly. Thanks again." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-06T00:37:44.693", "Id": "227545", "ParentId": "213775", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T01:01:01.043", "Id": "213775", "Score": "4", "Tags": [ "python", "algorithm", "interview-questions", "palindrome" ], "Title": "Longest Palindromic Substring better approach" }
213775
<p>I'm a beginner in programming and I would like to have feedback and tips to improve. He's a simple command line program. It's a Rock, Paper, Scissors game.</p> <p>I guess I could use an enum for the "Attack", but I don't know how to use it with cout after that...</p> <p>Thanks!</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; using namespace std; enum class Result { win = 1, loss = -1, tie = 0 }; string ResultToString(Result result) { switch (result) { case Result::win: return "WIN!"; case Result::loss: return "LOSS!"; default: return "TIE!"; } } string DeterminePlay(char playAbbreviation) { if (playAbbreviation == 'r') { return "Rock"; } else if (playAbbreviation == 'p') { return "Paper"; } else { return "Scissors"; } } Result DetermineResult(char playerPlay, char computerPlay) { if (playerPlay == 'r' &amp;&amp; computerPlay == 's') { return Result::win; } else if (playerPlay == 'p' &amp;&amp; computerPlay == 'r') { return Result::win; } else if (playerPlay == 's' &amp;&amp; computerPlay == 'p') { return Result::win; } else if (playerPlay == 's' &amp;&amp; computerPlay == 'r') { return Result::loss; } else if (playerPlay == 'r' &amp;&amp; computerPlay == 'p') { return Result::loss; } else if (playerPlay == 'p' &amp;&amp; computerPlay == 's') { return Result::loss; } else { return Result::tie; } } int GenerateRandomNumber(int min, int max) { srand((int)time(0)); int number{(rand() % max) + min}; return number; } char GenerateComputerPlay() { char computerPlay{}; int number{GenerateRandomNumber(1, 3)}; switch (number) { case 1: computerPlay = 'r'; break; case 2: computerPlay = 'p'; break; default: computerPlay = 's'; } return computerPlay; } int main() { setlocale(LC_ALL, ""); char play{'y'}; while (play == 'y') { char computerPlay{}; char playerPlay{}; cout &lt;&lt; "--- Rock, Paper, Scissors ---" &lt;&lt; endl &lt;&lt; endl; while (playerPlay != 'r' &amp;&amp; playerPlay != 'p' &amp;&amp; playerPlay != 's') { cout &lt;&lt; "Enter a choice : (R)ock, (P)aper, (S)cissors : "; cin &gt;&gt; playerPlay; playerPlay = tolower(playerPlay); } cout &lt;&lt; endl &lt;&lt; "You played " &lt;&lt; DeterminePlay(playerPlay) &lt;&lt; endl; computerPlay = GenerateComputerPlay(); cout &lt;&lt; "The computer played " &lt;&lt; DeterminePlay(computerPlay) &lt;&lt; endl; Result result{DetermineResult(playerPlay, computerPlay)}; cout &lt;&lt; "It's a " &lt;&lt; ResultToString(result) &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Play again?" &lt;&lt; endl &lt;&lt; "(Y)es" &lt;&lt; endl &lt;&lt; "(N)o" &lt;&lt; endl; cin &gt;&gt; play; play = tolower(play); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T08:03:15.607", "Id": "413508", "Score": "0", "body": "The program works as intended. There are small improvments you could do. For example the main loop could be a do...while as you will run it at least once, not that it matters much. You could do with some '\\n' instead of so many endl. You only need to call srand once, in main, not in each GenerateRandomNumber call. You could use a enum or a const value called ROCK, SCISSORS, PAPER, instead of 'r', 's', 'p', for legibility." } ]
[ { "body": "<p>Here's a small suggestion:</p>\n\n<p>Your random number generation method is biased (taking the mod does not get you a uniform distribution). Also, you're seeding your random number every time you access it, while you can also just seed it once upon the start of the program (as @mcabreb mentioned). Additionally, <code>lo</code> and <code>hi</code> might be better parameter names for your <code>GenerateRandomNumber</code> function since <code>min</code> and <code>max</code> are actual function names in the STL. If you're using c++11, you can use the <code>&lt;random&gt;</code> header for generating uniform random numbers:</p>\n\n<pre><code>#include &lt;random&gt;\nusing namespace std;\nstd::default_random_engine generator;\n\n\nint GenerateRandomNumber(int lo, int hi)\n{\n std::uniform_int_distribution&lt;int&gt; distribution(lo, hi);\n return distribution(generator);\n}\n\n\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:51:28.713", "Id": "213822", "ParentId": "213777", "Score": "1" } }, { "body": "<p>This is a good exercise in doing things in a more data-driven way. This will result in clearer separation of concepts (i.e., game logic) and allow for more customization easily.</p>\n\n<p>So consider (skipping updating the main program):</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;cstdlib&gt;\n#include &lt;ctime&gt;\n#include &lt;cctype&gt;\n#include &lt;set&gt;\n#include &lt;map&gt;\n\nenum Choice\n{\n Rock = 1,\n Paper = 2,\n Scissors = 3\n};\n\nenum class Result\n{\n Win,\n Loss,\n Tie\n};\n\nconst std::set&lt;std::pair&lt;Choice, Choice&gt; &gt; wins =\n{\n { Rock, Scissors },\n { Scissors, Paper},\n { Paper, Rock }\n};\n\nconst std::map&lt;Result, std::string&gt; result_strings = \n{\n { Result::Win, \"WIN!\" },\n { Result::Loss, \"LOSS!\" },\n { Result::Tie, \"TIE!\" }\n};\n\nconst std::map&lt;char, std::string&gt; play_abbreviations =\n{\n { 'r', \"Rock\" },\n { 'p', \"Paper\" },\n { 's', \"Scissors\" }\n};\n\nstd::string ResultToString(Result result)\n{\n // TODO: Decide how to handle the case of input being unrecognized.\n return result_strings[result];\n}\n\nstd::string DeterminePlay(char playAbbreviation)\n{\n // TODO: Decide how to handle the case of input being unrecognized.\n return play_abbreviations[playAbbreviation];\n}\n\nResult DetermineResult(Choice playerPlay, Choice computerPlay)\n{\n if (playerPlay == computerPlay)\n {\n return Result::Tie;\n }\n else\n {\n return wins.find(std::make_pair(playerPlay, computerPlay)) != wins.cend() ? Result::Win : Result::Loss;\n }\n}\n\nint GenerateRandomNumber(int min, int max)\n{\n // TODO: Look at &lt;random&gt; to see how this is done better.\n srand(std::time(0));\n return (rand() % max) + min;\n}\n\nChoice GenerateComputerPlay()\n{\n const int number = GenerateRandomNumber(1, 3);\n return static_cast&lt;Choice&gt;(number);\n}\n</code></pre>\n\n<p>What we did here was that built the logic of who wins into a data structure, which is essentially a directed graph (more precisely, it's a directed 3-cycle). The winner determination now consist of checking whether the input is an arc in our graph; otherwise it's a loss if no such arc exists and a draw if the arc is a self-loop.</p>\n\n<p>Notice also the possibilities you obtain by a having a <code>result_strings</code>: you could put in more \"output texts\" for a win for instance, so maybe sometimes you'd like to tell the user \"WIN!\", but other times you could print \"GREAT JOB!\" or \"NICE!\"; that'll end up a nightmare from a maintenance and logic point of view if the number of possible strings grows large.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T18:24:49.207", "Id": "213826", "ParentId": "213777", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T02:16:36.603", "Id": "213777", "Score": "3", "Tags": [ "c++", "beginner", "console", "rock-paper-scissors" ], "Title": "Rock, Paper, Scissors. C++" }
213777
<p>Given the following definitions of <a href="https://github.com/data61/fp-course/blob/fddbca36d02bd19029eee25e75faa933634763da/src/Course/Functor.hs#L21" rel="nofollow noreferrer"><code>Functor</code></a> and <a href="https://github.com/data61/fp-course/blob/ad361c51862c5b7a7ba53a8767fa90bf38f2dc31/src/Course/Traversable.hs#L99" rel="nofollow noreferrer"><code>Coproduct</code></a> from <a href="https://github.com/data61/fp-course" rel="nofollow noreferrer">fp-course</a>:</p> <blockquote> <pre><code>class Functor f where (&lt;$&gt;) :: (a -&gt; b) -&gt; f a -&gt; f b class Functor f =&gt; Applicative f where pure :: a -&gt; f a (&lt;*&gt;) :: f (a -&gt; b) -&gt; f a -&gt; f b class Functor t =&gt; Traversable t where traverse :: Applicative f =&gt; (a -&gt; f b) -&gt; t a -&gt; f (t b) data Coproduct f g a = InL (f a) | InR (g a) </code></pre> </blockquote> <p>Is there a cleaner or more succinct way to implement the following?</p> <pre><code>instance (Traversable f, Traversable g) =&gt; Traversable (Coproduct f g) where traverse :: Applicative h =&gt; (a -&gt; h b) -&gt; Coproduct f g a -&gt; h (Coproduct f g b) traverse f (InL fa) = InL &lt;$&gt; traverse f fa traverse f (InR ga) = InR &lt;$&gt; traverse f ga </code></pre>
[]
[ { "body": "<p>Here is how <a href=\"https://github.com/ekmett\" rel=\"nofollow noreferrer\">Edward Kmett</a> implemented <code>traverse</code> in the <a href=\"https://hackage.haskell.org/package/comonad-4.0/docs/src/Data-Functor-Coproduct.html#Coproduct\" rel=\"nofollow noreferrer\">Data.Functor.Coproduct</a> package. </p>\n\n<pre><code>instance (Traversable f, Traversable g) =&gt; Traversable (Coproduct f g) where\n traverse f = coproduct\n (fmap (Coproduct . Left) . traverse f)\n (fmap (Coproduct . Right) . traverse f)\n</code></pre>\n\n<p>While he writes in a points free style and uses <code>Either</code> under the hood instead of your bespoke Coproduct instance, the result is still the same. Apply the supplied function to either the left or right branch and wrap the result back in the constructor.</p>\n\n<p>I do not see a better way to than the implementation given unless η-conversion to points-free is appealing for some reason.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T05:37:38.927", "Id": "213782", "ParentId": "213780", "Score": "3" } }, { "body": "<p><code>type Coproduct f g a = Either (f a) (g a)</code> has a <code>Traversal</code> via the <code>lens</code> library:</p>\n\n<pre><code>choosing traverse traverse :: (Traversable tl, Traversable tr, Applicative f)\n =&gt; (a -&gt; f b) -&gt; Coproduct tl tr a -&gt; f (Coproduct tl tr b)\n</code></pre>\n\n<p>I'd expect your usecase to have an easier time using <code>lens</code> directly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T22:26:33.810", "Id": "213841", "ParentId": "213780", "Score": "0" } } ]
{ "AcceptedAnswerId": "213782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T03:15:48.210", "Id": "213780", "Score": "2", "Tags": [ "haskell" ], "Title": "Implementing Traversable for Coproduct" }
213780
<p>I have found similar posts which has some optimizations on Winning-checking logic: <a href="https://codereview.stackexchange.com/questions/161139/react-tic-tac-toe">React Tic Tac Toe</a></p> <p>My primary focus for this post is about <code>hook setters</code> being asynchronous. So to check if anyone wins, I used <code>useEffect</code> to listen to the board.</p> <pre><code> useEffect( () =&gt; { if (winning()) { setMessage(`Player ${turn % 2 ? 1 : 2} wins!`); setGameState("stopped"); } else { setTurn(turn + 1); } }, [board] ); </code></pre> <p>When the move is made, the turn number won't increase when the game is finished.</p> <p>However this makes the initial "turn number" 0 (so the effect adds to it to get 1).</p> <p>Should I make the board update synchronous before calling the setters? (like using a <code>tempBoard = {...board, (new move)}</code> and check there instead?</p> <p>Full code (Click handler is <code>step</code>)</p> <pre><code>import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function App() { const [turn, setTurn] = useState(0); const [message, setMessage] = useState(""); const [gameState, setGameState] = useState("playing"); const [board, setBoard] = useState({}); const winning = _ =&gt; { return ( (board[0] &amp;&amp; board[1] &amp;&amp; board[2] &amp;&amp; board[0] === board[1] &amp;&amp; board[1] === board[2]) || (board[3] &amp;&amp; board[4] &amp;&amp; board[5] &amp;&amp; board[3] === board[4] &amp;&amp; board[4] === board[5]) || (board[6] &amp;&amp; board[7] &amp;&amp; board[8] &amp;&amp; board[6] === board[7] &amp;&amp; board[7] === board[8]) || (board[0] &amp;&amp; board[3] &amp;&amp; board[6] &amp;&amp; board[0] === board[3] &amp;&amp; board[3] === board[6]) || (board[1] &amp;&amp; board[4] &amp;&amp; board[7] &amp;&amp; board[1] === board[4] &amp;&amp; board[4] === board[7]) || (board[2] &amp;&amp; board[5] &amp;&amp; board[8] &amp;&amp; board[2] === board[5] &amp;&amp; board[5] === board[8]) || (board[0] &amp;&amp; board[4] &amp;&amp; board[8] &amp;&amp; board[0] === board[4] &amp;&amp; board[4] === board[8]) || (board[2] &amp;&amp; board[4] &amp;&amp; board[6] &amp;&amp; board[2] === board[4] &amp;&amp; board[4] === board[6]) ); }; useEffect( () =&gt; { if (winning()) { setMessage(`Player ${turn % 2 ? 1 : 2} wins!`); setGameState("stopped"); } else { setTurn(turn + 1); } }, [board] ); const step = (n, turn) =&gt; { if (gameState === "playing" &amp;&amp; !board[n]) { setBoard({ ...board, [n]: turn % 2 ? "x" : "o" }); } }; return ( &lt;div className="App"&gt; Turn {turn} &lt;div className="container"&gt; {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(n =&gt; ( &lt;div key={"b" + n} className={"b" + n}&gt; &lt;button onClick={_ =&gt; step(n, turn)}&gt;{board[n] || " "}&lt;/button&gt; &lt;/div&gt; ))} &lt;/div&gt; {message} &lt;/div&gt; ); } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre> <p><a href="https://codesandbox.io/s/544r3qzyll" rel="nofollow noreferrer">CodeSandbox</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T04:52:22.223", "Id": "213781", "Score": "2", "Tags": [ "tic-tac-toe", "react.js", "jsx" ], "Title": "Tic-Tac-Toe with React hooks" }
213781
<blockquote> <p>This problem was asked by Stripe.</p> <p>Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.</p> <p>For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.</p> <p>You can modify the input array in-place.</p> </blockquote> <pre><code>class DailyCodingProblem5 { public static void main(String args[]) { int[] arr = { 3, 4, -1, 1 }; int res = solution(arr); System.out.println(res); int[] arr2 = { 1, 2, 0 }; res = solution(arr2); System.out.println(res); } private static int solution(int[] arr) { int n = arr.length; int i = 0; for (i = 0; i &lt; n; i++) { int val = arr[i]; if (val &lt;= 0 || val &gt; n) continue; while (val != arr[val - 1]) { int nextval = arr[val - 1]; arr[val - 1] = val; val = nextval; if (val &lt;= 0 || val &gt; n) { break; } } } for (i = 0; i &lt; n; i++) { if (arr[i] != i + 1) { return i + 1; } } return n+1; } } </code></pre> <p><strong>How can i improve the above solution? Is there any improvements i can have in my code ?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T06:45:22.430", "Id": "413501", "Score": "3", "body": "Testing for { 1, 2, 3, 4, 5 } and similar arrays return 5, which is not missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T08:08:09.123", "Id": "413509", "Score": "1", "body": "I have voted to close this since your algorithm doesn't work. Please come back when you have fixed it. (What I can tell you right away, though, is that your algorithm can never finish in linear time if you have nested loops)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T08:39:08.947", "Id": "413511", "Score": "0", "body": "@vnp updated the code to return return n+1;. It works now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T09:25:02.360", "Id": "413517", "Score": "0", "body": "I appreciate code comments in general. I'd like to see an argument that \"the rearrangement loop\" runs `in linear time`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:29:49.080", "Id": "413523", "Score": "0", "body": "@greybeard while (val != arr[val - 1]) based on this condition, it will enter only when we need to rearrange. Thus in the worst case max n of swap's are possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T22:24:59.597", "Id": "413611", "Score": "1", "body": "Not *I want to be enlightened how it works*: I'd like to see an argument that \"the rearrangement loop\" runs in linear time *in the code* - easiest in comment form. (You can't put it there in this question, as considerable time has passed since posting and, more compellingly, answering started.)" } ]
[ { "body": "<p>It would be good to have some comments in the code explaining why (a) it works; (b) it takes linear time.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int i = 0;\n for (i = 0; i &lt; n; i++) {\n</code></pre>\n</blockquote>\n\n<p>I would prefer to use <code>for (int i = 0; ...)</code> and similarly for the other loop over <code>i</code>: they don't need to use the same variable, and keeping scopes as small as possible helps understanding and maintenance. But if you prefer to keep the variable in the wider scope, there's no need to initialise it twice. Either of</p>\n\n<pre><code> int i = 0;\n for (; i &lt; n; i++) {\n</code></pre>\n\n<p>or</p>\n\n<pre><code> int i;\n for (i = 0; i &lt; n; i++) {\n</code></pre>\n\n<p>works fine.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (val &lt;= 0 || val &gt; n)\n continue;\n while (val != arr[val - 1]) {\n int nextval = arr[val - 1];\n arr[val - 1] = val;\n val = nextval;\n if (val &lt;= 0 || val &gt; n) {\n break;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>It's a bit inelegant to apply the range test twice. A simple refactor gives</p>\n\n<pre><code> while (val &gt; 0 &amp;&amp; val &lt;= n &amp;&amp; val != arr[val - 1]) {\n int nextval = arr[val - 1];\n arr[val - 1] = val;\n val = nextval;\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> }\n return n+1;\n\n }\n</code></pre>\n</blockquote>\n\n<p>For consistency I would add whitespace around <code>+</code>. The blank line makes more sense to me before the <code>return</code> rather than after it, and I would also add a blank line separating the two loops.</p>\n\n<p>The fact that I'm nitpicking whitespace like this is a good sign: I haven't found anything which I consider to be a major problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T13:34:21.403", "Id": "413683", "Score": "0", "body": "\"*It would be good to have some comments in the code explaining why (a) it works*\" even better if it's not *comments* but *self-documenting code* that explains how it works. Better variable names and extracting expressions into variables can do that. A comment can still serve to explain the linear timing, question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:52:24.077", "Id": "413701", "Score": "0", "body": "In this case, I won't believe that refactoring could explain why the code works unless I see it. If you think you can do it, feel free to post the code in an answer and ping me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T08:59:00.007", "Id": "213788", "ParentId": "213785", "Score": "5" } } ]
{ "AcceptedAnswerId": "213788", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T06:24:13.293", "Id": "213785", "Score": "2", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "First missing positive integer in linear time and constant space" }
213785
<p>I'm developing a webpage displaying the scheduled pipelines from all projects of a GitLab instance. The scheduled time is expressed using <a href="https://en.wikipedia.org/wiki/Cron" rel="noreferrer">CRON expressions</a>, i.e. five digits as follows:</p> <p><a href="https://i.stack.imgur.com/NR726.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NR726.png" alt="Wikipedia's description of the five digits of CRON expressions" /></a></p> <p>Because not all future users of my webpage are familiar with CRON expressions, I wrote a script for translating it into a human-readable time expression.</p> <p>Some important information for understanding the logic behind the code:</p> <ul> <li><strong>&quot;7&quot; is not used as an alias for &quot;Sunday&quot;</strong> on my GitLab instance.</li> <li><strong>Timezones are not taken into account</strong> (...yet). I'm considering all CRON expressions as UTC times for now.</li> <li>Times are expressed in the <strong>24 hours format</strong> (so 11:23PM is 23h23)</li> <li>The pipelines that we launch take a lot of time to be fully executed, which is why we don't allow the first digit of the CRON expression to be <code>*</code>.</li> </ul> <h2>Some examples of cron-to-string conversion:</h2> <blockquote> <p>0 4 * * * * → &quot;Runs at 04h00 every day&quot;</p> <p>0 23 * * 0 → &quot;Runs at 23h00 on Sundays&quot;</p> <p>0 4 1 * * → &quot;Runs at 04h00 on the 1st day of every month&quot;</p> </blockquote> <h2>The code</h2> <pre><code>function convertCronToString(cronExpression) { var cron = cronExpression.split(&quot; &quot;); var minutes = cron[0]; var hours = cron[1]; var dayOfMonth = cron[2]; var month = cron[3]; var dayOfWeek = cron[4]; var cronToString = &quot;Runs at &quot;; // Formatting time if composed of zeros if (minutes === &quot;0&quot;) minutes = &quot;00&quot;; if (hours === &quot;0&quot;) hours = &quot;00&quot;; // If it's not past noon add a zero before the hour to make it look like &quot;04h00&quot; instead of &quot;4h00&quot; else if (hours.length === 1 &amp;&amp; hours !== &quot;*&quot;) { hours = &quot;0&quot; + hours; } // Our activities do not allow launching pipelines every minute. It won't be processed. if (minutes === &quot;*&quot;) { cronToString = &quot;Unreadable cron format. Cron will be displayed in its raw form: &quot; + cronExpression; } cronToString = cronToString + hours + &quot;h&quot; + minutes + &quot; &quot;; if (dayOfWeek === &quot;0,6&quot;) dayOfWeek = &quot;on weekends&quot;; else if (dayOfWeek === &quot;1-5&quot;) dayOfWeek = &quot;on weekdays&quot;; else if (dayOfWeek.length === 1) { if (dayOfWeek === &quot;*&quot; &amp;&amp; dayOfMonth === &quot;*&quot;) dayOfWeek = &quot;every day &quot;; else if (dayOfWeek === &quot;*&quot; &amp;&amp; dayOfMonth !== &quot;*&quot;) { cronToString = cronToString + &quot;on the &quot; + dayOfMonth; if ( dayOfMonth === &quot;1&quot; || dayOfMonth === &quot;21&quot; || dayOfMonth === &quot;31&quot; ) { cronToString = cronToString + &quot;st &quot;; } else if (dayOfMonth === &quot;2&quot; || dayOfMonth === &quot;22&quot;) { cronToString = cronToString + &quot;nd &quot;; } else if (dayOfMonth === &quot;3&quot; || dayOfMonth === &quot;23&quot;) { cronToString = cronToString + &quot;rd &quot;; } else { cronToString = cronToString + &quot;th &quot;; } cronToString = cronToString + &quot;day of every month&quot;; return cronToString; } else if (dayOfWeek !== &quot;*&quot; &amp;&amp; dayOfMonth === &quot;*&quot;) { switch (parseInt(dayOfWeek)) { case 0: dayOfWeek = &quot;on Sundays&quot;; break; case 1: dayOfWeek = &quot;on Mondays&quot;; break; case 2: dayOfWeek = &quot;on Tuesdays&quot;; break; case 3: dayOfWeek = &quot;on Wednesdays&quot;; break; case 4: dayOfWeek = &quot;on Thursdays&quot;; break; case 5: dayOfWeek = &quot;on Fridays&quot;; break; case 6: dayOfWeek = &quot;on Saturdays&quot;; break; default: cronToString = &quot;Unreadable cron format. Cron will be displayed in its raw form: &quot; + cronExpression; return cronToString; } } cronToString = cronToString + dayOfWeek + &quot; &quot;; } return cronToString; } </code></pre> <h2>Question</h2> <p>How could this code be optimized?</p> <h2>Additional information</h2> <ul> <li>This method is part of a Vue.JS component so I apologize if I forgot to translate some of the Vue-specific into Vanilla Javascript.</li> <li>I have not implemented the code in case the pipeline is supposed to run on a given number of days of the week/month when provided as a suite of numbers separated by commas.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:54:02.347", "Id": "413525", "Score": "0", "body": "@422_unprocessable_entity Mmh, that's possible that it's one of the differences between Vue and Javascript. I'll edit to suit the JS syntax. Thanks for spotting this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T12:29:12.837", "Id": "413532", "Score": "2", "body": "Since you didn't say you could use `,` or `-` in `dayOfWeek`, I looked up how these are formed. Does your code correctly handle `0,30 0,12 1,8,15,22,29 1-12 *`?" } ]
[ { "body": "<p>You do a lot of tests. It would be simplier if you implement a few objects containing your different values and you just display these values.</p>\n\n<p>You'd have to do enough objects to cover all cases but you limit the tests to the minimum this way.</p>\n\n<p>Example :</p>\n\n<pre><code>// I won't print every cases but you got the idea\nlet dayOfWeekWhenNoMonthIsSpecified = {\n '*' : 'every day', '0' : 'on Sundays', '1' : 'on Mondays',\n '0,6' : 'on weekends', '1-5' : 'on weekdays'\n};\n\ncronToString = \"Runs \" + dayOfWeekWhenNoMonthIsSpecified[cron[4]];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T12:06:17.180", "Id": "213797", "ParentId": "213790", "Score": "2" } }, { "body": "<blockquote>\n <p>How could this code be optimized?</p>\n</blockquote>\n\n<p>I'm not sure if you mean optimized for performance, brevity, readability, maintainability, etc. but I will offer some suggestions below that might suffice in some of those areas.</p>\n\n<p>Overall the function seems a bit long. There is no exact rule about what is too long but there are various conventions developers adhere to (e.g. see answers to <a href=\"https://softwareengineering.stackexchange.com/q/27798/244085\"><em>What should be the maximum length of a function?</em> on SE SE</a>. You could break the function up into separate functions that handle an individual aspect of parsing the string and/or adding output- for example one to return the output for the time, one for the days, etc. This might also allow for better unit testing if you chose to do that. </p>\n\n<p>I also see two different <code>return</code> statements - one for the case where <code>dayOfWeek.length === 1</code> combined with <code>dayOfWeek === \"*\" &amp;&amp; dayOfMonth !== \"*\"</code> and one at the end. It is fine to return early, but should the code also return early when the string calls for execution each minute? - i.e. the following code</p>\n\n<blockquote>\n<pre><code>if (minutes === \"*\") {\n cronToString =\n \"Unreadable cron format. Cron will be displayed in its raw form: \" +\n cronExpression;\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Unless the browser requirements are such that it won't work (e.g. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Browser_compatibility\" rel=\"nofollow noreferrer\">for IE</a>) you can utilize some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features to shorten the code. For example:</p>\n\n<blockquote>\n<pre><code>var cron = cronExpression.split(\" \");\nvar minutes = cron[0];\nvar hours = cron[1];\nvar dayOfMonth = cron[2];\nvar month = cron[3];\nvar dayOfWeek = cron[4];\n</code></pre>\n</blockquote>\n\n<p>This could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring\" rel=\"nofollow noreferrer\">Array destructuring</a>:</p>\n\n<pre><code>let [minutes, hours, dayOfMonth, month, dayOfWeek] = cronExpression.split(\" \");\n</code></pre>\n\n<p>You could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> instead of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> if you don't overwrite those variables (and instead add to the output string).</p>\n\n<hr>\n\n<p>I see a few places where the string to be returned (i.e. <code>cronToString</code>) is appended to using </p>\n\n<blockquote>\n<pre><code>cronToString = cronToString + hours + \"h\" + minutes + \" \";\n</code></pre>\n</blockquote>\n\n<p>This can be simplified using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#String_operators\" rel=\"nofollow noreferrer\">shorthand concatenation operator</a> - i.e. <code>+=</code></p>\n\n<blockquote>\n<pre><code>cronToString += hours + \"h\" + minutes + \" \";\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>I see one call to <code>parseInt()</code> - i.e. </p>\n\n<blockquote>\n<pre><code>parseInt(dayOfWeek)\n</code></pre>\n</blockquote>\n\n<p>If you are going to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt()</code></a>, it is wise to specify the radix using the second parameter - unless you are using a unique number system like hexidecimal, octal, etc. then specify 10 for decimal numbers. </p>\n\n<blockquote>\n <p><strong>Always specify this parameter</strong> to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<pre><code>parseInt(dayOfWeek, 10);\n</code></pre>\n\n<p>While it may not cause a logic error with this code due to the range of numbers checked, it is a good habit to specify that parameter.</p>\n\n<hr>\n\n<p>Let us talk about that <code>switch</code> statement. Bearing in mind that the code in the question doesn’t exactly use one, I am reminded of <a href=\"https://codereview.stackexchange.com/a/44187/120114\">this stellar answer</a> where the OP was advised to use a hashmap (since that Code is java). Whenever you have a set of cases in a <code>switch</code> statement that have one line very similar to the majority of all other cases then you might want to consider creating a mapping. This can be done in JavaScript with an array, a plain old JavaScript object (A.K.A. a “<em>POJO</em>”) or a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\"><code>Map</code></a>. Then just check that the value used in the <code>switch</code> statement matches an index/key of the array/object/map. </p>\n\n<p>Instead of using the <code>switch</code> statement to add the day of the week display, you could put the days of the week into an array (perhaps outside the function to avoid re-assignment whenever the function is called), and check if <code>dayOfWeek</code> matches a key in that array:</p>\n\n<pre><code>const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wedensday', 'Thursday', 'Friday', 'Saturday'];\n</code></pre>\n\n<p>Then to use it, reference the key as <code>dayOfWeek</code>:</p>\n\n<pre><code>if (dayOfWeek &gt; -1 &amp;&amp; dayOfWeek &lt; 7) {\n dayOfWeek = \"on \" + daysOfWeek[dayOfWeek];\n}\nelse {\n cronToString =\n \"Unreadable cron format. Cron will be displayed in its raw form: \" +\n cronExpression;\n return cronToString;\n}\n</code></pre>\n\n<p>You could also consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString\" rel=\"nofollow noreferrer\"><code>date.toLocalDateString()</code></a> with the <code>weekday</code> option, which would allow offering localized values, but then that would involve constructing a date and calling more functions, which might not be optimal for your use case.</p>\n\n<p>I also looked for a similar way to add the ordinal suffix but don't see anything built-in, though there are various alternatives in the answers to <a href=\"https://stackoverflow.com/q/13627308/1575353\">this SO question</a> - some briefer (and more obfuscated) than others...</p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters</a></sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-03T22:47:18.723", "Id": "216821", "ParentId": "213790", "Score": "4" } } ]
{ "AcceptedAnswerId": "216821", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T09:55:36.040", "Id": "213790", "Score": "10", "Tags": [ "javascript", "parsing", "datetime" ], "Title": "Javascript cron-to-human-readable translator" }
213790
<p>I was doing an exercise in PHP, and it works perfectly, no problems. But I think that maybe I coded it so long, and I think it can be shorter than it is now, but I don't know how to make it shorter and that works exactly the same way.</p> <p>I will explain what this code is doing for you so it's faster if you are going to help (if you want a deeper explanation, you can translate the commented section because that's the wording of the exercise): first of all, I have a PHP file and a html file with a form. The form it's asking for 2 values (feet and inches), for converting them to centimeters. Feet value must be integer, greater than or equal 0. Inches must be integer or decimal, and greater than or equal 0.</p> <pre><code>&lt;?php //Realice un formulario que introduzca dos valores (pies y pulgadas) y los convierta a //centímetros. Los pies deben ser un número entero mayor o igual que cero. Las pulgadas //son un número entero o decimal mayor o igual que cero. Un pie son doce pulgadas y una //pulgada son 2,54 cm. $converPC = 30.48; $converPlC = 2.54; $pies = trim(htmlspecialchars(strip_tags($_REQUEST["pies"]), ENT_QUOTES, "UTF-8")); $pulgadas = trim(htmlspecialchars(strip_tags($_REQUEST["pulgadas"]), ENT_QUOTES, "UTF-8")); if ( (!empty($pies)) &amp;&amp; (!empty($pulgadas)) ) { if ( (is_numeric($pies)) &amp;&amp; (is_numeric($pulgadas)) ) { //Apartado de los pies if ( (filter_var($pies, FILTER_VALIDATE_INT)) &amp;&amp; ($pies &gt;= 0) ) { $resultadoPI = $pies*$converPC; print "&lt;b&gt;CONVERSIÓN PIES - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;"; print "$pies pies son $resultadoPI centímetros&lt;br/&gt;&lt;br/&gt;"; } else { print "&lt;b&gt;Error en pies&lt;/b&gt;&lt;br/&gt;"; print "Debe introducir un número entero mayor o igual que cero&lt;br/&gt;&lt;br/&gt;"; } //Apartado de las pulgadas if ($pulgadas &gt;= 0) { $resultadoPU = $pulgadas*$converPlC; print "&lt;b&gt;CONVERSIÓN PULGADAS - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;"; print "$pulgadas pulgadas son $resultadoPU centímetros"; } else { print "&lt;b&gt;Error en pulgadas&lt;/b&gt;&lt;br/&gt;"; print "Debe introducir un número mayor o igual que cero"; } } else { print "Error, ambos valores deben ser numéricos"; } } else { print "Para que todo funcione, debe rellenar TODOS los campos del formulario"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:20:53.537", "Id": "413537", "Score": "0", "body": "I wanted to shorten this code or improve it. In stackoverflow they said to me that I should post this here, where should I post this code if I want that someone can help me to shorten and improve this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:22:36.270", "Id": "413538", "Score": "0", "body": "@DaburuKao - Just to confirm: is this working code? If so, it is okay to post this here. Also, I am not sure how much this code can be reduced in size. Do you still want a review if the results don't offer much of a reduction in size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:24:51.453", "Id": "413539", "Score": "0", "body": "As I said before yes, this code worked for me as intended. And I would accept a review about my code, possible reduces in size or improvements...anything ^^" } ]
[ { "body": "<p>This code is pretty compact already so there isn't much room to reduce the size of it. Typically separating the error handling, calculations, and output of content are separated so you may want to look into that for code improvements but that won't make the code any smaller.</p>\n<p><strong>Better data sanitation</strong></p>\n<p>It's great that you do your best to sanitize user input before you use it. But, there's better ways to go about it. Since\nboth inputs are expected to be floating point numbers you can use PHP's built in <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow noreferrer\"><code>filter_var()</code></a> with the\n<code>FILTER_VALIDATE_FLOAT</code> flag to sanitize the value to a floating point number:</p>\n<pre><code>$pies = filter_var($_REQUEST[&quot;pies&quot;], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);\n$pulgadas = filter_var($_REQUEST[&quot;pulgadas&quot;], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);\n</code></pre>\n<p><strong>Combine/remove your IF statements</strong></p>\n<p>When you see an IF statement followed by another IF statement that's usually a sign that you could combine the two into one as all of them must be true for the following code to be executed:</p>\n<pre><code>if ( !empty($pies) &amp;&amp; !empty($pulgadas) &amp;&amp; (s_numeric($pies) &amp;&amp; is_numeric($pulgadas) ) {\n</code></pre>\n<p>The above line can then be shortened thanks to the better sanitation used above. The checks to is_numeric are no longer\nneeded since <code>filter_var()</code> will return a number or false which will be caught by the <code>empty()</code> checks. So you can now safely remove them:</p>\n<pre><code>if ( !empty($pies) &amp;&amp; !empty($pulgadas) ) {\n</code></pre>\n<p>You can eliminate your check to see if <code>$pies &gt;= 0</code> by passing an extra flag to <code>filter_var()</code> to only allow positive numbers and zero.</p>\n<pre><code>if ( filter_var($pies, FILTER_VALIDATE_INT) &amp;&amp; $pies &gt;= 0 ) {\n</code></pre>\n<p>becomes</p>\n<pre><code>if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' =&gt; ['min_range' =&gt; 0]]) ) {\n</code></pre>\n<p>You also forgot to add this check for <code>$pulgadas</code>.</p>\n<h1>Other notes</h1>\n<p><strong>Use constants to store values that will remain the same and are unchangeable</strong></p>\n<p>Your variables containing the ratios for converting the measurements are better off set as constants than variables since they will remain the same and are unchangeable. (i.e. constant)</p>\n<pre><code>$converPC = 30.48;\n$converPlC = 2.54;\n</code></pre>\n<p>becomes (notice the use of all capital letters as that is the expected format of constants in PHP)</p>\n<pre><code>define('CONVER_PC', 30.48);\ndefine('CONVER_PLC', 2.54);\n</code></pre>\n<p><strong>Omit closing PHP tag</strong></p>\n<p>When the closing tag is the last line of a PHP file you can safely omit and it is the standard practice as set forth by\nthe <a href=\"http://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> coding standard for PHP. There are <a href=\"https://stackoverflow.com/a/4499749/250259\">lots of good reasons to do this</a>.</p>\n<p><strong>Use <code>echo</code> over <code>print()</code></strong></p>\n<p><code>print()</code> is an alias of <code>echo</code> but there are minor differences between the two. Although they don't come into play here, it is the PHP convention to use <code>echo</code> for outputting content.</p>\n<p><strong>Unnecessary parenthesis</strong></p>\n<p>If your IF statements you have parenthesis around each conditional. That is not necessary. You only need to use them when you need to clarify scope. When there's only one condition there is nothing that needs clarification.</p>\n<h1>Outcome</h1>\n<p>This code is untested but should give you the idea of what the comments above mean.</p>\n<pre><code>define('CONVER_PC', 30.48);\ndefine('CONVER_PLC', 2.54);\n$pies = filter_var($_REQUEST[&quot;pies&quot;], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);\n$pulgadas = filter_var($_REQUEST[&quot;pulgadas&quot;], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);\nif ( !empty($pies) &amp;&amp; !empty($pulgadas) ) {\n //Apartado de los pies\n if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' =&gt; ['min_range' =&gt; 0]]) ) {\n $resultadoPI = $pies*CONVER_PC;\n echo &quot;&lt;b&gt;CONVERSIÓN PIES - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;&quot;;\n echo &quot;$pies pies son $resultadoPI centímetros&lt;br/&gt;&lt;br/&gt;&quot;;\n } else {\n echo &quot;&lt;b&gt;Error en pies&lt;/b&gt;&lt;br/&gt;&quot;;\n echo &quot;Debe introducir un número entero mayor o igual que cero&lt;br/&gt;&lt;br/&gt;&quot;;\n }\n //Apartado de las pulgadas\n if ( filter_var($pulgadas, FILTER_VALIDATE_INT, ['options' =&gt; ['min_range' =&gt; 0]]) ) {\n $resultadoPU = $pulgadas*CONVER_PLC;\n echo &quot;&lt;b&gt;CONVERSIÓN PULGADAS - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;&quot;;\n echo &quot;$pulgadas pulgadas son $resultadoPU centímetros&quot;;\n } else {\n echo &quot;&lt;b&gt;Error en pulgadas&lt;/b&gt;&lt;br/&gt;&quot;;\n echo &quot;Debe introducir un número mayor o igual que cero&quot;;\n }\n} else {\n print &quot;Para que todo funcione, debe rellenar TODOS los campos del formulario&quot;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:29:54.193", "Id": "213804", "ParentId": "213791", "Score": "3" } }, { "body": "<p>Main issues with this code are</p>\n\n<ol>\n<li>It doesn't meet the requirements (so doesn't the code in the other answer).</li>\n<li>Its result is not very useful <em>if you ever try to actually use it</em>. </li>\n<li>Nearly half of this code just duplicates itself or plain useless.</li>\n</ol>\n\n<p>So here goes your homework</p>\n\n<pre><code>$converPlC = 2.54;\n$converPC = $converPlC * 12;\n\n$pies = $_REQUEST[\"pies\"];\n$pulgadas = $_REQUEST[\"pulgadas\"];\n\nif (ctype_digit($pies) &amp;&amp; $pies &gt;= 0) {\n $resultadoPI = $pies*$converPC;\n print \"&lt;b&gt;CONVERSIÓN PIES - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;\\n\";\n print \"$pies pies son $resultadoPI centímetros&lt;br/&gt;&lt;br/&gt;\\n\";\n} else {\n print \"&lt;b&gt;Error en pies&lt;/b&gt;&lt;br/&gt;\\n\";\n print \"Debe introducir un número entero mayor o igual que cero&lt;br/&gt;&lt;br/&gt;\\n\";\n $resultadoPI = 0;\n}\nif (is_numeric($pulgadas) &amp;&amp; $pulgadas &gt;= 0) {\n $resultadoPU = $pulgadas*$converPlC;\n print \"&lt;b&gt;CONVERSIÓN PULGADAS - CENTÍMETROS&lt;/b&gt;&lt;br/&gt;\\n\";\n print \"$pulgadas pulgadas son $resultadoPU centímetros\\n\";\n} else {\n print \"&lt;b&gt;Error en pulgadas&lt;/b&gt;&lt;br/&gt;\\n\";\n print \"Debe introducir un número mayor o igual que cero\\n\";\n $resultadoPU = 0;\n}\n</code></pre>\n\n<p>It makes your code fixed but it doesn't look good. To make it better, we will need a sensible output and also we definitely should separate the calculations from the output. So here goes the refactored version</p>\n\n<pre><code>$converPlC = 2.54;\n$converPC = $converPlC * 12;\n\n$pies = $_REQUEST[\"pies\"];\n$pulgadas = $_REQUEST[\"pulgadas\"];\n\nif (ctype_digit($pies) &amp;&amp; $pies &gt;= 0 &amp;&amp; is_numeric($pulgadas) &amp;&amp; $pulgadas &gt;= 0) {\n $resultadoPI = $pies*$converPC;\n $resultadoPU = $pulgadas*$converPlC;\n $resultado = $resultadoPU + $resultadoPI;\n if ($resultadoPU &amp;&amp; $resultadoPI) {\n $title = \"CONVERSIÓN PIES Y PULGADAS - CENTÍMETROS\";\n $message = \"$pies pies y $pulgadas pulgadas son $resultado centímetros\";\n } elseif ($resultadoPI) {\n $title = \"CONVERSIÓN PIES - CENTÍMETROS\";\n $message = \"$pies pies son $resultado centímetros\";\n } elseif ($resultadoPU) {\n $title = \"CONVERSIÓN PULGADAS - CENTÍMETROS\";\n $message = \"$pulgadas pulgadas son $resultado centímetros\";\n } else {\n $title = \"Invalid input data\";\n $message = \"Enter at least one value\";\n }\n} else {\n $title = \"Invalid input data\";\n $message = \"Input must be a positive number or zero\";\n}\n?&gt;\n&lt;b&gt;&lt;?=$title?&gt;&lt;/b&gt;&lt;br/&gt;\n&lt;?=$message?&gt;&lt;br/&gt;&lt;br/&gt;\n</code></pre>\n\n<p>Here you can see the immediate benefit of the separated output: when you will have to change the formatting, it would be done only once and without the hassle of escaping quotes and stuff. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:20:49.713", "Id": "213808", "ParentId": "213791", "Score": "-2" } } ]
{ "AcceptedAnswerId": "213804", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T10:13:33.440", "Id": "213791", "Score": "3", "Tags": [ "php", "unit-conversion" ], "Title": "Asking 2 values, feet and inches, and it converts them to centimeters" }
213791
<p>I have a dictionary:</p> <pre><code>x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'} </code></pre> <p>and a dataframe</p> <pre><code>df = pd.DataFrame({'q':['hey this is [a]', 'why dont you [b]', 'clas is [c]']}) </code></pre> <p>I want to append the values from dictionary to the corresponding keys.</p> <p>My expected output is:</p> <pre><code> q 0 hey this is [a](1234) 1 why dont you [b](2345) 2 clas is [c](xyzad) </code></pre> <p>Here's my solution:</p> <pre><code>x = {k: k+v for k,v in x.items()} def das(data): for i in x.keys(): if i in data: data = data.replace(i, x[i]) return data df['q'] = df['q'].apply(lambda x: das(x)) print(df) </code></pre> <p>Is there a way to improve this?</p> <p>I have to update a dictionary by appending a key infront of values. Then I use <code>apply</code> to replace the values.</p> <p>I am looking for more efficient solution.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:24:16.247", "Id": "413573", "Score": "0", "body": "Are the keys always in the form shown in this example, i.e. surrounded by `[]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T04:32:59.250", "Id": "413635", "Score": "0", "body": "@Graipher yes..it's like markdown used in SE" } ]
[ { "body": "<p>There is an alternative way using the <code>str</code> functions of <code>pandas.Series</code>, which has the advantage that they are usually faster. In this case you can use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html\" rel=\"nofollow noreferrer\"><code>pandas.Series.str.replace</code></a>, which can take a regex to match strings against and a callable to replace them with, which gets passed the regex match object:</p>\n\n<pre><code>def repl(m):\n k = m.group()\n return k + x[k]\n\ndf.q.str.replace(r'\\[.*\\]', repl)\n# 0 hey this is [a](1234)\n# 1 why dont you [b](2345)\n# 2 clas is [c](xyzad)\n# Name: q, dtype: object\n</code></pre>\n\n<p>This uses the fact that your keys to replace seem to follow a pattern, though, and works only as long as you can write a regex to capture it. In that sense your solution is more general.</p>\n\n<p>One thing that you can change in your approach is the check for <code>if i in data</code>. It is superfluous, since <code>str.replace</code> will just ignore it if the string to replace does not appear in the string (it has to search linearly through the whole string to figure that out, but so does <code>i in data</code>).</p>\n\n<p>In addition, instead of iterating over the keys with <code>for i in x.keys():</code>, you can just do <code>for i in x:</code>. But since you also need the value, you can directly do <code>for key, repl in x.items(): data = data.replace(key, repl)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T05:02:34.990", "Id": "413637", "Score": "0", "body": "Thanks and nice catch that `if` statement in useless in that `for` loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:30:22.723", "Id": "213816", "ParentId": "213795", "Score": "1" } } ]
{ "AcceptedAnswerId": "213816", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T11:04:48.400", "Id": "213795", "Score": "3", "Tags": [ "python", "hash-map", "pandas" ], "Title": "Appending values in Pandas column" }
213795
<p>My team has been given care of an old embedded C project. Its main part is a security critical RPC API and I'm trying to create a new design of its internal interfaces to make it more robust against the inevitable bugs. My main goals are:</p> <ul> <li>Make it easy to write memory safe code (no buffer overflows, information disclosure, etc.)</li> <li>Make error propagation hard to forget or at least easy to audit.</li> <li>[Anything which is important for security given time constrained developers / auditors.]</li> </ul> <p>My biggest joker is that because of it being an RPC server nearly all allocations have a lifetime of at most one request and the server is (currently) single threaded only. Thus I have written a per-request memory pool:</p> <pre><code>struct req_scoped_alloc_pool { unsigned char *base_pointer; size_t capacity; size_t bytes_used; } struct req_scoped_alloc_pool global_alloc_pool; int init(…) { // … size_t GLOBAL_REQ_ALLOC_POOL_CAPACITY = 2048; void *alloc_res = malloc(GLOBAL_REQ_ALLOC_POOL_CAPACITY) if(alloc_res == NULL) { return SOME_ERROR_CODE } global_alloc_pool.base_pointer = (unsigned char *)alloc_res; global_alloc_pool.capacity = GLOBAL_REQ_ALLOC_POOL_CAPACITY; global_alloc_pool.bytes_used = 0; // … return 0; } void erase_req_allocs() { mem_clear(global_alloc_pool.base_pointer, global_alloc_pool.capacity); global_alloc_pool.bytes_used = 0; } void assert_empty_global_alloc_pool(HDL a_handle) { if(global_alloc_pool.bytes_used != 0) { // some more severe error reporting using RPC handle } cleanup: } </code></pre> <p>Each remotely callable function checks the state of the global pool beforehand and clears it afterwards:</p> <pre><code>int some_external_function(HDL rpc_handle) { assert_empty_global_alloc_pool(rpc_handle); // do stuff set_result_values(rpc_handle, …) // or communicate errors erase_req_allocs(); } </code></pre> <p>Plain pointers will be replaced with fat pointers. This will make passing around pointer size information the comfortable default case. (Currently there are a lot of cases where the caller has to know how large the allocated memory for the passed pointer has to be and there are neither checks whether they get it right nor alarms when the called function is being refactored to require more memory):</p> <pre><code>typedef struct u8_vector { unsigned char *base_pointer; size_t capacity; // naming inspired by C++ vector size_t size; // naming inspired by C++ vector } u8_vector u8_vector empty_u8_vector() { u8_vector res;uiae res.base_pointer = NULL; res.capacity = 0; res.size = 0; } </code></pre> <p>Regarding error propagation I had to compromise. Ideally I would like each function to return a struct which contains the error code and a payload. The payload is then unwrapped to a local variable via a macro, which will also check the error code. This way, to access the payload you would always check the error code. Unfortunately I haven't been able to design a solution with sufficient usability without having a C++ like <code>auto</code> keyword available. I thus compromised to directly allow payload structs as return values and store the error code in a global variable:</p> <pre><code>int global_error = 0; #define RAISE_ERROR(err_code) {global_error = err_code; goto cleanup;} #define CHECK_ERROR {if(global_error != 0) {goto cleanup;}} </code></pre> <p>Request scoped memory allocations use this global error code:</p> <pre><code>u8_vector req_malloc_u8(size_t vec_capacity) { u8_vector res = empty_u8_vector(); // default to empty vector if callee forgets error handling // Round up to multiples of 8 bytes for simple data structure alignment int remainder = vec_capacity % 8; if(remainder != 0) { vec_capacity += 8 - remainder; } if(global_alloc_pool.bytes_used + vec_capacity &gt; global_alloc_pool.capacity) { RAISE_ERROR(SOME_ERROR_CODE); } res.base_pointer = global_alloc_pool.base_pointer + global_alloc_pool.capacity; res.capacity = vec_capacity; res.size = 0; cleanup: return res; } void append_from_char_p(u8_vector *target, unsigned char* source, size_t size) { if(target-&gt;capacity - target-&gt;size &lt; size) { RAISE_ERROR(SOME_ERROR_CODE); } target-&gt;capacity += target-&gt;size; memcpy(target-&gt;base_pointer + target-&gt;size, source, size); cleanup: } </code></pre> <h3>Now for some non-trivial usage example: Expansion of nibbles in a byte vector:</h3> <pre><code>typedef struct nibble_vector { unsigned char *base_pointer; size_t capacity; // naming inspired by C++ vector size_t size; // naming inspired by C++ vector } nibble_vector nibble_vector req_malloc_nibble(size_t vec_capacity) { nibble_vector res; u8_vector u8_res = req_malloc_u8(vec_capacity); CHECK_ERROR; res.base_pointer = u8_res.base_pointer; res.capacity = u8_res.capacity; res.size = u8_res.size; cleanup: return res; } </code></pre> <p>As a convention, vectors passed to functions are read-only read when they are passed as struct and read-write when passed as pointers. This hopefully greatly simplifies reading method invocations:</p> <pre><code>void push_back(nibble_vector *target, unsigned char new_nibble) { if(target-&gt;capacity - target-&gt;size &lt; 1) { RAISE_ERROR(SOME_ERROR_CODE); } target-&gt;base_pointer[target-&gt;size] = new_nibble; target-&gt;size += 1; cleanup: } // Expand each byte of compressed input vector to two half bytes ("nibbles") in result vector // Fill nibbles in input vector are left out nibble_vector expand_bytes_to_nibbles(u8_vector compressed, unsigned char fill_nibble) { nibble_vector res = empty_nibble_vector; res = req_malloc_nibble(compressed); CHECK_ERROR; for(int i=0; i&lt;compressed.size; ++i) { unsigned char current_nibble; current_nibble = (compressed.base_pointer[i] &amp; 0xF0) &gt;&gt; 4); if(current_nibble != fill_nibble) { push_back(&amp;res, current_nibble); CHECK_ERROR; } current_nibble = (compressed.base_pointer[i] &amp; 0x0F) &gt;&gt; 0); if(current_nibble != fill_nibble) { push_back(&amp;res, current_nibble); CHECK_ERROR; } } cleanup: return res; } </code></pre> <p><strong>Is this a good design?</strong></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T12:23:20.533", "Id": "213799", "Score": "4", "Tags": [ "c", "error-handling", "memory-management" ], "Title": "Memory managment for RPC code in C" }
213799
<p>Given a 2-D input matrix, I need to pick elements from it.</p> <blockquote> <p>constraint: you can pick one number at each row, each column</p> <p>given: number boards are given expected</p> <p>output: print least sum of numbers what you took!</p> </blockquote> <p>I think I found a firm framework like method for DPS in python. But I want this to be confirmed, please comment:</p> <pre class="lang-py prettyprint-override"><code>def recurse(row, n): global mean row += 1 #choose next row currentsum = sum(boards[row][column] for row, column in enumerate(answersheet[0:row])) if currentsum &gt; mean: ## put your bounding function here return if row == n: ##when you get to bottom of recursion tree if currentsum &lt; mean: mean = currentsum return for column in range(n): #recursive part if column not in answersheet[:row]: #check if column is already selected! [critical][pythonic] answersheet[row] = column recurse(row, n) boards = [[5, 2, 1, 1, 9], [3, 3, 8, 3, 1], [9, 2, 8, 8, 6], [1, 5, 7, 8, 3], [5, 5, 4, 6, 8] ] n = len(boards) answersheet = [-1] * n #using index as a row, #value as column what you took at that row row = -1 mean = 9999999 recurse(row, n) print(f&quot;the least {mean}&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T13:47:54.047", "Id": "413547", "Score": "0", "body": "How big can `n` become? Do you need to handle only small inputs, 1000x1000 matrices or millions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:54:33.803", "Id": "413563", "Score": "0", "body": "n <1000, because of recursion depth limit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:22:08.077", "Id": "413571", "Score": "0", "body": "Well, how big can `n` theoretically become (not just with your implementation)?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T12:35:44.473", "Id": "213801", "Score": "1", "Tags": [ "python", "programming-challenge", "depth-first-search" ], "Title": "Choose numbers from a grid, minimising the sum" }
213801
<p>So I made a bruteforce program for sha-X hashes and MD5 using wordlists in Python. I know Python is probably one of the worst languages for this, but it's only for learning purposes. I think this was a good way for me to learn optimization. I am still a beginner in coding, so my code might have some things that aren't the best :) I am searching for some help on optimizing the program and also learn about multiprocessing and if there is a way I can add it to my program :)</p> <pre><code>#!/usr/bin/env python # coding:utf-8 # # Author: Thewizy # Date: 19-02-2019 # Purpose: Find password from hashes using wordlists # Prerequisites: A big wordlist and of course hashes # # And now - the fun part :&gt; import os import datetime import argparse import itertools from urllib.request import hashlib from progress.bar import Bar def main(): normal() def countlines_hashfile(): with open(h) as myfile: count = sum(1 for line in myfile) return count def countlines_wordfile(): with open(w) as myfile: count2 = sum(1 for line in myfile) return count2 def wordlist_options(): path = "tmp" if not os.path.exists(path): os.makedirs(path) with open(w) as f: with open(os.path.join(path, "tmp.txt"), 'w') as temp_file: for line in f: if args.replace: line = replace(line) if args.repeat: line = line + line if args.uppercase: line = line.upper() if args.title: line = line.title() temp_file.write(line) temp_file_name = temp_file.name return temp_file_name def hashmethod(): hash_file = open(h).read() for hash in hash_file.split("\n"): # find type of hash are the hashes in the hash file with the length of it else raise an error message lenght = len(hash) if lenght == 32: # MD5 hashmethod_list.append(1) elif lenght == 40: # sha1 hashmethod_list.append(2) elif lenght == 56: # sha224 hashmethod_list.append(3) elif lenght == 64: # sha256 hashmethod_list.append(4) elif lenght == 96: # sha284 hashmethod_list.append(5) elif lenght == 128: # sha512 hashmethod_list.append(6) else: hashmethod_list.append(0) print(" /!\ Invalid Hash: " + hash + " /!\ ") hash_list.append(hash) def wordhasher(word,hashline): if hashmethod_list[hashline] == 1: hashedguess = hashlib.md5(bytes(word, "utf-8")).hexdigest() elif hashmethod_list[hashline] == 2: hashedguess = hashlib.sha1(bytes(word, "utf-8")).hexdigest() elif hashmethod_list[hashline] == 3: hashedguess = hashlib.sha224(bytes(word, "utf-8")).hexdigest() elif hashmethod_list[hashline] == 4: hashedguess = hashlib.sha256(bytes(word, "utf-8")).hexdigest() elif hashmethod_list[hashline] == 5: hashedguess = hashlib.sha384(bytes(word, "utf-8")).hexdigest() elif hashmethod_list[hashline] == 6: hashedguess = hashlib.sha512(bytes(word, "utf-8")).hexdigest() else: hashedguess = "ERROR" parser.error(" /!\ Invalid Hash Line: " + str(hashline + 1) + " /!\ ") # should QUIT doesnt work now return hashedguess def normal(): hashline = 0 i = 0 word_list = open(w).read() bar = Bar("&lt;&lt;PASSWORD TESTED&gt;&gt;", max=lines_wordfile) for word in word_list.split("\n"): if args.prog: bar.next() savedword = word while True: # Reset the hash line to line 0 when all hashes have been checked and print the guessed password if hashline &gt;= lines_hashfile: hashline = 0 if args.show: print(word) if args.numbers: l = len(digits_list) if i - 1 &gt;= int(l -1): i = 0 break else: nd = digits_list[i] i += 1 if args.front: word = str(nd) + savedword elif args.extremity: word = str(nd) + savedword + str(nd) else: word = savedword + str(nd) else: break # Read the next hash in the list hash = hash_list[hashline] # Check if the word hashed is equal to the hash in file if wordhasher(word,hashline) == hash: result = word + " Line " + str(hashline + 1) + ": " + hash result_list.append(result) hashline += 1 if args.prog: bar.finish() readresult() def replace(word): word = word.replace("e", "3").replace("a", "4").replace("o", "0") return word def dates(): dates = [] dates_day = ["1","2","3","4","5","6","7","8","9","01","02","03","04","05","06","07","08","09","10","11","12","13", "14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"] dates_month = ["1","2","3","4","5","6","7","8","9","01","02","03","04","05","06","07","08","09","10","11","12"] for days, month in itertools.product(dates_day, dates_month): dates.append(days+month) for years in range(1875,2020): dates.append(years) return dates def numbers(number_digits): i = 0 digits_list = [] while i &lt;= int(number_digits): n = str(i) digits_list.append(n) i += 1 print(digits_list) return digits_list def readresult(): end_time = datetime.datetime.now() print("Time taken: -{" + str(end_time - start_time) + "}-") if not result_list: print("No Password Found") print(result_list) else: for a in result_list: print(a) if args.save: s = open(save, "a") s.write(str(result_list)) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Ultimate Sha1/256/512 and MD5 hashes Bruteforcer with dictionaries", prog="UltimateBrutforcer", usage="%(prog)s.py &lt;your_wordlist.txt&gt; &lt;your_hashlist.txt&gt; -option1 etc...") parser.add_argument("wordlist", help="The wordlist you wish to use.(Example: wordlist.txt)", type=str) parser.add_argument("hashlist", help="The hashlist you wish to find the password.(Example: hashlist.txt)", type=str) parser.add_argument("-n", "--numbers",default=False, dest="numbers", action="store_true", help="Put numbers at the end of each word") parser.add_argument("--common", default=False, dest="common", action="store_true", help="Use most common number used in password only") parser.add_argument("--dates", default=False, dest="dates", action="store_true", help="Use all possible dates") parser.add_argument("--fr", default=False, dest="front", action="store_true", help="Change the numbers to be at the beggining of the word") parser.add_argument("--ex", default=False, dest="extremity", action="store_true", help="Change the numbers to be at the extremity of the word") parser.add_argument("-r", "--replace", default=False, dest="replace", action="store_true", help="Replace every E by 3, every A by 4, and every = O by 0(zéro)") parser.add_argument("-p", "--repeat", default=False, dest="repeat", action="store_true", help="repeat the word two times") parser.add_argument("-u", "--upper", default=False, dest="uppercase", action="store_true", help="Change the word in uppercase") parser.add_argument("-t", "--title", default=False, dest="title", action="store_true", help="Write the word as a title, ex: title word -&gt; Title Word") parser.add_argument("-s", "--save", default=False, dest="save", action="store_true", help="Save the results in a text file.") parser.add_argument("-pr", "--progression", default=False, dest="prog", action="store_true", help="Show the progression of the scan with a progression bar" "might be useful to explain how Bruteforce works to some people") parser.add_argument("-sh", "--show", default=False, dest="show", action="store_true", help="Show the password tested(/!\TAKES A LOT MORE TIME/!\)" "might be useful to explain how Bruteforce works to some people") args = parser.parse_args() # All errors about options: if args.front and not args.numbers: parser.error('-n is required when --front is set.') if args.extremity and not args.numbers: parser.error('-n is required when --front is set.') if args.common and not args.numbers: parser.error('-n is required when --common or -c is set.') if args.extremity and args. front: parser.error('you cannot put those two options to -n') if args.common and args.dates: parser.error('you cannot put those two options to -n.') if args.show and args.prog: parser.error('you cannot put those two options together.') # global variables: w = args.wordlist h = args.hashlist lines_hashfile = countlines_hashfile() lines_wordfile = countlines_wordfile() result_list = [] hashmethod_list = [] hash_list = [] if args.replace or args.repeat or args.uppercase or args.title: w = wordlist_options() if args.numbers: digits_list = [] if args.common: digits_list = ["1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789", "00", "01", "10", "11", "13", "19","22", "23", "42", "69", "77", "99", "314", "666", "777", "111", "100", "200"] elif args.dates: digits_list = dates() else: while True: number_digits = input("How many numbers do you want to put" "(/!\max is 6 numbers!\)") if number_digits.isdigit() and int(number_digits) &lt;= 6: number_digits = "9" * int(number_digits) digits_list = numbers(number_digits) number_digits = "" break else: parser.error('A number lower or equal to 6 is required for the lenght of the numbers') if args.save: run = True while run: save = input("How do you want to name the save file?") if save != "": save = save+".txt" break print("\n" + "-Found [" + str(lines_hashfile) + "] hashes in hashlist " + "\n" + "-Found [" + str(lines_wordfile) + "] words in wordlist") hashmethod() input("\n"+"Press &lt;ENTER&gt; to start") start_time = datetime.datetime.now() # Save the time the program started main() print("Scan finished") try: os.remove("tmp") except PermissionError: print("PermissionError: tmp file couldn't be removed (need administrator permissions)") </code></pre> <p>You can also find the code with wordlists and hashlist for test here: <a href="https://github.com/Thewizy/UltimateBruteforcer" rel="nofollow noreferrer">https://github.com/Thewizy/UltimateBruteforcer</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:18:56.013", "Id": "413554", "Score": "0", "body": "Can you add the actual code? or reasonable chunk of it? (Similar to your other questions) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:29:31.977", "Id": "413555", "Score": "0", "body": "I know my questions are similar :) but this time the code is not as small :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:42:10.083", "Id": "413559", "Score": "0", "body": "I did this but i had to add spaces myself the indentation won't work I guess I'm going to do it with my spacebar" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:59:19.763", "Id": "413566", "Score": "1", "body": "sorry I didn't mean it is similar to other questions. I meant add code as you did in other questions :) This looks nice now that code is added." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:00:11.600", "Id": "413567", "Score": "0", "body": "Oh yes misunderstood :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T17:38:53.413", "Id": "413590", "Score": "0", "body": "Unless the misspelling is an intentional skirting of keyword restrictions, you might want to change `lenght` to something else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T17:50:24.500", "Id": "413592", "Score": "0", "body": "@LSpice No keyword issues. But write an answer." } ]
[ { "body": "<p>Just a few quick comments</p>\n\n<ul>\n<li><p>You can use a dictionary as mapping file</p>\n\n<p>First you check the length of the bytes and use an <code>temp</code> variable <code>1, 2, 3, 4, 5, 6</code> to know which hashing algo to use</p>\n\n<blockquote>\n<pre><code>lenght = len(hash)\nif lenght == 32: # MD5\n hashmethod_list.append(1)\n...\nif hashmethod_list[hashline] == 1:\n hashedguess = hashlib.md5(bytes(word, \"utf-8\")).hexdigest()\n</code></pre>\n</blockquote>\n\n<p>Thi can be simplified using a dictionary that maps the length of the hash to the correct function</p>\n\n<pre><code>BYTELEN_TO_HASH = {\n 32 : hashlib.md5,\n 40 : hashlib.sha1,\n 56 : hashlib.sha224,\n 64 : hashlib.sha256,\n 96 : hashlib.sha384,\n 128 : hashlib.sha512\n}\n\ndef brute_password(hash_line):\n hash_func = BYTELEN_TO_HASH.get(len(hash_line), None)\n if hash_func is None:\n return f'Incorrect hash: {hash_line} with length {len(hash_line)}'\n\n\n for word in read_wordlist():\n if hash_func(bytes(word, \"utf-8\")).hexdigest() == hash_line:\n return word\n\n return 'No matching password found'\n</code></pre>\n\n<p>This is alot shorter and removes those <code>magic</code> numbers</p></li>\n<li><p>Creating a new wordlist for each optional argument will cost alot of IO operations</p>\n\n<p>Instead you could read the file and alter the word after you read it from the wordlist</p>\n\n<p>We could possibly? make another optional function dictionary</p>\n\n<pre><code>OPTIONS = {\n 'U', str.upper\n ...\n}\n\noptional = OPTIONS.get(optional, lambda x: x)\nfor word in read_wordlist():\n word = optional(word)\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:22:14.250", "Id": "413572", "Score": "0", "body": "Ok thanks a lot I didn't know i could use dictionaries to change a command based on a value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:28:04.870", "Id": "413575", "Score": "0", "body": "About the wordlist I actually had ealier version of the program where the program had no tmp file and was reading the file and altering them as they come but I've see a really small performance gain by applying the options first" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:28:51.810", "Id": "413576", "Score": "0", "body": "But since you have to wait for the file to be ready it's actually a lost of time :/ so I might removed the tmp file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:29:22.607", "Id": "413577", "Score": "0", "body": "You don;t need to alter the file in place. Just read the wordlist as usual and alter the word's value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:30:38.633", "Id": "413578", "Score": "0", "body": "You are right it's easier and faster" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:36:36.537", "Id": "413579", "Score": "0", "body": "I've expanded on the second point a bit. Have to go I hope you receive some more good answers :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:51:38.997", "Id": "413581", "Score": "0", "body": "Really good idea haven't tought of this :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:53:11.240", "Id": "413582", "Score": "1", "body": "You can do `OPTIONS = {\"U\": str.upper, ...}` directly. Also `optional = OPTIONS.get(optional, lambda x: x)` might be a better fall-back than `None` which will then raise an error because `None` is not callable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:59:24.180", "Id": "413583", "Score": "1", "body": "@Graipher Ahh yes `lambda x: x` I was looking for that :) I also added the `str.upper` but is was more to show you could supply your own function" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:17:11.553", "Id": "213813", "ParentId": "213807", "Score": "10" } } ]
{ "AcceptedAnswerId": "213813", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T14:14:01.060", "Id": "213807", "Score": "10", "Tags": [ "python", "performance", "python-3.x", "multiprocessing" ], "Title": "Python 3.7 UltimateBruteforcer" }
213807
<p>From leet code question: <a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">https://leetcode.com/problems/lru-cache/</a></p> <blockquote> <p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p> <p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.</p> <p>Follow up: Could you do both operations in O(1) time complexity?</p> <p>Example:</p> <pre><code>LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 </code></pre> </blockquote> <p><strong>Code:</strong> Filename: <code>lru_cache.py</code></p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Node: def __init__(self, key: int, val: int, prv=None, nxt=None): self.prv = prv self.nxt = nxt self.val = val self.key = key def __str__(self): nx = str(self.nxt) return "{}:{} -&gt; {}".format(self.key, self.val, nx) class LRUCache: def __init__(self, capacity: int): """ :type capacity: int """ self.first = None self.last = None self.cap = capacity self.cache = {} self.size = 0 def get(self, key): """ :type key: int :rtype: int """ if key not in self.cache: return -1 node = self.cache[key] if self.first is self.last: return node.val if node is self.last: return node.val if node is self.first: nxt = node.nxt nxt.prv = None self.first = nxt node.nxt = None else: # In the middle nxt = node.nxt prv = node.prv node.nxt = None prv.nxt = nxt nxt.prv = prv self.last.nxt = node node.prv = self.last self.last = node return node.val def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if self.get(key) != -1: # Already have self.cache[key].val = value return node = Node(key, value) if not self.first: self.size = 1 self.first = node self.last = node self.cache[key] = node return self.cache[key] = node self.last.nxt = node node.prv = self.last self.last = node self.size = len(self.cache) if self.size &gt; self.cap: # Need to remove first = self.first nxt = first.nxt nxt.prv = None self.first = nxt del self.cache[first.key] self.size = self.cap def __str__(self): return "LRUCache:: {}".format(self.first) def _test(): cache = LRUCache(2) cache.put(1, 1) cache.put(2, 2) assert cache.get(1) == 1 # returns 1 cache.put(3, 3) # evicts key 2 assert str(cache) == "LRUCache:: 1:1 -&gt; 3:3 -&gt; None" assert cache.get(2) == -1 # returns -1 (not found) cache.put(4, 4) # evicts key 1 assert str(cache) == "LRUCache:: 3:3 -&gt; 4:4 -&gt; None" assert cache.get(1) == -1 # returns -1 (not found) assert cache.get(3) == 3 # returns 3 assert cache.get(4) == 4 # returns 4 assert str(cache) == "LRUCache:: 3:3 -&gt; 4:4 -&gt; None" if __name__ == "__main__": _test() </code></pre> <p><strong>What I want reviewed:</strong></p> <ol> <li>How pythonic the code is? How can I improve it.</li> <li>Is there any area I can optimise performance ? (This passes all tests on leet-code)</li> <li>Readability improvements?</li> <li>Structure of the code file? Can we place things better?</li> </ol> <p>You are welcome to be strict and brutal.</p> <p><strong>Additional info:</strong></p> <ul> <li>I've used <strong>black</strong> to format code.</li> </ul>
[]
[ { "body": "<h3>Use more abstract data types</h3>\n\n<p>In the current implementation two behaviors are mixed together:</p>\n\n<ul>\n<li>Caching</li>\n<li>Linked list manipulation</li>\n</ul>\n\n<p>It would be better if the linked list manipulation was encapsulated in a dedicated abstract data type. Then <code>LRUCache</code> could use an instance of it, and perform operations that have nice descriptive names like <code>append_node</code>, <code>delete_node</code>, instead of blocks of nameless code. It will reveal more clearly the implemented logic of both the caching and linked list behaviors, and be more intuitively readable.</p>\n\n<h3>Avoid unclear side effects</h3>\n\n<p>At first glance I found this piece surprising in <code>put</code>:</p>\n\n<blockquote>\n<pre><code>if self.get(key) != -1:\n # Already have\n self.cache[key].val = value\n return\n</code></pre>\n</blockquote>\n\n<p>Why <code>self.get(key) != -1</code> instead of <code>key not in self.cache</code>?\nThe <code>self.get</code> is of course necessary,\nfor its side effect of moving the node to the end.\nThis may be subjective,\nbut I would prefer to have an explicit private method that moves the node,\nand call it from both <code>get</code> and <code>put</code>.\nThat will make the intention perfectly clear.\nAnother reason I prefer that is to eliminate using the magic value <code>-1</code> more than necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T18:08:57.717", "Id": "213825", "ParentId": "213811", "Score": "3" } } ]
{ "AcceptedAnswerId": "213825", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:04:22.977", "Id": "213811", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "LRUCache for integers using dict + linkedlist" }
213811
<p>Here is my implementation of Conway's Game of Life in C++ which takes advantage of multi-threading. I'm using <a href="https://www.sfml-dev.org/" rel="noreferrer">SFML 2.5.1</a> for a graphics library and CMake. I also use SFML's <code>Vector</code> classes for convenience.</p> <p>Right now the game runs in a fixed sized grid world and the <code>update()</code> function that applies the game rules splits the world up into parts based on how many cores are available on the current machine and updates the sections in parallel. The cells and background areas are color-coded to represent the boundaries where the world is being run on the different CPU threads. The user can draw in more "live" cells by clicking and holding the left mouse button over the game grid. The world wraps around the edges, so cells at the bottom-right corner will consider the cells in the top-left to be some of their neighbors.</p> <p>I've written this project because I'm a long-time C# developer trying to learn C++, I wanted to practice writing parallel code, and to practice with a project that needs to run fast (with memory requirements being less important right now).</p> <p>Some highlights of what I'm trying to get out of this project and this code review:</p> <ul> <li>How to write performant C++ code</li> <li>Learn the STL</li> <li>How to write clean, readable, reusable C++ code <ul> <li>Good C++ syntax</li> <li>Good comment placement/syntax</li> </ul></li> <li>Learn the things that C++ does that C# doesn't <ul> <li>Memory management</li> <li>Pointers/References and to know when to use Pointers</li> <li>Behind-the-scenes mechanisms like auto-instantiation of variables (e.g. pushing a new object into a <code>std::vector&lt;std::pair&gt;</code> like <code>vector.push_back({"string", true});</code> automatically instantiates a new <code>pair</code> object.)</li> </ul></li> </ul> <p><a href="https://github.com/k-vekos/GameOfLife" rel="noreferrer">GitHub Repo</a></p> <p><strong>Main.cpp</strong></p> <pre><code>#include "GameOfLife.h" #include "WorldRenderer.h" #include &lt;iostream&gt; #include &lt;SFML/Graphics.hpp&gt; using namespace std; static const int WORLD_SIZE_X = 256; static const int WORLD_SIZE_Y = 256; int main() { // create the window sf::RenderWindow window(sf::VideoMode(256, 256), "Game of Life"); // scale the image up 2x size window.setSize(sf::Vector2u(512, 512)); // disable vsync and uncap framerate limit window.setVerticalSyncEnabled(false); window.setFramerateLimit(0); // Create the game GameOfLife game(sf::Vector2i(WORLD_SIZE_X, WORLD_SIZE_Y)); // Create a world renderer WorldRenderer worldRenderer; // Track if mouse button is being held down bool mouseHeld = false; // run the program as long as the window is open while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); // capture if the user is holding left mouse button down if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) mouseHeld = true; } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) mouseHeld = false; } } // clear the window with black color window.clear(sf::Color::Black); // if left mouse button held down then make cells under cursor alive and pause simulation if (mouseHeld) { auto mousePosition = sf::Mouse::getPosition(window); // normalize mouse pos int x = (mousePosition.x / 512.0f) * WORLD_SIZE_X; int y = (mousePosition.y / 512.0f) * WORLD_SIZE_Y; // set cell under cursor to alive game.setCell(x, y, true); } else { // update the game world game.update(); } // render the game worldRenderer.render(window, game); // end the current frame window.display(); } return 0; } </code></pre> <p><strong>GameOfLife.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;SFML/Graphics.hpp&gt; #include "Cell.h" class GameOfLife { public: GameOfLife(sf::Vector2i size); virtual ~GameOfLife() = default; // Returns a reference to the cell value at the given grid position. uint8_t &amp; getCell(int x, int y); // Returns a vector of the given cell's grid position by it's cell index. sf::Vector2i get2D(int index); // Updates the state of the game world by one tick. void update(); // Update the cells from position start (inclusive) to position end (exclusive). std::vector&lt;Cell&gt; GameOfLife::doUpdate(int start, int end, int coreIdx); // Set the value of the cell at the given grid position to the given alive state. void setCell(int x, int y, bool alive); // A cache of all the alive cells at the end of the update() call. std::vector&lt;Cell&gt; aliveCells; // The maximum amount of threads to be used for update(). const int maxThreads; // Represents the width and height of the simulated world. sf::Vector2i worldSize; // Returns a color to use for cells/backgrounds based on the thread ID #. sf::Color getThreadColor(int index); private: // A 1D representation of the 2D grid that is the world. std::vector&lt;uint8_t&gt; world; // A buffer where the next world state is prepared, swapped with world at end of update(). std::vector&lt;uint8_t&gt; worldBuffer; }; </code></pre> <p><strong>GameOfLife.cpp</strong></p> <pre><code>#include "GameOfLife.h" #include "Cell.h" #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;future&gt; #include &lt;chrono&gt; GameOfLife::GameOfLife(sf::Vector2i size) : worldSize(size), world(size.x * size.y, false), worldBuffer(world), maxThreads(std::thread::hardware_concurrency()) { aliveCells.reserve(size.x * size.y); // reserve space for worst-case (all cells are alive) // place an "acorn" int midX = worldSize.x / 2; int midY = worldSize.y / 2; getCell(midX + 0, midY + 0) = 1; getCell(midX + 1, midY + 0) = 1; getCell(midX + 4, midY + 0) = 1; getCell(midX + 5, midY + 0) = 1; getCell(midX + 6, midY + 0) = 1; getCell(midX + 3, midY + 1) = 1; getCell(midX + 1, midY + 2) = 1; } uint8_t&amp; GameOfLife::getCell(int x, int y) { return world[y * worldSize.x + x]; } sf::Vector2i GameOfLife::get2D(int index) { int y = index / worldSize.x; int x = index % worldSize.x; return { x, y }; } sf::Color GameOfLife::getThreadColor(int index) { switch (index % 4) { case 0: return sf::Color::Red; break; case 1: return sf::Color::Green; break; case 2: return sf::Color::Blue; break; case 3: return sf::Color::Yellow; break; } } std::vector&lt;Cell&gt; GameOfLife::doUpdate(int start, int end, int coreIdx) { std::vector&lt;Cell&gt; aliveCells; aliveCells.reserve(end - start); // reserve space for worst case (all alive cells) for (int i = start; i &lt; end; i++) { auto pos = get2D(i); // # of alive neighbors int aliveCount = 0; // check all 8 surrounding neighbors for (int nX = -1; nX &lt;= 1; nX++) // nX = -1, 0, 1 { for (int nY = -1; nY &lt;= 1; nY++) // nY = -1, 0, 1 { // make sure to skip the current cell! if (nX == 0 &amp;&amp; nY == 0) continue; // wrap around to other side if neighbor would be outside world int newX = (nX + pos.x + worldSize.x) % worldSize.x; int newY = (nY + pos.y + worldSize.y) % worldSize.y; aliveCount += getCell(newX, newY); } } // Evaluate game rules on current cell bool dies = aliveCount == 2 || aliveCount == 3; bool lives = aliveCount == 3; worldBuffer[i] = world[i] ? dies : lives; // if the cell's alive push it into the vector if (worldBuffer[i]) aliveCells.push_back(Cell(pos, getThreadColor(coreIdx))); } return aliveCells; } void GameOfLife::update() { // clear aliveCells cache aliveCells.clear(); // divide the grid into horizontal slices int chunkSize = (worldSize.x * worldSize.y) / maxThreads; // split the work into threads std::vector&lt;std::future&lt;std::vector&lt;Cell&gt;&gt;&gt; asyncTasks; for (int i = 0; i &lt; maxThreads; i++) { int start = i * chunkSize; int end; if (i == maxThreads - 1) // if this is the last thread, endPos will be set to cover remaining "height" end = worldSize.x * worldSize.y; else end = (i + 1) * chunkSize; asyncTasks.push_back( std::async(std::launch::async, [this, start, end, i] { return this-&gt;doUpdate(start, end, i); }) ); } // Wait until all async tasks are finished for (auto&amp;&amp; task : asyncTasks) { // TODO Why use 'auto&amp;&amp;'? auto aliveCellsPartial = task.get(); aliveCells.insert(std::end(aliveCells), std::begin(aliveCellsPartial), std::end(aliveCellsPartial)); } // apply updates world.swap(worldBuffer); } void GameOfLife::setCell(int x, int y, bool alive) { // constrain x and y x = std::max(std::min(x, (int) worldSize.x - 1), 0); y = std::max(std::min(y, (int) worldSize.y - 1), 0); getCell(x, y) = alive; aliveCells.push_back(Cell(sf::Vector2i(x, y), sf::Color::White)); } </code></pre> <p><strong>WorldRenderer.h</strong></p> <pre><code>#pragma once #include &lt;SFML/Graphics.hpp&gt; #include &lt;vector&gt; #include "GameOfLife.h" class WorldRenderer { public: WorldRenderer(); ~WorldRenderer(); // Renders the given game to the given window. void render(sf::RenderWindow&amp; window, GameOfLife&amp; world); private: // Vertex points for the pending draw call. std::vector&lt;sf::Vertex&gt; m_vertexPoints; // Adds a cell-sized quad in the "grid position" specified. void addQuad(int gridX, int gridY, sf::Color color); // Adds a darker colored quad in the given coordinates. void addBackgroundQuad(sf::Vector2f topLeft, sf::Vector2f bottomRight, sf::Color color); // Renders the background colors which correspond to the thread ID and the cells they are updating. void renderBackgrounds(sf::RenderWindow&amp; window, GameOfLife&amp; world); // Returns a darker variant of the given color. sf::Color darkenColor(sf::Color input); }; </code></pre> <p><strong>WorldRenderer.cpp</strong></p> <pre><code>#include "WorldRenderer.h" WorldRenderer::WorldRenderer() { } WorldRenderer::~WorldRenderer() { } void WorldRenderer::addQuad(int gridX, int gridY, sf::Color color) { sf::Vertex topLeft; sf::Vertex topRight; sf::Vertex bottomLeft; sf::Vertex bottomRight; float gridXFloat = gridX * 1.0f; float gridYFloat = gridY * 1.0f; topLeft.position = { gridXFloat, gridYFloat }; topRight.position = { gridXFloat + 1, gridYFloat }; bottomLeft.position = { gridXFloat, gridYFloat + 1 }; bottomRight.position = { gridXFloat + 1, gridYFloat + 1 }; topLeft.color = color; topRight.color = color; bottomLeft.color = color; bottomRight.color = color; m_vertexPoints.push_back(topLeft); m_vertexPoints.push_back(bottomLeft); m_vertexPoints.push_back(bottomRight); m_vertexPoints.push_back(topRight); } void WorldRenderer::addBackgroundQuad(sf::Vector2f topLeft, sf::Vector2f bottomRight, sf::Color color) { sf::Vertex vTopLeft; sf::Vertex vTopRight; sf::Vertex vBottomLeft; sf::Vertex vBottomRight; vTopLeft.position = topLeft; vTopRight.position = { bottomRight.x, topLeft.y }; vBottomLeft.position = { topLeft.x, bottomRight.y }; vBottomRight.position = bottomRight; vTopLeft.color = color; vTopRight.color = color; vBottomLeft.color = color; vBottomRight.color = color; m_vertexPoints.push_back(vTopLeft); m_vertexPoints.push_back(vBottomLeft); m_vertexPoints.push_back(vBottomRight); m_vertexPoints.push_back(vTopRight); } void WorldRenderer::render(sf::RenderWindow &amp; window, GameOfLife &amp; game) { // clear m_cellVertexPoints m_vertexPoints.clear(); // draw backgrounds for "core zones" renderBackgrounds(window, game); // populate m_cellVertexPoints for (auto cell : game.aliveCells) { addQuad(cell.position.x, cell.position.y, cell.color); } // draw quads to window window.draw(m_vertexPoints.data(), m_vertexPoints.size(), sf::Quads); } void WorldRenderer::renderBackgrounds(sf::RenderWindow &amp; window, GameOfLife &amp; world) { int cellsPerCore = world.worldSize.x * world.worldSize.y / world.maxThreads; // first draw the background color of the final core index addBackgroundQuad( sf::Vector2f(0, 0), sf::Vector2f(world.worldSize.x, world.worldSize.y), darkenColor(world.getThreadColor(world.maxThreads - 1)) ); // draw the remaining core background colors on top, in reverse order for (int i = world.maxThreads - 2; i &gt;= 0; i--) { auto end = world.get2D(cellsPerCore * (i + 1)); addBackgroundQuad( sf::Vector2f(0, 0), sf::Vector2f(world.worldSize.x, end.y), darkenColor(world.getThreadColor(i)) ); } } sf::Color WorldRenderer::darkenColor(sf::Color input) { return sf::Color(input.r / 3, input.g / 3, input.b / 3); } </code></pre> <p><strong>Cell.h</strong></p> <pre><code>#pragma once #include &lt;SFML/Graphics.hpp&gt; class Cell { public: Cell(sf::Vector2i position, sf::Color color); ~Cell(); sf::Vector2i position; sf::Color color; }; </code></pre> <p><strong>Cell.cpp</strong></p> <pre><code>#include "Cell.h" Cell::Cell(sf::Vector2i position, sf::Color color) : position(position), color(color) { } Cell::~Cell() { } </code></pre>
[]
[ { "body": "<p>Don't make destructors if you don't need to. The default behavior is plenty for your use case.</p>\n\n<p>Why is the destructor of <code>GameOfLife</code> virtual? You don't have a class that would need to inherit from it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T20:57:53.610", "Id": "413601", "Score": "0", "body": "I think you're right about the destructors and I didn't mean to mark `GameOfLife` as virtual. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:05:17.480", "Id": "213817", "ParentId": "213814", "Score": "3" } }, { "body": "<h1>Avoid importing the whole of <code>std</code> namespace</h1>\n\n<p>Bringing all names in from a namespace is problematic; <code>namespace std</code> particularly so. See <a href=\"//stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>.</p>\n\n<h1>Include the right headers</h1>\n\n<p><code>Main.cpp</code> includes <code>&lt;iostream&gt;</code>, but appears not to use anything declared there.</p>\n\n<p>The same is true of <code>GameOfLife.cpp</code>.</p>\n\n<p>On the other hand, we're using <code>std::uint8_t</code> but failing to include <code>&lt;cstdint&gt;</code> to declare it. Although it might be brought in by one of the other headers on a particular platform, we shouldn't depend on that if we want to be portable.</p>\n\n<h1>Naming conventions</h1>\n\n<p>We normally reserve all-uppercase names for preprocessor macros, to mark them as dangerous in code. Using such names for plain constants subverts that convention, misleading the reader.</p>\n\n<h1>Fix compilation errors</h1>\n\n<p>Remove the extra qualification <code>GameOfLife::</code> on member <code>doUpdate</code>.</p>\n\n<p><code>GameOfLife::getThreadColor()</code> fails to return a value when no switch cases match. Although we readers can tell that a case must always match, we should add a <code>return</code> statement after the <code>switch</code> to keep the compiler from reporting the error.</p>\n\n<h1>Enable and fix compilation warnings</h1>\n\n<p>You seem to be compiling with all warnings disabled. With <code>g++ -Wall -Wextra -Weffc++</code>, we get a few extra things to fix:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>In file included from /home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.cpp:1:\n/home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.h: In constructor ‘GameOfLife::GameOfLife(sf::Vector2i)’:\n/home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.h:46:23: warning: ‘GameOfLife::worldBuffer’ will be initialized after [-Wreorder]\n std::vector&lt;uint8_t&gt; worldBuffer;\n ^~~~~~~~~~~\n/home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.h:33:12: warning: ‘const int GameOfLife::maxThreads’ [-Wreorder]\n const int maxThreads;\n ^~~~~~~~~~\n/home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.cpp:11:1: warning: when initialized here [-Wreorder]\n GameOfLife::GameOfLife(sf::Vector2i size) : worldSize(size), world(size.x * size.y, false), worldBuffer(world), maxThreads(std::thread::hardware_concurrency())\n ^~~~~~~~~~\n/home/tms/stackexchange/review/213814/GameOfLife/src/GameOfLife.cpp:11:1: warning: ‘GameOfLife::aliveCells’ should be initialized in the member initialization list [-Weffc++]\n[ 60%] Building CXX object CMakeFiles/GameOfLife.dir/src/WorldRenderer.cpp.o\n/usr/bin/c++ -Wall -Wextra -Wwrite-strings -Wno-parentheses -Weffc++ -pthread -std=c++17 -o CMakeFiles/GameOfLife.dir/src/WorldRenderer.cpp.o -c /home/tms/stackexchange/review/213814/GameOfLife/src/WorldRenderer.cpp\n/home/tms/stackexchange/review/213814/GameOfLife/src/WorldRenderer.cpp: In constructor ‘WorldRenderer::WorldRenderer()’:\n/home/tms/stackexchange/review/213814/GameOfLife/src/WorldRenderer.cpp:3:1: warning: ‘WorldRenderer::m_vertexPoints’ should be initialized in the member initialization list [-Weffc++]\n WorldRenderer::WorldRenderer()\n ^~~~~~~~~~~~~\n/home/tms/stackexchange/review/213814/GameOfLife/src/WorldRenderer.cpp: In member function ‘void WorldRenderer::renderBackgrounds(sf::RenderWindow&amp;, GameOfLife&amp;)’:\n/home/tms/stackexchange/review/213814/GameOfLife/src/WorldRenderer.cpp:79:58: warning: unused parameter ‘window’ [-Wunused-parameter]\n void WorldRenderer::renderBackgrounds(sf::RenderWindow &amp; window, GameOfLife &amp; world)\n ~~~~~~~~~~~~~~~~~~~^~~~~~\n</code></pre>\n\n<p>These are all easily fixed. For example, we can avoid the warning about an uninitialized member by providing a default initializer (though I'd be happier if my compiler were smart enough to know which types get constructed in a genuinely uninitialized state, and warn only about those):</p>\n\n<pre><code>std::vector&lt;sf::Vertex&gt; m_vertexPoints = {};\n</code></pre>\n\n<p>We also want to turn on some compiler optimizations here; I'll use <code>-O3</code>. After all, there's little point conducting a <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged &#39;performance&#39;\" rel=\"tag\">performance</a> review on unoptimized code.</p>\n\n<h1>Don't declare empty constructors and destructors</h1>\n\n<blockquote>\n<pre><code>public:\n WorldRenderer();\n\n ~WorldRenderer();\n\nWorldRenderer::WorldRenderer()\n{\n}\n\n\nWorldRenderer::~WorldRenderer()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>Let the compiler generate the special methods, so we don't have to:</p>\n\n<pre><code>public:\n WorldRenderer() = default;\n</code></pre>\n\n<p>That's much simpler. And this class:</p>\n\n<blockquote>\n<pre><code>class Cell\n{\npublic:\n Cell(sf::Vector2i position, sf::Color color);\n ~Cell();\n sf::Vector2i position;\n sf::Color color;\n};\n\nCell::Cell(sf::Vector2i position, sf::Color color)\n : position(position), color(color)\n{\n}\n\nCell::~Cell()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>becomes simply</p>\n\n<pre><code>struct Cell\n{\n sf::Vector2i position;\n sf::Color color;\n};\n</code></pre>\n\n<p>if we change the constructor calls to plain aggregate initialization.</p>\n\n<h1>Reduce copying</h1>\n\n<p>Instead of taking a copy of <code>game.aliveCells</code>, it might be better to expose a read-only reference:</p>\n\n<pre><code>private:\n // Update the cells from position start(inclusive) to position end(exclusive).\n std::vector&lt;Cell&gt; doUpdate(int start, int end, int coreIdx);\n\n // A cache of all the alive cells at the end of the update() call.\n std::vector&lt;Cell&gt; aliveCells = {};\n\npublic:\n auto const&amp; getLivingCells() const { return aliveCells; }\n</code></pre>\n\n\n\n<pre><code> // populate m_cellVertexPoints\n for (auto const&amp; cell: game.getLivingCells()) {\n addQuad(cell.position.x, cell.position.y, cell.color);\n }\n</code></pre>\n\n<p>The <code>const&amp;</code> qualifier on the return type lets client code view the contents of our vector without being able to modify it and without needing to make a copy.</p>\n\n<p>And <code>addQuad</code> can accept a <code>const Cell&amp;</code> instead of unpacking it here:</p>\n\n<pre><code>void WorldRenderer::addQuad(const Cell&amp; cell)\n{\n float gridXFloat = cell.position.x * 1.0f;\n float gridYFloat = cell.position.y * 1.0f;\n\n m_vertexPoints.emplace_back(sf::Vector2f{gridXFloat, gridYFloat }, cell.color); // top-left\n m_vertexPoints.emplace_back(sf::Vector2f{gridXFloat, gridYFloat + 1}, cell.color); // bottom-left\n m_vertexPoints.emplace_back(sf::Vector2f{gridXFloat + 1, gridYFloat + 1}, cell.color); // bottom-right\n m_vertexPoints.emplace_back(sf::Vector2f{gridXFloat + 1, gridYFloat }, cell.color); // top-right\n}\n</code></pre>\n\n<p>Here, I've used <code>emplace_back</code> to reduce the likelihood of copying (that said, <code>push_back()</code> is overloaded to move-from an rvalue argument, so there's likely no real difference in the optimized binary). That takes us neatly to the next member, which can similarly be reduced:</p>\n\n<pre><code>void WorldRenderer::addBackgroundQuad(sf::Vector2f topLeft, sf::Vector2f bottomRight, sf::Color color)\n{\n auto topRight = topLeft;\n auto bottomLeft = bottomRight;\n std::swap(topRight.x, bottomLeft.x);\n\n m_vertexPoints.emplace_back(topLeft, color);\n m_vertexPoints.emplace_back(bottomLeft, color);\n m_vertexPoints.emplace_back(bottomRight, color);\n m_vertexPoints.emplace_back(topRight, color);\n}\n</code></pre>\n\n<h1>Prefer declarative threading to hand-built parallelism</h1>\n\n<p>I can see that great care has been put into dividing the work into threads and collating the results, so it's hard to recommend throwing that away. But I'm going to (don't worry; having written it gives you a better understanding of what will happen behind the scenes). If we enable OpenMP (i.e. add <code>-fopenmp</code> to our GCC arguments, or equivalent on other compilers; use <code>find_package(OpenMP)</code> in CMake), then we don't need to explicitly code the mechanism of parallelisation, and instead we can focus on the content.</p>\n\n<p>Here's the new <code>update()</code> (which also replaces <code>doUpdate()</code>) using OpenMP:</p>\n\n<pre><code>#include &lt;omp.h&gt;\n\nvoid GameOfLife::update()\n{\n // clear aliveCells cache\n aliveCells.clear();\n\n#pragma omp parallel\n {\n // private, per-thread variables\n auto this_thread_color = getThreadColor(omp_get_thread_num());\n std::vector&lt;Cell&gt; next_generation;\n\n#pragma omp for\n for (int i = 0; i &lt; worldSize.x * worldSize.y; ++i) {\n auto pos = get2D(i);\n\n int aliveCount = 0;\n\n // check all 8 neighbors\n for (int nX = -1; nX &lt;= 1; ++nX) {\n for (int nY = -1; nY &lt;= 1; ++nY) {\n // skip the current cell\n if (nX == 0 &amp;&amp; nY == 0) continue;\n\n // wrap around to other side if neighbor would be outside world\n int newX = (nX + pos.x + worldSize.x) % worldSize.x;\n int newY = (nY + pos.y + worldSize.y) % worldSize.y;\n\n aliveCount += getCell(newX, newY);\n }\n }\n\n // Evaluate game rules on current cell\n bool dies = aliveCount == 2 || aliveCount == 3;\n bool lives = aliveCount == 3;\n worldBuffer[i] = world[i] ? dies : lives;\n\n // if the cell's alive push it into the vector\n if (worldBuffer[i])\n next_generation.emplace_back(Cell{pos, this_thread_color});\n }\n\n#pragma omp critical\n aliveCells.insert(aliveCells.end(), next_generation.begin(), next_generation.end());\n }\n\n // apply updates\n world.swap(worldBuffer);\n}\n</code></pre>\n\n<p>We can now play with things such as dynamic or guided scheduling without perturbing the logic. And we can control the maximum number of threads without recompiling (using <code>OMP_NUM_THREADS</code> environment variable).</p>\n\n<p>The <code>pragma omp critical</code> is required when combining results in order to ensure that the threads don't try to modify the shared <code>aliveCells</code> simultaneously. The other shared variables are read but not modified within the parallel section.</p>\n\n<h1>Fix an arithmetic bug</h1>\n\n<p>This conversion doesn't work after the display window has been resized by the user:</p>\n\n<blockquote>\n<pre><code> // normalize mouse pos\n int x = (mousePosition.x / 512.0f) * WORLD_SIZE_X;\n int y = (mousePosition.y / 512.0f) * WORLD_SIZE_Y;\n</code></pre>\n</blockquote>\n\n<h1>Minor/style issues</h1>\n\n<p>There's no need to explicitly return 0 from <code>main()</code> if we always succeed - a common convention is to do so only when there's another code path that returns non-zero.</p>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<h2>Main.cpp</h2>\n\n<pre><code>#include \"GameOfLife.h\"\n#include \"WorldRenderer.h\"\n\n#include &lt;SFML/Graphics.hpp&gt;\n\nstatic const sf::Vector2i World_Size = { 256, 256 };\n\nint main()\n{\n // create the window\n sf::RenderWindow window({256, 256}, \"Game of Life\");\n // scale the image up 2x size\n window.setSize({512, 512});\n\n // disable vsync and uncap framerate limit\n window.setVerticalSyncEnabled(false);\n window.setFramerateLimit(0);\n\n // Create the game\n GameOfLife game(World_Size);\n\n // Create a world renderer\n WorldRenderer worldRenderer;\n\n // Track if mouse button is being held down\n bool mouseHeld = false;\n\n // run the program as long as the window is open\n while (window.isOpen()) {\n // check all the window's events that were triggered since the last iteration of the loop\n sf::Event event;\n while (window.pollEvent(event)) {\n // \"close requested\" event: we close the window\n if (event.type == sf::Event::Closed)\n window.close();\n\n // capture if the user is holding left mouse button down\n if (event.type == sf::Event::MouseButtonPressed) {\n if (event.mouseButton.button == sf::Mouse::Left)\n mouseHeld = true;\n } else if (event.type == sf::Event::MouseButtonReleased) {\n if (event.mouseButton.button == sf::Mouse::Left)\n mouseHeld = false;\n }\n }\n\n // clear the window with black color\n window.clear(sf::Color::Black);\n\n // if left mouse button held down then make cells under cursor alive and pause simulation\n if (mouseHeld) {\n auto mousePosition = sf::Mouse::getPosition(window);\n\n // normalize mouse pos\n int x = mousePosition.x * World_Size.x / window.getSize().x;\n int y = mousePosition.y * World_Size.y / window.getSize().y;\n\n // set cell under cursor to alive\n game.setCell(x, y, true);\n } else {\n // update the game world\n game.update();\n }\n\n // render the game\n worldRenderer.render(window, game);\n\n // end the current frame\n window.display();\n }\n}\n</code></pre>\n\n<h2>GameOfLife.h</h2>\n\n<pre><code>#pragma once\n\n#include \"Cell.h\"\n\n#include &lt;SFML/System/Vector2.hpp&gt;\n\n#include &lt;cstdint&gt;\n#include &lt;vector&gt;\n\nclass GameOfLife\n{\npublic:\n GameOfLife(sf::Vector2i size);\n\n // Set the value of the cell at the given grid position to the given alive state.\n void setCell(int x, int y, bool alive);\n\n // Updates the state of the game world by one tick.\n void update();\n\n // Returns a reference to the cell value at the given grid position.\n std::uint8_t &amp; getCell(int x, int y);\n\n // Returns a vector of the given cell's grid position by its cell index.\n sf::Vector2i get2D(int index) const;\n\n auto const&amp; getLivingCells() const { return aliveCells; }\n\n // Returns a color to use for cells/backgrounds based on the thread ID #.\n static sf::Color getThreadColor(int index);\n\n // Represents the width and height of the simulated world.\n const sf::Vector2i worldSize;\n\nprivate:\n\n // A cache of all the alive cells at the end of the update() call.\n std::vector&lt;Cell&gt; aliveCells = {};\n\n // A 1D representation of the 2D grid that is the world.\n std::vector&lt;std::uint8_t&gt; world;\n\n // A buffer where the next world state is prepared, swapped with world at end of update().\n std::vector&lt;std::uint8_t&gt; worldBuffer;\n};\n</code></pre>\n\n<h2>GameOfLife.cpp</h2>\n\n<pre><code>#include \"GameOfLife.h\"\n\n#include &lt;omp.h&gt;\n\n#include &lt;array&gt;\n\nGameOfLife::GameOfLife(sf::Vector2i size)\n : worldSize(size),\n world(size.x * size.y, false),\n worldBuffer(world)\n{\n aliveCells.reserve(size.x * size.y); // reserve space for worst-case(all cells are alive)\n\n // place an \"acorn\"\n int midX = worldSize.x / 2;\n int midY = worldSize.y / 2;\n getCell(midX + 0, midY + 0) = 1;\n getCell(midX + 1, midY + 0) = 1;\n getCell(midX + 4, midY + 0) = 1;\n getCell(midX + 5, midY + 0) = 1;\n getCell(midX + 6, midY + 0) = 1;\n getCell(midX + 3, midY + 1) = 1;\n getCell(midX + 1, midY + 2) = 1;\n}\n\nstd::uint8_t&amp; GameOfLife::getCell(int x, int y)\n{\n\n return world[y * worldSize.x + x];\n}\n\nsf::Vector2i GameOfLife::get2D(int index) const\n{\n int y = index / worldSize.x;\n int x = index % worldSize.x;\n return { x, y };\n}\n\nsf::Color GameOfLife::getThreadColor(int index)\n{\n switch (index % 4) {\n case 0:\n return sf::Color::Red;\n case 1:\n return sf::Color::Green;\n case 2:\n return sf::Color::Blue;\n case 3:\n return sf::Color::Yellow;\n }\n\n return sf::Color::White;\n}\n\nvoid GameOfLife::update()\n{\n // clear aliveCells cache\n aliveCells.clear();\n\n#pragma omp parallel\n {\n // private, per-thread variables\n auto this_thread_color = getThreadColor(omp_get_thread_num());\n std::vector&lt;Cell&gt; next_generation;\n\n#pragma omp for\n for (int i = 0; i &lt; worldSize.x * worldSize.y; ++i) {\n auto const pos = get2D(i);\n int aliveCount = 0;\n\n // check all 8 neighbors\n static const std::array&lt;std::array&lt;int, 2&gt;, 8&gt; neighbours{{{-1, -1}, {0, -1}, {1, -1},\n {-1, 0}, {1, 0},\n {-1, 1}, {0, 1}, {1, 1}}};\n for (auto const [nX, nY]: neighbours) {\n // wrap around to other side if neighbor would be outside world\n int newX = (nX + pos.x + worldSize.x) % worldSize.x;\n int newY = (nY + pos.y + worldSize.y) % worldSize.y;\n\n aliveCount += getCell(newX, newY);\n }\n\n // Evaluate game rules on current cell\n bool dies = aliveCount == 2 || aliveCount == 3;\n bool lives = aliveCount == 3;\n worldBuffer[i] = world[i] ? dies : lives;\n\n // if the cell's alive push it into the vector\n if (worldBuffer[i])\n next_generation.emplace_back(Cell{pos, this_thread_color});\n }\n\n#pragma omp critical\n aliveCells.insert(aliveCells.end(), next_generation.begin(), next_generation.end());\n }\n\n // apply updates\n world.swap(worldBuffer);\n}\n\nvoid GameOfLife::setCell(int x, int y, bool alive)\n{\n // constrain x and y\n x = std::max(std::min(x, (int) worldSize.x - 1), 0);\n y = std::max(std::min(y, (int) worldSize.y - 1), 0);\n getCell(x, y) = alive;\n aliveCells.push_back(Cell{sf::Vector2i(x, y), sf::Color::White});\n}\n</code></pre>\n\n<h2>WorldRenderer.h</h2>\n\n<pre><code>#pragma once\n\n#include &lt;SFML/Graphics.hpp&gt;\n#include &lt;vector&gt;\n#include \"GameOfLife.h\"\n\nclass WorldRenderer\n{\npublic:\n WorldRenderer() = default;\n\n // Renders the given game to the given window.\n void render(sf::RenderWindow&amp; window, GameOfLife&amp; world);\n\nprivate:\n // Vertex points for the pending draw call.\n std::vector&lt;sf::Vertex&gt; m_vertexPoints = {};\n\n // Adds a cell-sized quad in the \"grid position\" specified.\n void addQuad(const Cell&amp; cell);\n\n // Adds a darker colored quad in the given coordinates.\n void addQuad(sf::Vector2f topLeft, sf::Vector2f bottomRight, sf::Color color);\n\n // Renders the background colors which correspond to the thread ID and the cells they are updating.\n void renderBackgrounds(GameOfLife&amp; world);\n\n // Returns a darker variant of the given color.\n sf::Color darkenColor(sf::Color input);\n};\n</code></pre>\n\n<h2>WorldRenderer.cpp</h2>\n\n<pre><code>#include \"WorldRenderer.h\"\n\n#include &lt;omp.h&gt;\n\nvoid WorldRenderer::addQuad(const Cell&amp; cell)\n{\n\n sf::Vector2f topLeft{cell.position.x * 1.0f, cell.position.y * 1.0f};\n sf::Vector2f bottomRight{topLeft.x + 1, topLeft.y + 1};\n addQuad(topLeft, bottomRight, cell.color);\n}\n\nvoid WorldRenderer::addQuad(sf::Vector2f topLeft, sf::Vector2f bottomRight, sf::Color color)\n{\n auto topRight = topLeft;\n auto bottomLeft = bottomRight;\n std::swap(topRight.x, bottomLeft.x);\n\n m_vertexPoints.emplace_back(topLeft, color);\n m_vertexPoints.emplace_back(bottomLeft, color);\n m_vertexPoints.emplace_back(bottomRight, color);\n m_vertexPoints.emplace_back(topRight, color);\n}\n\nvoid WorldRenderer::render(sf::RenderWindow &amp; window, GameOfLife &amp; game)\n{\n // clear m_cellVertexPoints\n m_vertexPoints.clear();\n\n // draw backgrounds for \"core zones\"\n renderBackgrounds(game);\n\n // populate m_cellVertexPoints\n for (auto const&amp; cell: game.getLivingCells()) {\n addQuad(cell);\n }\n\n // draw quads to window\n window.draw(m_vertexPoints.data(), m_vertexPoints.size(), sf::Quads);\n}\n\nvoid WorldRenderer::renderBackgrounds(GameOfLife &amp; world)\n{\n auto const maxThreads = omp_get_max_threads();\n auto const threadHeight = world.worldSize.y / maxThreads;\n\n for (int i = 0; i &lt; maxThreads; ++i) {\n sf::Vector2f topLeft{0, 1.f * i * threadHeight};\n sf::Vector2f bottomRight{1.f * world.worldSize.x + 1, topLeft.y + 1.f * world.worldSize.y / maxThreads + 1};\n addQuad(topLeft, bottomRight, darkenColor(world.getThreadColor(i)));\n }\n}\n\nsf::Color WorldRenderer::darkenColor(sf::Color input)\n{\n return sf::Color(input.r / 4, input.g / 4, input.b / 4);\n}\n</code></pre>\n\n<h2>Cell.h</h2>\n\n<pre><code>#pragma once\n\n#include &lt;SFML/Graphics/Color.hpp&gt;\n#include &lt;SFML/System/Vector2.hpp&gt;\n\nstruct Cell\n{\n sf::Vector2i position;\n sf::Color color;\n};\n</code></pre>\n\n<h2>CMakeLists.txt</h2>\n\n<pre><code># CMakeList.txt : CMake project for GameOfLife\n#\ncmake_minimum_required (VERSION 3.8)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -O3 -Werror -Wall -Wextra -Wshadow -Wwrite-strings -Wno-parentheses -Weffc++\")\n\nset(CMAKE_CXX_STANDARD 17)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Give the project a name\nproject(GameOfLife)\n\nfind_package(OpenMP)\nfind_package(SFML 2.5 COMPONENTS graphics REQUIRED)\n\nset(SOURCES \n src/Main.cpp\n src/GameOfLife.cpp\n src/GameOfLife.h\n src/WorldRenderer.cpp\n src/WorldRenderer.h\n src/Cell.h\n)\n\nadd_executable(GameOfLife ${SOURCES})\n\ntarget_link_libraries(GameOfLife sfml-graphics OpenMP::OpenMP_CXX)\n</code></pre>\n\n<p>Some minor changes I introduced while refactoring:</p>\n\n<ul>\n<li>I changed the loop with the <code>neighbours</code> array to avoid the branch for the {0,0} case and to make it a single loop rather than nested loops. I think this is clearer, and it <em>might</em> be a tiny bit faster (but I didn't profile that).</li>\n<li>I tend to prefer snake_case for identifiers, and that has crept into the code where I should have been consistent with the original camelCase - sorry about that! The same goes for spacing around operators and the <code>&amp;</code> that indicates a reference variable. Being consistent is more important than any particular style, and I broke that rule because I was rushing.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:22:45.603", "Id": "413719", "Score": "0", "body": "When I try to build the CMake-generated Visual Studio project I'm getting this error: `D8021 - invalid numeric argument '/Werror'`\nAnd I had a couple questions but I don't know where to put them. The comment section doesn't allow enough characters..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:31:41.817", "Id": "413721", "Score": "0", "body": "I decided to put my questions [here](https://github.com/k-vekos/GameOfLife/blob/code-review-update/CODE_REVIEW_QUESTIONS.md)!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T17:56:08.507", "Id": "413731", "Score": "1", "body": "There's probably a better CMake way to do that (I'm ignorant with CMake - I just added the minimum I could glean from SO and that works with GCC). Failing that, just put the required arguments for your compiler into the `CMAKE_CXX_FLAGS` line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:23:09.407", "Id": "413739", "Score": "1", "body": "I believe my latest edit answers the other questions - if not, then let me know (reply may be tomorrow, as I'm reaching end of day here)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:30:03.600", "Id": "413741", "Score": "1", "body": "I found a useful blog entry about enabling warnings with CMake: https://foonathan.net/blog/2018/10/17/cmake-warnings.html#enabling-warnings-by-modifying-target-properties Perhaps that helps (particularly the section referring to *generator expressions*)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:26:12.087", "Id": "413871", "Score": "0", "body": "Thank you, your edits answered my questions perfectly. I am having a problem with my modified code though, where all cells are appearing red in color. I tried to put a breakpoint on [GameOfLife.cpp ln 63](https://github.com/k-vekos/GameOfLife/blob/code-review-update/src/GameOfLife.cpp#L63) but when I observe `omp_get_thread_num()` in my watch list it resolves to `omp_get_thread_num() identifier \"omp_get_thread_num\" is undefined` and I believe this may be the root cause. Do you know why this might be happening? I don't know OpenMP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:34:58.580", "Id": "413874", "Score": "1", "body": "Perhaps it's a library linking problem - I'm able to use the functions from `<omp.h>` just by adding `-fopenmp` to my compile line, but maybe your platform needs linker options, too? Just a guess, and I'm heading AFK for a few days now, so I hope you manage to track that down (or find an answer over on [so] - remember to make a [MCVE](//stackoverflow.com/help/mcve) for that rather than posting the whole program!)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:14:59.210", "Id": "213862", "ParentId": "213814", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T15:19:55.963", "Id": "213814", "Score": "7", "Tags": [ "c++", "performance", "multithreading", "game-of-life" ], "Title": "Multi-threaded Conway's Game of Life in C++" }
213814
<p>This is a rework of a small program for faster(?) switching working directories, and it looks like a pile of crap, I must admit. Could you give me pointers how to make it maintainable?</p> <p><strong>dt_tag_entry.hpp</strong></p> <pre><code>#ifndef NET_CODERODDE_DT2_TAG_ENTRY_HPP #define NET_CODERODDE_DT2_TAG_ENTRY_HPP #include &lt;string&gt; namespace net { namespace coderodde { namespace dt { class TagEntry { public: TagEntry(std::string const&amp; tag, std::string const&amp; directory); TagEntry(); TagEntry(TagEntry const&amp; other); TagEntry&amp; operator=(TagEntry&amp;&amp; other); TagEntry&amp; operator=(TagEntry const&amp; other); std::string const&amp; getTag() const; std::string const&amp; getDirectory() const; void setTag(std::string&amp; tag); void setDirectory(std::string&amp; directory); private: std::string m_tag; std::string m_directory; }; } // End of namespace 'net::coderodde::dt2'. } // End of namespace 'net::coderodde'. } // End of namespace 'net'. #endif // NET_CODERODDE_DT2_TAG_ENTRY_HPP </code></pre> <p><strong>dt_tag_entry.cpp</strong></p> <pre><code>#include "dt_tag_entry.hpp" #include &lt;string&gt; #include &lt;utility&gt; namespace net { namespace coderodde { namespace dt { TagEntry::TagEntry(std::string const&amp; tag, std::string const&amp; directory) : m_tag(tag), m_directory(directory) { } TagEntry::TagEntry() : m_tag(""), m_directory("") { } TagEntry::TagEntry(TagEntry const&amp; other) : m_tag(other.m_tag), m_directory(other.m_directory) { } TagEntry&amp; TagEntry::operator=(TagEntry&amp;&amp; other) { m_tag = std::move(other.m_tag); m_directory = std::move(other.m_directory); return *this; } TagEntry&amp; TagEntry::operator=(TagEntry const&amp; other) { m_tag = other.m_tag; m_directory = other.m_directory; return *this; } std::string const&amp; TagEntry::getTag() const { return m_tag; } std::string const&amp; TagEntry::getDirectory() const { return m_directory; } void TagEntry::setTag(std::string&amp; tag) { m_tag = tag; } void TagEntry::setDirectory(std::string&amp; directory) { m_directory = directory; } } // End of namespace 'net::coderodde::dt2'. } // End of namespace 'net::coderodde'. } // End of namespace 'net'. </code></pre> <p><strong>dt_tag_entry_list.hpp</strong></p> <pre><code>#ifndef NET_CODERODDE_DT2_TAG_ENTRY_LIST_HPP #define NET_CODERODDE_DT2_TAG_ENTRY_LIST_HPP #include "dt_tag_entry.hpp" #include &lt;vector&gt; using net::coderodde::dt::TagEntry; namespace net { namespace coderodde { namespace dt { class TagEntryList { public: void operator&lt;&lt;(TagEntry const&amp; tagEntry); TagEntry operator[](std::string const&amp; tag) const; std::vector&lt;TagEntry&gt;::const_iterator begin() const; std::vector&lt;TagEntry&gt;::const_iterator end() const; void sortByTags(); void sortByDirectories(); bool empty() const; std::size_t size() const; private: std::vector&lt;TagEntry&gt; m_entries; }; } // End of namespace 'net::coderodde::dt2'. } // End of namespace 'net::coderodde'. } // End of namespace 'net'. #endif // NET_CODERODDE_DT2_TAG_ENTRY_LIST_HPP </code></pre> <p><strong>dt_tag_entry_list.cpp</strong></p> <pre><code>#include "dt_tag_entry.hpp" #include "dt_tag_entry_list.hpp" #include &lt;algorithm&gt; #include &lt;limits&gt; #include &lt;stdexcept&gt; using net::coderodde::dt::TagEntry; static size_t computeEditDistance(std::string const&amp; string1, std::string const&amp; string2, size_t index1, size_t index2) { if (index1 == 0) { return index2; } else if (index2 == 0) { return index1; } return std::min( std::min( computeEditDistance(string1, string2, index1 - 1, index2) + 1, computeEditDistance(string1, string2, index1, index2 - 1) + 1 ), computeEditDistance(string1, string2, index1 - 1, index2 - 1) + (string1[index1 - 1] != string2[index2 - 1] ? 1 : 0) ); } static size_t computeEditDistance(std::string const&amp; string1, std::string const&amp; string2) { return computeEditDistance(string1, string2, string1.length(), string2.length()); } namespace net { namespace coderodde { namespace dt { void TagEntryList::operator&lt;&lt;(TagEntry const&amp; tagEntry) { m_entries.push_back(tagEntry); } TagEntry TagEntryList::operator[](std::string const&amp; tag) const { if (m_entries.empty()) { throw std::runtime_error("No entries available."); } TagEntry bestTagEntry; size_t bestEditDistance = std::numeric_limits&lt;size_t&gt;::max(); for (TagEntry const&amp; tagEntry : m_entries) { size_t currentEditDistance = computeEditDistance(tag, tagEntry.getTag()); if (bestEditDistance &gt; currentEditDistance) { bestEditDistance = currentEditDistance; bestTagEntry = tagEntry; } } return bestTagEntry; } std::size_t TagEntryList::size() const { return m_entries.size(); } std::vector&lt;TagEntry&gt;::const_iterator TagEntryList::begin() const { return m_entries.cbegin(); } std::vector&lt;TagEntry&gt;::const_iterator TagEntryList::end() const { return m_entries.cend(); } void TagEntryList::sortByTags() { std::stable_sort(m_entries.begin(), m_entries.end(), [](TagEntry const&amp; tagEntry1, TagEntry const&amp; tagEntry2) { return tagEntry1.getTag() &lt; tagEntry2.getTag(); }); } void TagEntryList::sortByDirectories() { std::stable_sort(m_entries.begin(), m_entries.end(), [](TagEntry const&amp; tagEntry1, TagEntry const&amp; tagEntry2) { return tagEntry1.getDirectory() &lt; tagEntry2.getDirectory(); }); } bool TagEntryList::empty() const { return m_entries.empty(); } } // End of namespace 'net::coderodde::dt2'. } // End of namespace 'net::coderodde'. } // End of namespace 'net'. </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;linux/limits.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;pwd.h&gt; #include "dt_tag_entry.hpp" #include "dt_tag_entry_list.hpp" #include &lt;algorithm&gt; #include &lt;cctype&gt; #include &lt;cstdlib&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;locale&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;utility&gt; const std::string FLAG_LIST_TAGS_AND_DIRECTORIES = "-L"; const std::string FLAG_LIST_TAGS_NO_DIRECTORIES = "-l"; const std::string FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED = "-S"; const std::string FLAG_LIST_TAGS_NO_DIRECTORIES_SORTED = "-s"; const std::string FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED_BY_DIRS = "-d"; const std::string TAG_ENTRY_LIST_FILE_DIRECTORY = "/.dt"; const std::string TAG_ENTRY_LIST_FILE_NAME = "/tags"; const std::string TAG_LINE = "tag"; const std::string OPERATION_DESCRIPTOR_SWITCH_DIRECTORY = "switch_directory"; const std::string OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST = "show_tag_entry_list"; const std::string OPERATION_DESCRIPTOR_MESSAGE = "message"; const std::string LIST_LINE = "list"; const size_t LINE_BUFFER_CAPACITY = 1024; ////// https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring static inline void ltrim(std::string &amp;s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } static inline void rtrim(std::string &amp;s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } inline void trim(std::string &amp;s) { ltrim(s); rtrim(s); } using net::coderodde::dt::TagEntry; using net::coderodde::dt::TagEntryList; static void operator&gt;&gt;(std::ifstream&amp; inputFileStream, TagEntryList&amp; tagEntryList) { char lineBuffer[LINE_BUFFER_CAPACITY]; while (!inputFileStream.eof() &amp;&amp; !inputFileStream.bad() &amp;&amp; !inputFileStream.fail()) { inputFileStream.getline(lineBuffer, LINE_BUFFER_CAPACITY); std::stringstream ss; std::string tag; std::string directory; ss &lt;&lt; lineBuffer; ss &gt;&gt; tag; char directoryBuffer[PATH_MAX]; ss.getline(directoryBuffer, PATH_MAX); directory = directoryBuffer; trim(directory); if (!tag.empty() &amp;&amp; !directory.empty()) { TagEntry tagEntry(tag, directory); tagEntryList &lt;&lt; tagEntry; } } } static size_t getMaximumTagLength(TagEntryList const&amp; tagEntryList) { auto const&amp; maximumLengthTagIter = std::max_element(tagEntryList.begin(), tagEntryList.end(), [](TagEntry const&amp; tagEntry1, TagEntry const&amp; tagEntry2) { return tagEntry1.getTag().length() &lt; tagEntry2.getTag().length(); }); return maximumLengthTagIter-&gt;getTag().length(); } static void listTags(TagEntryList const&amp; tagEntryList) { std::cout &lt;&lt; OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST &lt;&lt; '\n'; for (TagEntry const&amp; tagEntry : tagEntryList) { std::cout &lt;&lt; tagEntry.getTag() &lt;&lt; "\n"; } } static void listTagsAndDirectories(TagEntryList const&amp; tagEntryList) { if (tagEntryList.empty()) { // getMaximumTagLength assumes that the tagEntryList // is not empty. (It would dereference end(). std::cout &lt;&lt; OPERATION_DESCRIPTOR_MESSAGE &lt;&lt; "\nTag list is empty.\n"; return; } size_t maximumTagLength = getMaximumTagLength(tagEntryList); std::cout &lt;&lt; OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST &lt;&lt; '\n'; for (TagEntry const&amp; tagEntry : tagEntryList) { std::cout &lt;&lt; std::setw(maximumTagLength) &lt;&lt; std::left &lt;&lt; tagEntry.getTag() &lt;&lt; " " &lt;&lt; tagEntry.getDirectory() &lt;&lt; "\n"; } } static std::string matchTag(TagEntryList const&amp; tagEntryList, std::string const&amp; tag) { try { TagEntry bestTagEntry = tagEntryList[tag]; return bestTagEntry.getDirectory(); } catch (std::runtime_error const&amp; err) { std::exit(1); } } static std::string getUserHomeDirectoryName() { struct passwd* pw = getpwuid(getuid()); std::string name{pw-&gt;pw_dir}; return name; } static void createTagFile(char* fileName) { int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); close(fd); } static TagEntryList loadTagFile(std::string const&amp; tagFileName) { std::ifstream ifs; ifs.open(tagFileName.c_str(), std::ifstream::in); TagEntryList tagEntryList; ifs &gt;&gt; tagEntryList; ifs.close(); return tagEntryList; } static void toggleDirectory(std::string const&amp; tagFileName) { TagEntryList tagEntryList = loadTagFile(tagFileName); std::string path; try { path = tagEntryList["prev"].getDirectory(); } catch (...) { std::cout &lt;&lt; OPERATION_DESCRIPTOR_MESSAGE &lt;&lt; "\nNo 'prev' tag in the tag file.\n"; return; } std::cout &lt;&lt; OPERATION_DESCRIPTOR_SWITCH_DIRECTORY &lt;&lt; '\n' &lt;&lt; path; } static std::string getTagFilePath() { std::string homeDirectoryName = getUserHomeDirectoryName(); std::string directoryTaggerDirectory = homeDirectoryName + TAG_ENTRY_LIST_FILE_DIRECTORY; std::string tagFilePath = directoryTaggerDirectory + TAG_ENTRY_LIST_FILE_NAME; return tagFilePath; } static std::string omitTilde(std::string&amp; dir, std::string const&amp; homeDirectoryPath) { if (dir[0] == '~') { return homeDirectoryPath + dir.substr(1); } else { return dir; } } int main(int argc, char* argv[]) { if (argc &gt; 3) { std::cout &lt;&lt; OPERATION_DESCRIPTOR_MESSAGE &lt;&lt; "\nInvalid number of arguments: " &lt;&lt; argc - 1 &lt;&lt; '\n'; return EXIT_FAILURE; } std::string tagFilePath = getTagFilePath(); createTagFile((char*) tagFilePath.c_str()); // Make sure the tag file exists. // TODO: I don't think I need this. if (argc == 1) { toggleDirectory(tagFilePath); return EXIT_SUCCESS; } TagEntryList tagEntryList = loadTagFile(tagFilePath); if (argc == 3) { std::string flag = argv[1]; std::string path = argv[2]; if (std::string{"--update-prev"}.compare(flag) != 0) { std::cout &lt;&lt; OPERATION_DESCRIPTOR_MESSAGE &lt;&lt; " \n--update_prev expected, but " &lt;&lt; flag &lt;&lt; " was received.\n"; return EXIT_FAILURE; } // Now rewrite the file. std::ofstream ofs; ofs.open(tagFilePath.c_str(), std::ofstream::trunc | std::ofstream::out); bool prevTagIsPresent = false; for (auto iter = tagEntryList.begin(); iter != tagEntryList.end(); iter++) { TagEntry currentTagEntry = *iter; std::string tag = currentTagEntry.getTag(); std::string dir = currentTagEntry.getDirectory(); trim(dir); // Reset the string to the entry: currentTagEntry.setTag(tag); currentTagEntry.setDirectory(dir); if (currentTagEntry.getTag().compare(std::string{"prev"}) == 0) { currentTagEntry.setDirectory(path); prevTagIsPresent = true; } ofs &lt;&lt; currentTagEntry.getTag() &lt;&lt; " " &lt;&lt; currentTagEntry.getDirectory() &lt;&lt; '\n'; } if (!prevTagIsPresent) { TagEntry tagEntry("prev", path); tagEntryList &lt;&lt; tagEntry; ofs &lt;&lt; tagEntry.getTag() &lt;&lt; ' ' &lt;&lt; tagEntry.getDirectory(); std::cout &lt;&lt; OPERATION_DESCRIPTOR_SWITCH_DIRECTORY &lt;&lt; path; } ofs.close(); return 0; } std::string flag{argv[1]}; if (flag == FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED || flag == FLAG_LIST_TAGS_NO_DIRECTORIES_SORTED) { tagEntryList.sortByTags(); } else if (flag == FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED_BY_DIRS) { tagEntryList.sortByDirectories(); } if (flag == FLAG_LIST_TAGS_AND_DIRECTORIES || flag == FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED || flag == FLAG_LIST_TAGS_AND_DIRECTORIES_SORTED_BY_DIRS) { listTagsAndDirectories(tagEntryList); } else if (flag == FLAG_LIST_TAGS_NO_DIRECTORIES || flag == FLAG_LIST_TAGS_NO_DIRECTORIES_SORTED) { listTags(tagEntryList); } else { std::string targetDirectory = tagEntryList[argv[1]].getDirectory(); targetDirectory = targetDirectory[0] == '~' ? getUserHomeDirectoryName() + targetDirectory.substr(1) : targetDirectory; std::cout &lt;&lt; OPERATION_DESCRIPTOR_SWITCH_DIRECTORY &lt;&lt; '\n' &lt;&lt; targetDirectory; } return 0; } </code></pre> <p>(The entire story is <a href="https://github.com/coderodde/linux.directory_tagger" rel="nofollow noreferrer">here.</a>)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:14:39.000", "Id": "413606", "Score": "0", "body": "I think you could use [Boost's trim methods](https://www.boost.org/doc/libs/1_69_0/doc/html/string_algo.html) instead of rolling your own, but that's minor. Even less importantly, I'd rename `begin` and `end` to `cbegin` and `cend` because they return const_iterators." } ]
[ { "body": "<p>It seems to me that a whole lot of this is duplicating things that are already in the standard library (and many other libraries).</p>\n\n<p>It also seems to me like it does a lot of work to handle things that are more easily dealt with via a simple text editor. Just for example, if you want to add command aliases for bash, you don't feed some special command to bash to have it modify your <code>~/.bashrc</code>. Instead, you use a text editor of your choice to edit <code>~/.bashrc</code>, and then (most likely) re-source it to get bash to use it. I'd tend to do pretty much the same here--have the utility stick to expanding tags to directory names, and let the user edit tags with their normal text editor.</p>\n\n<p>Handling things that way, the code can be reduced to something on this general order:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;iomanip&gt;\n#include &lt;fstream&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;iostream&gt;\n#include &lt;pwd.h&gt;\n\nstatic std::string get_home_dir() {\n struct passwd* pw = getpwuid(getuid());\n std::string name{pw-&gt;pw_dir}; \n return name;\n}\n\n// expand tilde, if needed. To be more thorough, consider using\n// wordexp(3) instead.\nstd::string expand(std::string in) { \n std::string home = get_home_dir();\n\n auto pos = in.find(\"~\");\n if (pos != std::string::npos) {\n in.replace(pos, 1, home);\n }\n return in;\n}\n\n// Read tags from file. A tag must not contain white-space, and a \"#\" at the\n// beginning of a line signifies a comment.\nstd::map&lt;std::string, std::string&gt; read_tags(std::string const &amp;filename) { \n std::ifstream in{expand(filename)};\n\n std::string tag;\n std::string path;\n std::map&lt;std::string, std::string&gt; ret;\n\n while (in &gt;&gt; tag) {\n // I'm not sure if you supported comments in the tags file, but it \n // seems like a useful thing, and it's easy, so why not?\n if (tag[0] == '#')\n continue;\n std::getline(in, path);\n ret[tag] = path;\n }\n return ret;\n}\n\nvoid write_tags(std::map&lt;std::string, std::string&gt; const &amp;tags, std::string const &amp;filename) { \n std::ofstream out{expand(filename)};\n for (auto const &amp;p : tags)\n out &lt;&lt; p.first &lt;&lt; \"\\t\" &lt;&lt; p.second &lt;&lt; \"\\n\";\n}\n\nvoid chdir(std::string const &amp;s) {\n // Here we write the shell script fragment to change directory\n // For now I'm going to cheat and just print the command on standard output\n std::cout &lt;&lt; \"cd \" &lt;&lt; expand(s) &lt;&lt; \"\\n\";\n}\n\nint main(int argc, char **argv) { \n std::string config_path = \"~/.path_tags\"; \n\n auto tags = read_tags(config_path);\n\n std::string prev;\n if (tags.find(\"prev\") != tags.end()) \n prev = tags[\"prev\"];\n\n tags[\"prev\"] = get_current_dir_name();\n\n write_tags(tags, config_path);\n\n if (argc == 1) {\n if (!prev.empty())\n chdir(prev);\n else\n std::cerr &lt;&lt; \"No previous directory to switch to.\";\n }\n else {\n auto pos = tags.find(argv[1]);\n if (pos != tags.end())\n chdir(pos-&gt;second);\n }\n}\n</code></pre>\n\n<h3>File Reading</h3>\n\n<p>This code:</p>\n\n<pre><code>while (!inputFileStream.eof() &amp;&amp; !inputFileStream.bad() &amp;&amp; !inputFileStream.fail()) {\n inputFileStream.getline(lineBuffer, LINE_BUFFER_CAPACITY);\n</code></pre>\n\n<p>...is pretty much broken. In fact, nearly any loop of the form <code>while (!foo.eof())</code> is broken. You want to test the result of attempting to read the line instead:</p>\n\n<pre><code>while (inputFileStream.getline(lineBuffer, LINE_BUFFER_CAPACITY)) {\n // process the data we just read \n}\n</code></pre>\n\n<p>It's also generally easier to read the data into an <code>std::string</code> instead:</p>\n\n<pre><code>std::string lineBuffer;\nwhile (std::getline(lineBuffer)) {\n // process the line\n}\n</code></pre>\n\n<h3>File I/O</h3>\n\n<p>Right now, you use not only iostreams, but (for no particularly obvious reason) in places use posix <code>creat</code>/<code>open</code> level functions as well. At least offhand, I don't see much reason for using both.</p>\n\n<h3>Tag File</h3>\n\n<p>Right now, you store the tags in a single global file that's shared across all users of the system. This doesn't seem like a great idea. I'd (strongly) prefer a per-user tag file (as in the code I've posted above).</p>\n\n<h3>default ctor</h3>\n\n<p>Right now, you've explicitly defined a default constructor for your <code>TagEntry</code> type:</p>\n\n<pre><code>TagEntry::TagEntry()\n :\n m_tag(\"\"),\n m_directory(\"\") {\n\n}\n</code></pre>\n\n<p>When (as in this case) the compiler can generate an adequate ctor, it's generally preferable to let it do so, with a declaration like this:</p>\n\n<pre><code>TagEntry() = default;\n</code></pre>\n\n<p>In fact, at least at first glance, it looks like all of <code>TagEntry</code>'s ctors are doing pretty much what the compiler-generated ones would do if you didn't define any, so it's probably better to just not declare or define any at all (but as in the code above, I'd tend to just use a <code>map</code> or <code>unordered_map</code>, and skip creating a <code>TagEntry</code> class at all). Right now, <code>TagEntry</code> is pretty much a Quasi-class, that would work about as well as a struct:</p>\n\n<pre><code>struct TagEntry { \n std::string tag;\n std::string directory;\n};\n</code></pre>\n\n<p>I'd say if you decide to keep it, at least keep it simple.</p>\n\n<p><strong>Reference</strong></p>\n\n<p><a href=\"https://www.idinews.com/quasiClass.pdf\" rel=\"nofollow noreferrer\">Pseudo-classes and Quasi-Classes</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T05:53:51.737", "Id": "213850", "ParentId": "213819", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:20:53.423", "Id": "213819", "Score": "1", "Tags": [ "c++", "console", "file-system", "linux" ], "Title": "Tagging the directories and switching between them by tags - follow-up (Part 1/2: File management)" }
213819
<p>I'm quite new to C++ and want to focus on writing performant multithreaded code because I will try to port our company internal GUI framework which is currently implemented in C#. So I'd love to get some recommendations about code style and Performance on a reader-writer spin lock that favors writers I wrote:</p> <pre><code>namespace UI { namespace Threading { /** * \brief ReaderWriterSpinLock which favors writers */ class ReaderWriterSpinLock { public: ReaderWriterSpinLock() = default; ~ReaderWriterSpinLock() = default; ReaderWriterSpinLock(ReaderWriterSpinLock&amp;) = delete; ReaderWriterSpinLock(ReaderWriterSpinLock&amp;&amp;) = delete; ReaderWriterSpinLock&amp; operator =(ReaderWriterSpinLock&amp;) = delete; ReaderWriterSpinLock&amp; operator =(ReaderWriterSpinLock&amp;&amp;) = delete; void AcquireReaderLock() { int computedValue, initialValue; do { int count{0}; while (m_waitingWriters != 0 || (initialValue = m_lockCount) &lt; 0) { if (++count % MAX_SPIN_COUNT == 0) std::this_thread::yield(); } computedValue = initialValue + 1; } while (!m_lockCount.compare_exchange_strong(initialValue, computedValue)); } void ReleaseReaderLock() { assert(m_lockCount &gt; 0); --m_lockCount; } void AcquireWriterLock() { int computedValue, initialValue; ++m_waitingWriters; do { int count{0}; while (m_lockCount != 0) { if (++count % MAX_SPIN_COUNT == 0) std::this_thread::yield(); } initialValue = 0; computedValue = -1; } while (!m_lockCount.compare_exchange_strong(initialValue, computedValue)); --m_waitingWriters; } void ReleaseWriterLock() { assert(m_lockCount == -1); ++m_lockCount; } private: static constexpr int MAX_SPIN_COUNT = 1000; std::atomic&lt;int&gt; m_lockCount{0}; std::atomic&lt;int&gt; m_waitingWriters{0}; }; } } </code></pre> <p><strong>Explanation</strong>: A negative <code>m_lockCount</code> denotes the active writers (because there can only be one writer at a time the minimum is -1) and a positive count denotes the active readers. When aquiring the reader lock it spins (and yields every <code>MAX_SPIN_COUNT</code> spins) until there are no waiting writers (because it should favor those) and there are no active writers (<code>m_lockCount &gt;= 0</code>), then it tries to update the lock count and repeats the process if it fails. When releasing the lock, the lock count can get decremented without further checks. The methods for the writer lock are quite similar with the difference of temporarily incrementing the <code>m_waitingWriters</code> instead of checking them in the acquire method.</p> <p>I know that you should normally rely on library functions but in my test it was ten times faster for acquiring the writer lock and twice as fast for readers+writers (with four readers trying to acquire the reader lock in a loop) than the <code>boost::shared_mutex</code> in combination with the <code>boost::shared_lock</code> and <code>boost::unique_lock</code>. So it would actually be worth it.</p> <p>Also in my application the thread count equals the processor count so the yield should rarely be necessary and the spin lock will only be used for methods which only need a few cycles.</p> <p>I also wanted to explicitly delete the move and copy constructors because it makes sense for such a class (even though they are deleted implicitly because of the atomic fields). Is this a good idea?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T17:25:05.783", "Id": "413587", "Score": "0", "body": "I can't see how this works. You are going to have to write a lot of documentation to convince me that that does anything. Which is probably why it is very fast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T17:47:04.360", "Id": "413591", "Score": "0", "body": "@MartinYork Fair point. I've added an explanation. Hope this makes it clear but lockfree code is rarely easy to understand." } ]
[ { "body": "<h2>On Threading</h2>\n<blockquote>\n<p>lockfree code is rarely easy to understand.</p>\n</blockquote>\n<p>I would beg to differ. It usually just hides the complex situations.</p>\n<h2>On Spin Locks.</h2>\n<p>Spin locks are generally not a good idea. You should be really sure that a thread caught in a spin lock will escape quickly (otherwise you are going to melt your processor).</p>\n<p>But you mitigate the problem by using <code>std::this_thread::yield()</code> so this is not such a huge problem. So it is not what I would call a classic spin lock. More a spin with yield.</p>\n<h2>Guaranteed escape</h2>\n<p>The only issue I see is that you don't guarantee escape of the lock for a particular thread.</p>\n<p>Some particular unlucky thread may be caught trying to obtain a lock while other threads zip passed and keep getting the lock forcing the unlucky thread to keep re-trying to get out of the acquire.</p>\n<p>So your spin lock has the potential for some resource starvation (or worst case making the code serial).</p>\n<p>This is usually achieved by maintaining an order.</p>\n<h2>Documentation</h2>\n<p>You need to put the explanation into the code (as comments). Putting it as an explanation for this site was nice and allowed me to understand the code. But without it the code is undecipherable.</p>\n<h2>RAII</h2>\n<p>You have designed your code that requires matched calls to method (this is bad practice). Also you have not show RAII lockers for this class so we must assume its use is not exception safe.</p>\n<p>All four of your methods:</p>\n<pre><code> void AcquireReaderLock()\n void ReleaseReaderLock()\n void AcquireWriterLock()\n void ReleaseWriterLock()\n</code></pre>\n<p>Should be private members. You should only allow access to these methods via an RAII lock guard. Look at <code>std::lock</code> for an example.</p>\n<h2>Best practice</h2>\n<p>Minor best practice violations:</p>\n<pre><code>// One declaration per line\nint computedValue, initialValue;\n\n// Why not initialize these on declaration.\ninitialValue = 0;\ncomputedValue = -1;\n// There is no need to ever set them again.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T20:16:54.467", "Id": "413597", "Score": "0", "body": "Is the guaranteed escape always important? Because it doesn't add to the total runtime of all threads but just devides the wait time equally at the cost of more instructions. In my case it doesn't really matter if one thread takes longer to acquire the lock. Thanks for all the advice though, it helps a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:41:44.887", "Id": "413610", "Score": "1", "body": "Is guaranteed escape always important: **No**. Can it be the source of surprising behavior: **Yes**. You have to way on a case by case basis. Without more information about your use case its impossible to say more. It could be just fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T19:32:33.753", "Id": "213834", "ParentId": "213823", "Score": "2" } } ]
{ "AcceptedAnswerId": "213834", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:51:53.660", "Id": "213823", "Score": "4", "Tags": [ "c++", "concurrency" ], "Title": "Reader Writer SpinLock" }
213823
<p><strong>Context:</strong><br> I'm making a Codepen-like app but I want it to support sophisticated JS libraries/frameworks like Vue or Angular 2+ for example. I want to have a live preview of my snippet which updates in a reasonable time. So I came up with an idea that when I create a new snippet I'll initialize a <em>blank</em> starter project on my backend server and run <code>npm start</code> to have <a href="https://vue-loader.vuejs.org/guide/hot-reload.html" rel="nofollow noreferrer">Hot reload</a> enabled. When I update the code of my snippet on the frontend side, I'm making a request to the backend server and update files in the starter project which is making the <em>Hot reload</em> refresh the live preview. This is what I got at the moment and it is working.</p> <p><strong>What I came up with:</strong><br> This is my function which first copies the starter project to the new location, searches for the free port and eventually spawns <code>npm start</code>:</p> <pre><code>function createStarter(request, snippetId, callback) { const fs = require('fs'); const path = require('path'); const portfinder = require('portfinder'); const { technology } = request.params; const snippetPath = path.join(__dirname, '../../static/snippets/vue', snippetId.toString()); spawnProcess('cp', ['-r', 'vue-starter/', snippetPath], { cwd: snippetPath.slice(0, snippetPath.lastIndexOf('/')) }) .then(async () =&gt; { const lastPort = process.env.STARTER_LAST_USED_PORT || 1e4; const port = await portfinder.getPortPromise({ port: +lastPort + 1 }).catch(console.error); process.env.STARTER_LAST_USED_PORT = port; const packageJson = require(`${snippetPath}/package.json`); packageJson.scripts.dev += ` --port ${port}`; fs.writeFileSync(`${snippetPath}/package.json`, JSON.stringify(packageJson), 'utf8'); console.log(`Starting project ${snippetId} at port ${port}`); spawnProcess('npm', ['start'], { cwd: snippetPath }); }) .catch(console.error); callback(); } </code></pre> <p>where <code>spawnProcess()</code> is just a simple helper which executes <code>spawn(...args)</code> and binds events to the streams.</p> <p><strong>Actual question:</strong><br> Is it a good idea to have multiple child processes spawned in parallel? I'm not worried about <code>cp -r</code> from the function above because it's short command and lasts for a few seconds. What I am worried about is <code>npm start</code> which potentially can last for even hours and I'm wondering if this is a good practice to spawn potentially, say, 50 or 100 child processes with <code>npm start</code> running for a long time before it'll be killed. I was thinking about setting a timeout for this command and kill it after about a minute but it can cause another issue which is re-spawning a child process multiple times which requires more resources.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T16:53:25.887", "Id": "213824", "Score": "1", "Tags": [ "javascript", "node.js", "child-process", "vue.js" ], "Title": "Spawning multiple child processes to preview Vue.js projects" }
213824
<p>I created a class which creates chained translations (for example, Japanese translated to English, then back to Japanese, then to English).</p> <p>Some concerns:</p> <ul> <li>Is my usage of recursion good?</li> <li>Is the class pythonic? Is there anything else to make it more pythonic?</li> <li>I used instantiated Translator twice in my code. Is there any way to only use it once?</li> </ul> <p>Code:</p> <pre><code>from googletrans import Translator word_list = [] class Translate: def __init__(self, word, target_language='en'): translator = Translator() self.target_language = target_language self.original_language = translator.detect(word).lang self.chained_translation = self.repeat_translation(word, target_language) def __getitem__(self, item): return self.chained_translation[item] def __len__(self): return len(self.chained_translation) def repeat_translation(self, word, target, count=0): translator = Translator() translated_text = translator.translate(word, dest=target).text word_list.append(translated_text) count += 1 # When recursive count is odd. if count % 2 == 1: return self.repeat_translation(translated_text, self.original_language, count) # When recursive count is even and under 10. if count &lt; 10: return self.repeat_translation(translated_text, self.target_language, count) # When recursive ends. else: return word_list </code></pre> <p>Example usage:</p> <pre><code>test = Translate('は忙しい。彼は多忙な人間だ。勉強をしたい') print(test.chained_translation) print(test[9]) print(test[8]) print(len(test)) ['I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい'] 私は忙しいです。彼は忙しい人だ。学びたい I am busy. He is a busy man. I want to learn 10 </code></pre>
[]
[ { "body": "<p>I think that you should be more explicit about the source language instead of relying exclusively on auto-detection, in both your <code>Translate</code> constructor and when you call <code>translator.translate()</code>. Japanese is easy enough to detect unambiguously in most cases. However, phrases in other languages could easily be interpreted as several possible languages.</p>\n\n<p>Recursion is rarely the most idiomatic solution in Python. Rather, <a href=\"https://docs.python.org/3/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">generators</a> are often a better idea. Here's a generator that will translate back and forth between two languages as many times as you want:</p>\n\n<pre><code>from googletrans import Translator\n\ndef chained_translations(phrase, target_language='en', source_language=None):\n translator = Translator()\n source_language = source_language or translator.detect(phrase).lang\n while True:\n phrase = translator.translate(phrase, src=source_language, dest=target_language).text\n yield phrase\n source_language, target_language = target_language, source_language\n</code></pre>\n\n<p>This solution is much simpler, because the state is kept in the execution flow of the generator code itself.</p>\n\n<p>Example usage:</p>\n\n<pre><code>&gt;&gt;&gt; test = chained_translations('は忙しい。彼は多忙な人間だ。勉強をしたい')\n&gt;&gt;&gt; print(next(test))\n'I am busy. He is a busy man. I want to learn'\n&gt;&gt;&gt; print(next(test))\n'私は忙しいです。彼は忙しい人だ。学びたい'\n&gt;&gt;&gt; from itertools import islice\n&gt;&gt;&gt; print(list(islice(test, 3)))\n['I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:11:51.927", "Id": "413717", "Score": "0", "body": "This is very pythonic. Thank you for pointing me to generators." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:58:54.327", "Id": "213839", "ParentId": "213831", "Score": "3" } } ]
{ "AcceptedAnswerId": "213839", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T18:56:49.890", "Id": "213831", "Score": "3", "Tags": [ "python", "recursion" ], "Title": "Python class which chains Google translations back and forth between two languages" }
213831
<p>The code's structure has been changed to make the program more readable. I've also commented and split up the program into blocks for better readability as well. The recursion in the player and computer moves have been replaced with a loop instead. The user can now determine the first player. The algorithm to determine game end by a win has also been made much more concise by re-using code and using loops. User input is also now validated, throwing up an error for invalid inputs.</p> <p>I still have not made a smarter computer, or used a minmax algorithm, and I am working on extending the program to allow user to make choices about players. However regarding the code at hand, are there any mistakes I am making in making certain choices, or any further optimisations I can make to improve structure, readability, efficiency, safety, etc? </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; //---------------------------------------------------------------------------------- // Structure Definition //---------------------------------------------------------------------------------- struct game_data { int win; // Either 0 or 1. int turns; // Ranges from 0 to 9(game end). int turn; // Either 0 or 1 where 0 is human player char grid[3][3]; // Grid }; //------------------------------------------------------------------------------------ // Function Declarations //------------------------------------------------------------------------------------ void Intro(void); // Game intro void GameSetup(struct game_data *game); // Determines first player void PlayerOneMove(struct game_data *game); // Player one input void RandomComputerMove(struct game_data *game); // Computer move void DrawUpdatedGrid(const struct game_data *game); // Draw updated grid void GameEventWon(struct game_data *game); // Checks for winners void GameEventDrawn(struct game_data *game); // Checks for draws char ThreeInARow(char grid[][3]); // Checks for three-in-a-row //------------------------------------------------------------------------------------ // Main Loop //------------------------------------------------------------------------------------ int main(void) { // Initialises Random Number Generator srand((unsigned)time(0)); // Initialising Game State Variables struct game_data game = { 0, 0, 0, {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}} }; Intro(); GameSetup(&amp;game); while (game.win == 0) { if (game.turn == 0) { PlayerOneMove(&amp;game); // RandomComputerMoveTwo(&amp;game); game.turns++; game.turn = 1; } else { RandomComputerMove(&amp;game); game.turns++; game.turn = 0; } DrawUpdatedGrid(&amp;game); GameEventWon(&amp;game); GameEventDrawn(&amp;game); } return 0; } //------------------------------------------------------------------------------------ // Short Intro and Setup //------------------------------------------------------------------------------------ void Intro(void) { printf("\nWelcome to NOUGHTS AND CROSSES\n\n"); printf("The grid you will be playing on is 3x3 and your input will be " "determined by the co ordinates you put in, in the form 'row " "column'.\n\n"); printf("For example an input of '1 1' will put a 'Z' on the first row " "on the " "first column. Like so:\n\n"); printf(" 1 2 3 \n" " +---+---+---+\n" "1 | Z | | |\n" " +---+---+---+\n" "2 | | | |\n" " +---+---+---|\n" "3 | | | |\n" " +---+---+---+\n" "\n"); } void GameSetup(struct game_data *game) { char answer; // Allow user to determine first player printf("Would you like to play first? y/n \n"); answer = getchar(); if (answer == 'y') { game-&gt;turn = 0; printf("\nYou have chosen to go first\n"); } else if (answer == 'n') { game-&gt;turn = 1; printf("\nYou have chosen to go second\n"); } else { puts("Invalid input"); exit(EXIT_FAILURE); } } //------------------------------------------------------------------------------------ // Player One Move //------------------------------------------------------------------------------------ void PlayerOneMove(struct game_data *game) { int row, column; do { printf("You are 'Crosses'. Please input co-ordinates ...\n"); if (scanf(" %d %d", &amp;row, &amp;column) != 2) { puts("Invalid input"); exit(EXIT_FAILURE); } if (row &lt; 1 || row &gt; 3 || column &lt; 1 || column &gt; 3) { puts("Out of range input"); exit(EXIT_FAILURE); } } while (game-&gt;grid[row - 1][column - 1] != ' '); game-&gt;grid[row - 1][column - 1] = 'X'; // Places player move printf("\nYour turn:\n\n"); } //------------------------------------------------------------------------------------ // Computer Move //------------------------------------------------------------------------------------ void RandomComputerMove(struct game_data *game) { int column; int row; do { row = rand() % 3; column = rand() % 3; } while (game-&gt;grid[row][column] != ' '); printf("\nComputer turn:\n\n"); game-&gt;grid[row][column] = 'O'; // Places computer move } //------------------------------------------------------------------------------------ // Display Updated Grid //------------------------------------------------------------------------------------ void DrawUpdatedGrid(const struct game_data *game) { printf( "+---+---+---+\n" "| %c | %c | %c |\n" "+---+---+---+\n" "| %c | %c | %c |\n" "----+---+---|\n" "| %c | %c | %c |\n" "+---+---+---+\n" "\n", game-&gt;grid[0][0], game-&gt;grid[0][1], game-&gt;grid[0][2], game-&gt;grid[1][0], game-&gt;grid[1][1], game-&gt;grid[1][2], game-&gt;grid[2][0], game-&gt;grid[2][1], game-&gt;grid[2][2]); } //------------------------------------------------------------------------------------ // Checks for Three In A Row //------------------------------------------------------------------------------------ char ThreeInARow(char grid[][3]) { for (int i = 0; i &lt; 3; i++) { // Rows if (grid[i][0] == grid[i][1] &amp;&amp; grid[i][1] == grid[i][2]) { return grid[i][0]; } // Columns else if (grid[0][i] == grid[1][i] &amp;&amp; grid[1][i] == grid[2][i]) { return grid[0][i]; } } // Diagonals if ((grid[0][0] == grid[1][1] &amp;&amp; grid[1][1] == grid[2][2]) || (grid[0][2] == grid[1][1] &amp;&amp; grid[1][1] == grid[2][0])) { return grid[1][1]; } return ' '; } //------------------------------------------------------------------------------------ // Check if Game Won //------------------------------------------------------------------------------------ void GameEventWon(struct game_data *game) { switch (ThreeInARow(game-&gt;grid)) { case 'X': game-&gt;win = 1; printf("CROSSES has WON\n"); break; case 'O': game-&gt;win = 1; printf("NOUGHTS has WON\n"); break; } } //------------------------------------------------------------------------------------ // Check if Game Drawn //------------------------------------------------------------------------------------ void GameEventDrawn(struct game_data *game) { if (game-&gt;turns == 9 &amp;&amp; game-&gt;win == 0) { game-&gt;win = 1; printf("GAME is a DRAW\n"); } } </code></pre>
[]
[ { "body": "<p>I really like your program because it is well structured and very readable.</p>\n\n<h1>Bug</h1>\n\n<p>There is a bug in <code>ThreeInARow()</code>. For</p>\n\n<pre><code>+---+---+---+\n| | | |\n+---+---+---+\n| X | X | X |\n----+---+---|\n| O | O | |\n+---+---+---+\n</code></pre>\n\n<p>it returns <code>' '</code> (space) and the game continues.</p>\n\n<h1>Declaration and Initialization</h1>\n\n<p>If you don't have to support ancient compilers I would recommend to declare variables where you initialize them, e.g. <code>/* ... */ char answer = getchar();</code> instead of <code>char answer; /* ... */ answer = getchar();</code>.</p>\n\n<h1>Naming</h1>\n\n<p><code>board_state.win</code> signals if the game has ended (also in case of a draw) and therefore should be renamed to something like <code>finished</code> or <code>ended</code>.</p>\n\n<p>Personally, I like to use a verb in my function names because I think it's clearer what the function does (get, set, write, initialize, etc.).</p>\n\n<h1>Comments</h1>\n\n<p>Some comments state the obvious:</p>\n\n<pre><code>// Initialises Random Number Generator\nsrand((unsigned)time(0));\n</code></pre>\n\n<p>or repeat what is already expressed by the variable or function name:</p>\n\n<pre><code>//------------------------------------------------------------------------------------\n// Player One Move\n//------------------------------------------------------------------------------------\nvoid PlayerOneMove(struct game_data *game) {\n</code></pre>\n\n<p>My advice: Prefer expressive code over comments, because over the lifetime of a program (with bugfixes, refactorings and new features) comments and code tend to get out of sync.</p>\n\n<h1>DRY</h1>\n\n<p>You could refactor</p>\n\n<pre><code>if (game.turn == 0) {\n PlayerOneMove(&amp;game);\n game.turns++;\n game.turn = 1;\n}\nelse {\n RandomComputerMove(&amp;game);\n game.turns++;\n game.turn = 0;\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (game.turn == 0)\n PlayerOneMove(&amp;game);\nelse\n RandomComputerMove(&amp;game);\ngame.turns++;\ngame.turn = !game.turn;\n</code></pre>\n\n<h1>Error handling</h1>\n\n<p>Currently you handle all errors locally by calling <code>exit(EXIT_FAILURE);</code>. That works well for this program and keeps the error handling code small.<br>\nFor larger programs you might prefer returning error codes and handling the errors in the main loop because it gets harder to reason about a program with many functions that might call <code>exit()</code>.</p>\n\n<h1>Usability</h1>\n\n<p>I like your example where <code>1 1</code> places a <code>Z</code> on the board. IMHO something like <code>1 2</code> would be a little bit more helpful because it shows that the order is <code>&lt;row&gt; &lt;column&gt;</code>.</p>\n\n<h1>Code Style</h1>\n\n<p>I don't see <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">PascalCase</a> (<code>GameEventDrawn()</code>) very often for function names in C. Usually snake_case or lowerCamelCase are used. </p>\n\n<p>Last not least I want to repeat myself:<br>\nI really like how readable your program is. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T21:58:48.773", "Id": "213838", "ParentId": "213832", "Score": "1" } } ]
{ "AcceptedAnswerId": "213838", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T19:03:27.593", "Id": "213832", "Score": "0", "Tags": [ "beginner", "c", "game", "console", "tic-tac-toe" ], "Title": "Noughts and Crosses Version 3" }
213832
<p>This is a project I came up just as an exercise with to familiarize myself with Python syntax and data types. I am just learning how to code and would like to avoid establishing bad habits. On the other hand, I wanted this program to function so when I found something that worked, I left it as is, even if I suspected that there might be a better way. Any suggestions on how to improve the code would be greatly appreciated.</p> <pre><code>import feedparser import nltk import random # idea is to scrape headlines from RSS feed and make new headlines # using words from original headlines and mimicking the syntax of original headlines #scrape titles into scrptitles list scrptitles=[] data = feedparser.parse('http://rss.cnn.com/rss/cnn_topstories.rss') for entry in data.entries: data = entry.title scrptitles.append(data) #tokenize and tag toks = [(nltk.pos_tag(nltk.word_tokenize(title))) for title in scrptitles] # create list of dictionaries from list of tuples # [{'Word':'TAG',...headline structure...},] d_list = [dict(toks[1]) for toks[1] in toks] # remove unwanted characters from d_list ['``',"''",'&gt;','.',',',''] nonetype_list = ['``',"''","'",'&gt;',',','.','|','(',')','- ','_','=','+','&lt;','@','#','$',"%",'^','*','[',']','{','}',":",";"] for dicts in d_list: for item in nonetype_list: if item in dicts: del dicts[item] # create list of tags perserving headline structure tags_list = [dict.values() for dict in d_list] # get a clean version of the tags list tags_list = [[element for element in dict_values] for dict_values in tags_list] # reverse dictionaries inside of list of dictionaries # inv_map = {TAG: [list of words]} inv_map = {} for dct in d_list: for k, v in dct.items(): inv_map[v] = inv_map.get(v,[]) inv_map[v].append(k) # grab a headline_pattern, choose random words from dictionary values, # print out new headline headline_pat = (random.choice(tags_list)) new_headline = [random.choice(inv_map[item]) for item in headline_pat] for item in new_headline: print(item.upper(), end=' ') ### ----&gt; 2 WAYS TO REFINANCE CREDIT IN WHITESPLAINING </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T23:20:59.530", "Id": "413614", "Score": "1", "body": "This looks like a bug. Is it? `for entry in data.entries: ;\n data = entry.title ;\nscrptitles.append(data)` (the `scrptitles` is not indented in your code)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T23:48:34.790", "Id": "413620", "Score": "0", "body": "Correct, that should be indented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:14:09.833", "Id": "413657", "Score": "1", "body": "I don't think `[dict(toks[1]) for toks[1] in toks]` does what you think it does. You first two entries of the resulting list are actually the same. If you want to make every entry into a dictionary, use `[dict(t) for t in toks]` or `list(map(dict, toks))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T17:10:01.930", "Id": "413726", "Score": "1", "body": "Yes, I had not noticed that. The expression as is duplicates the first entry and eliminates the second. Your suggestions work much better. Thank you." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T19:22:21.107", "Id": "213833", "Score": "2", "Tags": [ "python", "beginner", "natural-language-processing", "rss" ], "Title": "Fetching and modifying CNN headlines" }
213833
<p>As the title says, I'm trying to implement a <a href="https://en.wikipedia.org/wiki/Merge_sort" rel="nofollow noreferrer">merge sort</a> algorithm in C++ that's also <a href="https://en.wikipedia.org/wiki/Adaptive_sort" rel="nofollow noreferrer">adaptive</a>. This is a personal exercise, and I don't have any specific application in mind. My main goal is to write something that's succinct and easy to understand but also has reasonably good performance.</p> <p>I'm aware that implementations already exist: TimSort (<a href="https://github.com/gfx/cpp-TimSort" rel="nofollow noreferrer">C++ implementation</a>), for example. And new enough versions of GCC's C++ library seem to implement <a href="https://en.cppreference.com/w/cpp/algorithm/stable_sort" rel="nofollow noreferrer">std::stable_sort</a> using an adaptive algorithm as well. I'm not looking to replace either of these, or beat them in performance (though I would be happy if I came close).</p> <p>So here is what I have. I'd be particularly interested to know of any bugs/special cases I've missed, or opportunities to improve the performance without increasing the complexity/code size too much. I've also tried to make good use of C++11 features (other than, of course, std::stable_sort itself), and if there are improvements that could be made on that front, I'd like to know as well.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;vector&gt; /* * This algorithm borrows some ideas from TimSort but is not quite as * sophisticated. Runs are detected, but only in the forward direction, and the * invariant is stricter: each stored run must be no more than half the length * of the previous. * * As in TimSort, an already-sorted array will be processed in linear time, * making this an "adaptive" algorithm. */ template&lt;typename Iter, typename Less&gt; class MergeSort { private: typedef typename std::iterator_traits&lt;Iter&gt;::value_type Value; typedef typename std::vector&lt;Value&gt;::size_type Size; /* Inserts a single element into a sorted list */ static void insert_head (Iter head, Iter tail, Less less) { Iter dest; for (dest = head + 1; dest + 1 &lt; tail; dest ++) { if (! less (* (dest + 1), * head)) break; } Value tmp = std::move (* head); std::move (head + 1, dest + 1, head); * dest = std::move (tmp); } /* Merges two sorted sub-lists */ static void do_merge (Iter head, Iter mid, Iter tail, Less less, std::vector&lt;Value&gt; &amp; buf) { /* copy list "a" to temporary storage */ if (buf.size () &lt; (Size) (mid - head)) buf = std::vector&lt;Value&gt; (std::make_move_iterator (head), std::make_move_iterator (mid)); else std::move (head, mid, buf.begin ()); auto a = buf.begin (); auto a_end = a + (mid - head); Iter b = mid; Iter dest = head; while (1) { if (! less (* b, * a)) { * (dest ++) = std::move (* a); if ((++ a) == a_end) break; } else { * (dest ++) = std::move (* b); if ((++ b) == tail) break; } } /* copy remainder of list "a" */ std::move (a, a_end, dest); } public: /* Top-level merge sort algorithm */ static void sort (Iter start, Iter end, Less less) { /* A list with 0 or 1 element is sorted by definition. */ if (end - start &lt; 2) return; std::vector&lt;Value&gt; buf; /* The algorithm runs right-to-left (so that insertions are left-to-right). */ Iter head = end; /* Markers recording the divisions between sorted sub-lists or "runs". * Each run is at least 2x the length of its left-hand neighbor, so in * theory a list of 2^64 - 1 elements will have no more than 64 runs. */ Iter div[64]; int n_div = 0; do { Iter mid = head; head --; /* Scan right-to-left to find a run of increasing values. * If necessary, use insertion sort to create a run at 4 values long. * At this scale, insertion sort is faster due to lower overhead. */ while (head &gt; start) { if (less (* head, * (head - 1))) { if (mid - head &lt; 4) insert_head (head - 1, mid, less); else break; } head --; } /* Merge/collapse sub-lists left-to-right to maintain the invariant. */ while (n_div &gt;= 1) { Iter tail = div[n_div - 1]; while (n_div &gt;= 2) { Iter tail2 = div[n_div - 2]; /* * Check for the occasional case where the new sub-list is * longer than both the two previous. In this case, a "3-way" * merge is performed as follows: * * |---------- #6 ----------|- #5 -|---- #4 ----| ... * * First, the two previous sub-lists (#5 and #4) are merged. * (This is more balanced and therefore more efficient than * merging the long #6 with the short #5.) * * |---------- #5 ----------|-------- #4 -------| ... * * The invariant guarantees that the newly merged sub-list (#4) * will be shorter than its right-hand neighbor (#3). * * At this point we loop, and one of two things can happen: * * 1) If sub-list #5 is no longer than #3, we drop out of the * loop. #5 is still longer than half of #4, so a 2-way * merge will be required to restore the invariant. * * 2) If #5 is longer than even #3 (rare), we perform another * 3-way merge, starting with #4 and #3. The same result * holds true: the newly merged #3 will again be shorter * than its right-hand neighbour (#2). In this fashion the * process can be continued down the line with no more than * two sub-lists violating the invariant at any given time. * Eventually no more 3-way merges can be performed, and the * invariant is restored by a final 2-way merge. */ if ((mid - head) &lt;= (tail2 - tail)) break; do_merge (mid, tail, tail2, less, buf); tail = tail2; n_div --; } /* * Otherwise, check whether the new sub-list is longer than half its * right-hand neighbour. If so, merge the two sub-lists. The * merged sub-list may in turn be longer than its own right-hand * neighbor, and if so the entire process is repeated. * * Once the "head" pointer reaches the beginning of the original * list, we simply keep merging until only one sub-list remains. */ if (head &gt; start &amp;&amp; (mid - head) &lt;= (tail - mid) / 2) break; do_merge (head, mid, tail, less, buf); mid = tail; n_div --; } /* push the new sub-list onto the stack */ div[n_div] = mid; n_div ++; } while (head &gt; start); } }; template&lt;typename Iter, typename Less&gt; void mergesort (Iter start, Iter end, Less less) { MergeSort&lt;Iter, Less&gt;::sort (start, end, less); } template&lt;typename Iter&gt; void mergesort (Iter const start, Iter const end) { typedef typename std::iterator_traits&lt;Iter&gt;::value_type Value; mergesort (start, end, std::less&lt;Value&gt; ()); } </code></pre> <p>GitHub repository: <a href="https://github.com/jlindgren90/mergesort" rel="nofollow noreferrer">https://github.com/jlindgren90/mergesort</a></p>
[]
[ { "body": "<h2>Design</h2>\n<p>A class with all static members! Seems like the wrong use case. We have <code>namespace</code> for that type of thing.</p>\n<h2>Code Review</h2>\n<p>I like the comment at the top:</p>\n<pre><code>/*\n * This algorithm borrows some ideas from TimSort but is not quite as\n * sophisticated. Runs are detected, but only in the forward direction, and the\n * invariant is stricter: each stored run must be no more than half the length\n * of the previous.\n *\n * As in TimSort, an already-sorted array will be processed in linear time,\n * making this an &quot;adaptive&quot; algorithm.\n */\n</code></pre>\n<p>Though I am unfamiliar with TimSort it easy to google. So a very nice comment all in all.</p>\n<p>I hate this comment though:</p>\n<pre><code> /* Inserts a single element into a sorted list */\n static void insert_head (Iter head, Iter tail, Less less)\n</code></pre>\n<p>Especially when it does not seem to match the function. What element is being inserted here? After reading the code it seems like the element at the head of the range is sorted into place as the elements [<code>head + 1</code> to <code>tail</code>) are already sorted.</p>\n<p>Better name better comment on what it does. Preferably just a better function name.</p>\n<p>Not all iterators support <code>+</code> operation or the <code>&lt;</code> operation. This is why we have <code>std::next</code> or <code>operator++</code> and iterators are usually tested with <code>!=</code> or <code>==</code>. Also, it looks like you are just doing a <code>std::find_if()</code>, so use the algorithm.</p>\n<pre><code> for (dest = head + 1; dest + 1 &lt; tail; dest ++)\n {\n if (! less (* (dest + 1), * head))\n break;\n }\n\n // I would rewrite as:\n I loop = head;\n ++loop;\n auto find = std::find_if(loop, tail, [&amp;less](I lhs, I rhs){return !less(*lhs, *rhs);});\n</code></pre>\n<p>This bit of code:</p>\n<pre><code> Value tmp = std::move (* head);\n std::move (head + 1, dest + 1, head);\n * dest = std::move (tmp);\n</code></pre>\n<p>is implemented by <code>std::rotate()</code>.</p>\n<p>Again I hate the comment. Not because it or the function are badly named. But because the comment does not give me any extra information. If it is not giving me information, it is actually worse than nothing as it will suffer from comment rot over time. The name of the function and its parameters should be your documentation.</p>\n<pre><code> /* Merges two sorted sub-lists */\n static void do_merge (Iter head, Iter mid, Iter tail, Less less, std::vector&lt;Value&gt; &amp; buf)\n</code></pre>\n<p>Using the operator <code>-</code> on iterators is not always supported. You should use <code>std::distance()</code>. Also using a C-cast is not tolerated in any civilized world. Take your heathen ways and reform, sinner! C++ has its own set of cast operators that do this much better. In this case <code>static_cast&lt;&gt;()</code>. But if you use <code>std::distance()</code> you don't need it.</p>\n<p>Very clever. So clever I had to go through it a couple of times to convince myself it worked. This is where you may want to comment on being clever.</p>\n<pre><code> /* copy list &quot;a&quot; to temporary storage */\n if (buf.size () &lt; (Size) (mid - head))\n buf = std::vector&lt;Value&gt; (std::make_move_iterator (head), std::make_move_iterator (mid));\n else\n std::move (head, mid, buf.begin ());\n</code></pre>\n<p>But a vector contains two sizes: <code>size()</code> and <code>capacity()</code>. There is no need to allocate a new vector just because the size has been exceeded: you can go until you reach capacity. But even then, why are you doing it manually? The vector is designed to do this stuff all internally in the most efficient way. You should just copy using move iterators and a back inserter. Let the vector sort out its own resizing (this will be usually be more efficient).</p>\n<pre><code> buf.clear();\n std::copy(std::make_move_iterator(head), std::make_move_iterator(mid),\n std::back_inserter(buf));\n</code></pre>\n<p>Using move iterators and correctly sizing the buffer will make the following code cleaner.</p>\n<pre><code> auto a = buf.begin ();\n auto a_end = a + (mid - head);\n Iter b = mid;\n Iter dest = head;\n</code></pre>\n<p>Sure but this can be made much more readable:</p>\n<pre><code> while (1)\n {\n if (! less (* b, * a))\n {\n * (dest ++) = std::move (* a);\n if ((++ a) == a_end)\n break;\n }\n else\n {\n * (dest ++) = std::move (* b);\n if ((++ b) == tail)\n break;\n }\n }\n\n // I would write it like this:\n while(a != a_end &amp;&amp; b != tail) {\n *dest++ = (! less (* b, * a))\n ? std::move(*a++);\n : std::move(*b++);\n }\n</code></pre>\n<p>OK. That's enough for one season. Seems like plenty that needs to be re-worked already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T03:45:39.673", "Id": "413791", "Score": "0", "body": "I like a lot of your suggestions! Especially using std::find_if and std::rotate. I come from a C background so I sometimes forget that algorithms like that are already provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T03:48:34.630", "Id": "413792", "Score": "0", "body": "A couple of the things you pointed out that could be simplified (like using std::back_inserter, or writing the merge loop more compactly) I did already try, but found that GCC didn't optimize those forms as well. I'll re-examine those, and if there's no way to simplify them without losing performance, I'll add comments explaining why they are the way they are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:22:26.827", "Id": "413852", "Score": "0", "body": "@JohnLindgren Don't get fooled by micro optimizations. The majority of the time spent on by code is on writing and maintaining. Saving a couple of micro seconds a year is not worth the maintenance cost in the next person having to understand the code. Optimizations should be done at the algorithm level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T17:35:10.133", "Id": "413879", "Score": "0", "body": "Agreed, generally speaking ... but seeing that I'm already writing my own sort algorithm rather than using std::stable_sort, you can assume that reducing maintenance time is not my primary goal in this exercise :) My rule of thumb here is, if increasing the code size by 5% results in a >5% performance gain, I'll do it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T23:46:24.580", "Id": "213845", "ParentId": "213840", "Score": "4" } } ]
{ "AcceptedAnswerId": "213845", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T22:22:58.040", "Id": "213840", "Score": "3", "Tags": [ "c++", "c++11", "sorting", "mergesort" ], "Title": "Adaptive Merge Sort in C++" }
213840
<p>Looking over <a href="https://codereview.stackexchange.com/questions/213777/rock-paper-scissors-c">Rock, Paper, Scissors. C++</a> from a beginning programmer prompted me to think about how I'd program this simple game in C++. The <code>RockPaperScissors</code> class contains the essential features of printing and evaluating each round of the game, as well as generation of randomly selected moves. I didn't encode a player input because that didn't seem too interesting; instead the sample program just plays 20 rounds against itself and prints the result of each. No statistics are gathered or stored.</p> <p>One feature that does exist is that there is a <code>#define</code> to select whether the classic game or the enhanced "Rock-Paper-Scissors-Lizard-Spock" version is used. (With a bit more work, which I chose not to invest, one could allow for a fairly generic <span class="math-container">\$n\$</span>-ary relation as the basis of the game.) The other feature worth noting is that the <code>operator&lt;</code> is deliberately <code>private</code> because the <span class="math-container">\$&lt;\$</span> operation implemented here does not represent a <a href="https://en.wikipedia.org/wiki/Partially_ordered_set" rel="noreferrer">partially ordered set</a> because the operation is not <em>transitive.</em> In simple terms, we would normally expect that <span class="math-container">\$(a &lt; b) \land (b &lt; c) \implies (a &lt; c)\$</span> but this is expressly <em>not</em> true here.</p> <p>I'd be interested in comments on those or any other design decisions or implementation details.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string_view&gt; #include &lt;array&gt; #include &lt;stdexcept&gt; #include &lt;random&gt; // define ENHANCED to non-zero for enhanced version with Spock, Lizard #ifndef ENHANCED #define ENHANCED 0 #endif class RockPaperScissors { public: RockPaperScissors(std::size_t num) { if (num &gt;= words.size()) { throw std::range_error("invalid choice"); } choice = num; } static RockPaperScissors random(); const std::string_view&amp; vs(const RockPaperScissors &amp;b) const; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const RockPaperScissors &amp;rps); private: bool operator==(const RockPaperScissors &amp;b) const; bool operator&lt;(const RockPaperScissors &amp;b) const; #if ENHANCED static constexpr std::array&lt;std::string_view, 5&gt; words{ "Rock", "Paper", "Scissors", "Spock", "Lizard", }; #else static constexpr std::array&lt;std::string_view, 3&gt; words{ "Rock", "Paper", "Scissors" }; #endif static constexpr std::array&lt;std::string_view, 3&gt; results{"LOSE", "TIE", "WIN" }; std::size_t choice; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const RockPaperScissors &amp;rps) { return out &lt;&lt; rps.words[rps.choice]; } RockPaperScissors RockPaperScissors::random() { static std::random_device rd; static std::mt19937 gen{rd()}; static std::uniform_int_distribution&lt;&gt; dis(0, RockPaperScissors::words.size()-1); std::size_t which{static_cast&lt;std::size_t&gt;(dis(gen))}; return RockPaperScissors{which}; } bool RockPaperScissors::operator==(const RockPaperScissors &amp;b) const { return choice == b.choice; } bool RockPaperScissors::operator&lt;(const RockPaperScissors &amp;b) const { return (choice + 1) % words.size() == b.choice || (choice + 3) % words.size() == b.choice; } const std::string_view&amp; RockPaperScissors::vs(const RockPaperScissors &amp;b) const { if (*this == b) { return results[1]; } else if (*this &lt; b) { return results[0]; } return results[2]; } int main() { for (int trials = 20; trials; --trials) { auto a = RockPaperScissors::random(); auto b = RockPaperScissors::random(); std::cout &lt;&lt; a &lt;&lt; " vs. " &lt;&lt; b &lt;&lt; ": " &lt;&lt; a &lt;&lt; " " &lt;&lt; a.vs(b) &lt;&lt; "S!\n"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T23:10:47.750", "Id": "413613", "Score": "0", "body": "https://the-big-bang-theory.com/rock-paper-scissors-lizard-spock/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T00:14:55.070", "Id": "413621", "Score": "0", "body": "`int trials`... `unsigned int trials` maybe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:30:18.977", "Id": "416329", "Score": "0", "body": "Were you trying to golf your `for` loop a bit or why the somewhat unusal design?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:34:26.580", "Id": "416332", "Score": "1", "body": "I see nothing unusual about the `for` loop." } ]
[ { "body": "<p>After preparing <a href=\"https://codereview.stackexchange.com/questions/233644/rock-paper-scissors-in-c/233646#233646\">this recent answer</a> it occurred to me that I'd already written something like it. Here's my review of this code.</p>\n\n<h2>Make the class more useful</h2>\n\n<p>Right now the <em>only</em> thing we can do with the <code>RockPaperScissors</code> class is to get a new one via <code>random</code> or print the results of a contest. If we wanted to do something else, such as collect some statistics, there are pieces missing, such as the ability to get a printable version of the class. Here's one way to add that:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const RockPaperScissors &amp;rps);\n</code></pre>\n\n<p>Now we can gather some statistics like this:</p>\n\n<pre><code>int main()\n{\n std::unordered_map&lt;std::string_view, unsigned&gt; responses;\n std::unordered_map&lt;std::string_view, unsigned&gt; results;\n constexpr unsigned max_trials{300'000'000};\n for (unsigned trials = max_trials; trials; --trials) {\n auto a = RockPaperScissors::random();\n auto b = RockPaperScissors::random();\n ++responses[static_cast&lt;std::string_view&gt;(a)];\n ++responses[static_cast&lt;std::string_view&gt;(b)];\n ++results[a.vs(b)];\n }\n for (const auto&amp; resp: responses) {\n std::cout &lt;&lt; std::setw(16) &lt;&lt; resp.first &lt;&lt; '\\t' &lt;&lt; resp.second \n &lt;&lt; '\\t' &lt;&lt; static_cast&lt;double&gt;(resp.second)/max_trials/2\n &lt;&lt; '\\n';\n }\n for (const auto&amp; resp: results) {\n std::cout &lt;&lt; std::setw(16) &lt;&lt; resp.first &lt;&lt; '\\t' &lt;&lt; resp.second \n &lt;&lt; '\\t' &lt;&lt; static_cast&lt;double&gt;(resp.second)/max_trials\n &lt;&lt; '\\n';\n }\n}\n</code></pre>\n\n<p>This gives a report something like this:</p>\n\n<pre><code> Paper 200002179 0.333337\n Scissors 199987250 0.333312\n Rock 200010571 0.333351\n WIN 66662424 0.222208\n TIE 100003629 0.333345\n LOSE 133333947 0.444446\n</code></pre>\n\n<h2>Prefer open functions to class functions</h2>\n\n<p>The current code has this member function:</p>\n\n<pre><code>RockPaperScissors RockPaperScissors::random() {\n static std::random_device rd;\n static std::mt19937 gen{rd()};\n static std::uniform_int_distribution&lt;&gt; dis(0, RockPaperScissors::words.size()-1);\n std::size_t which{static_cast&lt;std::size_t&gt;(dis(gen))};\n return RockPaperScissors{which};\n}\n</code></pre>\n\n<p>However, selecting a single item at random from within a collection is a very common need. A more generally useful way to write this might be this:</p>\n\n<pre><code>template &lt;typename Iter&gt;\nIter random_one(Iter begin, const Iter&amp; end) {\n static std::random_device rd;\n static std::mt19937 gen{rd()};\n static std::uniform_int_distribution&lt;&gt; dis(0, std::distance(begin, end) - 1);\n std::advance(begin, dis(gen));\n return begin;\n}\n</code></pre>\n\n<p>Now we can get an iterator that points to a particular item in any collection. (To make this template more durable, we'd actually probably want to do some validation of both the <code>Iter</code> type and the values passed, but this conveys the idea.) We could use that with no further modifications as in this:</p>\n\n<pre><code>RockPaperScissors RockPaperScissors::random() {\n auto which = std::distance(words.begin(), random_one(words.begin(), words.end()));\n return RockPaperScissors{which};\n}\n</code></pre>\n\n<p>But that's a bit odd because we are converting an iterator to an ordinal. That leads to the next suggestion.</p>\n\n<h2>Store an iterator within the class</h2>\n\n<p>We can simplify some of the code for this implementation by changing the definition of <code>choice</code> within the class to be an iterator. </p>\n\n<pre><code>using iter = decltype(words.begin());\niter choice; \n</code></pre>\n\n<p>Now the constructor can use the templated function above very simply:</p>\n\n<pre><code>RockPaperScissors::RockPaperScissors() : choice{random_one(words.begin(), words.end())}\n{\n}\n</code></pre>\n\n<p>A few other changes are needed, but mostly they simplify the code. </p>\n\n<p>Also note that now the <code>random</code> function is no longer needed. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:32:31.350", "Id": "233943", "ParentId": "213842", "Score": "3" } } ]
{ "AcceptedAnswerId": "233943", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-19T22:40:27.433", "Id": "213842", "Score": "7", "Tags": [ "c++", "c++17", "rock-paper-scissors", "rags-to-riches" ], "Title": "Rock-Paper-Scissors engine" }
213842
<p>I'm new at PowerShell and I like it. </p> <p>I had the change to write a script that uninstall <strong>Erlang</strong> and <strong>RabbitMQ</strong> and I want the same script to then remove the <strong>Erlang folder</strong> and the <strong>RabbitMQ folder</strong>. </p> <p>But in order to do so I need the script to respect the tasks order. </p> <p>My way out was to use <code>Write-Verbose</code> (line 13) so the script needs to wait for the task to end in order to pass to the next task: </p> <pre><code># Let's set some verbosity $VerbosePreference = 'Continue' function Check_Program_Installed($programName){ $check = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | Get-ItemProperty | Where-Object {$_.DisplayName -like "*$programName*" } | Select-Object -Property DisplayName, UninstallString If ($check.DisplayName) { $result = $check.DisplayName Write-Output "I found: $result, let's uninstall it!" $uninst = $check.UninstallString Write-Verbose $uninst Start-Process -FilePath $uninst -ArgumentList "/qn" -Wait #-NoNewWindow Check_Program_Installed($programName) } Else{ Write-Output "$programName is not installed" } } # Erlang check and Uninstall Write-Output "Checking if Erlang exist" Check_Program_Installed("Erlang") # RabbitMQ check and Uninstall Write-Output "Checking if RabbitMQ exist" Check_Program_Installed("Rabbit") # These actions need to be executed ONLY after Erlang and RabbitMQ uninstall Write-Output "Then we do action 1" Start-Sleep -s 3 Write-Output "Then we do action 2" Start-Sleep -s 3 Write-Output "Then we do action 3" Start-Sleep -s 3 Write-Output "Then we do action 4" Start-Sleep -s 3 Write-Output "Then we do action 5" </code></pre> <p><a href="https://i.stack.imgur.com/NAGuk.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NAGuk.gif" alt="enter image description here"></a></p> <p>This is a very newbie approach but it's the only thing I came out with. </p> <p>Is there a more elegant way to handle the task and avoid PowerShell to pass to the next task if the previous one isn't completed? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T15:57:46.090", "Id": "415079", "Score": "0", "body": "Can you show us the content of the `UnInstall` strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T16:41:53.517", "Id": "415082", "Score": "0", "body": "If the uninstall string has the `\\i` switch, then I suggest replacing that by `\\x`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T08:12:59.160", "Id": "415869", "Score": "0", "body": "@Theo, the content is \"C:\\Program Files\\{your Erlang Version}\\Uninstall.exe\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T09:47:57.717", "Id": "415876", "Score": "0", "body": "I'm afraid the `/qn` switch is for `.msi` files. In this case it is a `.exe`. Apparently, the Erlang _Installer_ has a `/S` switch for silently install. Perhaps that also applies for the Uninstall.exe? There may be more switches possible. In a commandline you could try `\"C:\\Program Files\\{your Erlang Version}\\Uninstall.exe\" /?` to hopefully get help about accepted switches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:03:14.087", "Id": "416044", "Score": "0", "body": "Thank you @Theo but is not a silent installation what I need. I want the script *not to pass to the next step* while is uninstalling Erlang. For now I'm piping everything into a Write-Verbose but this is a mere workaround" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T02:15:56.570", "Id": "213847", "Score": "2", "Tags": [ "windows", "powershell", "installer", "erlang", "rabbitmq" ], "Title": "Uninstalling Erlang and RabbitMQ, using Write-Verbose to ensure sequencing" }
213847
<p>I'm learning C# and currently having an assignment on Tic Tac Toe. I'd love to have some feedback on where I can improve.</p> <p>I've managed to create the end game functions but I feel it could be improved. I'm just not sure how to do it and was hoping someone here could help me. </p> <p>I hope the information I've provided is enough, <code>this.cells</code> is a multidimensional array containing the <code>Cell</code> objects: </p> <pre><code>/// &lt;summary&gt; /// Contains info about what kind of cell we're dealing with /// &lt;/summary&gt; public enum Cell { Empty, Circle, Cross } </code></pre> <p><strong>Below is the part I'm searching feedback on. Too many if statements? What could I have done different or better?</strong> </p> <pre><code>/// &lt;summary&gt; /// Check all possible combinations for the target cell /// of winning the game (row, column, or slope). /// /// Returns true if there is a win condition, false if there isn't. /// &lt;/summary&gt; private bool IsGameOver(Cell cell) { // Row 1 if (this.cells[0, 0] == cell &amp;&amp; this.cells[0, 1] == cell &amp;&amp; this.cells[0, 2] == cell) { return true; } // Row 2 if (this.cells[1, 0] == cell &amp;&amp; this.cells[1, 1] == cell &amp;&amp; this.cells[1, 2] == cell) { return true; } // Row 3 if (this.cells[2, 0] == cell &amp;&amp; this.cells[2, 1] == cell &amp;&amp; this.cells[2, 2] == cell) { return true; } // Clm 1 if (this.cells[0, 0] == cell &amp;&amp; this.cells[1, 0] == cell &amp;&amp; this.cells[2, 0] == cell) { return true; } // Clm 2 if (this.cells[1, 0] == cell &amp;&amp; this.cells[1, 1] == cell &amp;&amp; this.cells[1, 2] == cell) { return true; } // Clm 3 if (this.cells[2, 0] == cell &amp;&amp; this.cells[2, 1] == cell &amp;&amp; this.cells[2, 2] == cell) { return true; } // Horizontal line 1 if (this.cells[0, 0] == cell &amp;&amp; this.cells[1, 1] == cell &amp;&amp; this.cells[2, 2] == cell) { return true; } // Horizontal line 2 if (this.cells[0, 2] == cell &amp;&amp; this.cells[1, 1] == cell &amp;&amp; this.cells[2, 0] == cell) { return true; } return false; } </code></pre>
[]
[ { "body": "<h1>Naming</h1>\n\n<p>The enum <code>Cell</code> defines <code>Empty</code>, <code>Circle</code> and <code>Cross</code>. This values aren't cells in terms of an object, they are more like types.</p>\n\n<p>For example: <em>Empty</em> is not a cell, but a cell can be <em>empty</em></p>\n\n<p>You can rename <code>Cell</code> to <code>CellType</code> to make it more clear.</p>\n\n<h1>Comments</h1>\n\n<p>Comments are a good documentation. You did a great job with the <code>&lt;summary&gt;</code>-tag. But the comments like <code>// Row 1</code>, <code>// Row 2</code>, <code>// Clm 3</code> are not so good..</p>\n\n<p>Robert C. Martin, who wrote the book \"Clean Code\" and many more, sad</p>\n\n<blockquote>\n <p><a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">Don’t Use a Comment When You Can Use a Function or a Variable</a></p>\n</blockquote>\n\n<h1>Introduce Methods</h1>\n\n<p>We can wrap the if-statements into methods</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsFirstRowComplete(CellType cellType) {\n if (this.cells[0, 0] == cellType &amp;&amp; this.cells[0, 1] == cellType &amp;&amp; this.cells[0, 2] == cellType) {\n return true;\n }\n return false;\n}\n\nbool IsSecondRowComplete(CellType cellType) {\n if (this.cells[1, 0] == cellType &amp;&amp; this.cells[1, 1] == cellType &amp;&amp; this.cells[1, 2] == cellType) {\n return true;\n }\n return false;\n}\n\n// ...\n</code></pre>\n\n<h2>Make them less complex</h2>\n\n<p>Since these methods return a Boolean we can return the boolean-expression itself</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsFirstRowComplete(CellType cellType) {\n return this.cells[0, 0] == cellType\n &amp;&amp; this.cells[0, 1] == cellType\n &amp;&amp; this.cells[0, 2] == cellType\n}\n\nbool IsSecondRowComplete(CellType cellType) {\n return this.cells[1, 0] == cellType\n &amp;&amp; this.cells[1, 1] == cellType\n &amp;&amp; this.cells[1, 2] == cellType\n}\n\n// ...\n</code></pre>\n\n<h2>Remove Duplication</h2>\n\n<p>The new methods <code>IsFirstRowComplete</code> and <code>IsSecondRowComplete</code> looks very similar. We can extract the main logic and wrap it into its own method.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsRowComplete(CellType cellType, int row) {\n return this.cells[row, 0] == cellType\n &amp;&amp; this.cells[row, 1] == cellType\n &amp;&amp; this.cells[row, 2] == cellType\n}\n\n// ...\n</code></pre>\n\n<p>If you like you can now wrap this method into <code>IsFirstRowComplete</code> and so on</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsFirstRowComplete(CellType cellType, int row) {\n return IsRowComplete(cellType, 0);\n}\n\n// ...\n</code></pre>\n\n<h2>Introduce more Methods</h2>\n\n<p>We could finish here.. But we can make the code more clear if we wrap each check into a method</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsARowComplete(CellType cellType) {\n return IsFirstRowComplete(cellType, 0)\n || IsSecondRowComplete(cellType, 1)\n || IsThirdRowComplete(cellType, 2);\n}\n\nbool IsAColumnsComplete(CellType cellType) {\n return IsFirstColumnComplete(cellType, 0)\n || IsSecondColumnComplete(cellType, 1)\n || IsThirdColumnComplete(cellType, 2);\n}\n\n// ...\n</code></pre>\n\n<h1>After the Refactoring</h1>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool IsGameOver(CellType cellType) {\n return IsARowComplete(cellType)\n || IsAColumnComplete(cellType)\n || IsAHorizontalComplete(cellType)\n}\n</code></pre>\n\n<h1>Maybe a Bug</h1>\n\n<p>If the method <code>isGameOver</code> gets called with a <code>CellType</code> of type <code>Empty</code> it could return <code>true</code></p>\n\n<p>So maybe you need to check if the <code>cellType</code> is not <code>Empty</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:51:52.753", "Id": "413674", "Score": "0", "body": "Roman thank you so much for your time! I learned so much! <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T01:22:13.947", "Id": "413785", "Score": "0", "body": "Well done! I'd have gone with `CellState` though =)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T07:52:28.680", "Id": "213856", "ParentId": "213852", "Score": "4" } } ]
{ "AcceptedAnswerId": "213856", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T06:28:33.597", "Id": "213852", "Score": "2", "Tags": [ "c#", "tic-tac-toe" ], "Title": "TicTacToe endgame feedback in C#" }
213852
<p>This is the <code>bash</code> script responsible for changing the directories via textual tags. (<a href="https://github.com/coderodde/linux.directory_tagger" rel="nofollow noreferrer">See here the entire project.</a>)</p> <p><strong>dt_script</strong></p> <pre><code>~/.dt/dt $@ &gt; ~/.dt/dt_tmp COMMAND_TYPE=$(head -n 1 ~/.dt/dt_tmp) if [ $# -eq 0 ]; then NEXT_PATH=$(~/.dt/dt prev | tail -n 1) # Let dt return pwd if no prev tag. ~/.dt/dt --update-prev $(pwd) if [ "$COMMAND_TYPE" == "message" ]; then tail -n 1 ~/.dt/dt_tmp else cd $NEXT_PATH fi else if [ "$COMMAND_TYPE" == "switch_directory" ]; then NEXT_PATH=$(tail -n 1 ~/.dt/dt_tmp) ~/.dt/dt --update-prev $(pwd) cd $NEXT_PATH elif [ "$COMMAND_TYPE" == "show_tag_entry_list" ]; then tail -n +2 ~/.dt/dt_tmp elif [ "$COMMAND_TYPE" == "message" ]; then tail -n 1 ~/.dt/dt_tmp #echo $(cut -d " " -f 2) else echo "Unknown command: $COMMAND_TYPE" fi fi rm ~/.dt/dt_tmp </code></pre> <p>Any further suggestions for improvement are welcomed.</p>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">Use More Quotes™</a>\n\n<ul>\n<li><code>$@</code> should be double quoted to pass the parameters without word splitting.</li>\n<li><em>Any</em> variable use should be quoted. It is very rare that word splitting is actually what you want, and it causes sometimes very subtle bugs.</li>\n<li><a href=\"https://mywiki.wooledge.org/CommandSubstitution\" rel=\"nofollow noreferrer\">Command substitution</a> should be quoted.</li>\n</ul></li>\n<li>Use <a href=\"https://stackoverflow.com/q/3427872/96588\">good bashisms</a> such as <code>[[</code> instead of <code>[</code>.</li>\n<li>Local variables should be lowercase to distinguish them from system variables, which are uppercase.</li>\n<li><p>There is no need for semicolons in Bash scripts. This may be more contentious, but I generally write like this:</p>\n\n<pre><code>if [[ \"$variable\" = 'value' ]]\nthen\n …\n</code></pre>\n\n<p>Apropos: <code>==</code> to compare strings is a bit of a historical accident. The original operator is just <code>=</code>, but <code>==</code> is probably not going away.</p></li>\n<li><code>$(pwd)</code> can be simplified to <code>.</code> - it also means the current directory.</li>\n<li>The home directory should not be used for temporary file storage (unless that is actually your configured temporary directory). In general you should use something like <code>working_dir=\"$(mktemp --directory)\"</code> (or <code>-d</code> if you don't have GNU coreutils <code>mktemp</code>). This has a few advantages:\n\n<ul>\n<li>It means your home directory isn't going to fill up with temporary files which are never cleaned up (but more about that below).</li>\n<li>It is often a memory mapped filesystem, so it may be much faster than your home directory.</li>\n</ul></li>\n<li>Long <code>if</code>/<code>elif</code> sections testing the value of a single variable can usually be easier written as a <code>case</code> block.</li>\n<li><p><code>head</code> does <em>not</em> fail if run on an empty file:</p>\n\n<pre><code>$ touch foo\n$ head foo\n$ echo $?\n0\n</code></pre>\n\n<p>So your first test could fail for the wrong reason. You might want to <code>[[ -s \"$path\" ]]</code> to check if a file is empty.</p></li>\n<li>The file name \"dt_tmp\" doesn't tell me anything about what it contains or what it's used for - in general I find that adding the project name to <em>anything</em> within the project is redundant, and marking something as temporary is not particularly helpful to know what it <em>is,</em> unless it really can contain anything. Is there a better name you can give it? It looks like it's some sort of command queue, maybe?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T07:49:02.607", "Id": "213855", "ParentId": "213853", "Score": "3" } } ]
{ "AcceptedAnswerId": "213855", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T06:59:08.027", "Id": "213853", "Score": "3", "Tags": [ "bash", "console", "file-system" ], "Title": "Tagging the directories and switching between them by tags - follow-up (Part 2/2: business logic)" }
213853
<p>In the below GameOutcome class I'm checking for wins/ties in Tic Tac Toe. I'm pretty set on breaking the checks into 5 different functions because I'm specifically practicing making functions short and single-purposed. But I'm not at all set on my 5 if statements in the find_winner_or_tie method. Does somebody know a more elegant solution for the find_winner_or_tie method so it doesn't have 5 if statements in it? I sort of which I could just call each of the "check functions" in a loop but I don't know how to do this without hardcoding the names of all 5 of the "check functions".</p> <pre><code>class GameOutcome: def __init__(self): self.letter_dict = {'X': -1, 'O': 1, ' ': 0} self.state_of_game = None self.row_index_of_move = None self.column_index_of_move = None self.game_outcome = None def find_winner_or_tie(self, state_of_game, row_index_of_move, column_index_of_move): self.set_board_and_move(state_of_game, row_index_of_move, column_index_of_move) if self.check_row_containing_move_for_win(): return self.game_outcome if self.check_column_containing_move_for_win(): return self.game_outcome if self.check_main_diagonal_for_win_iff_it_contains_move(): return self.game_outcome if self.check_off_diagonal_for_win_iff_it_contains_move(): return self.game_outcome if self.check_for_tie(): return self.game_outcome return '' def set_board_and_move(self, state_of_game, row_index_of_move, column_index_of_move): self.state_of_game = state_of_game self.row_index_of_move = row_index_of_move self.column_index_of_move = column_index_of_move def check_row_containing_move_for_win(self): total = 0 for column in range(3): total = total + int(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]]) if abs(total) == 3: winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move] self.game_outcome = winning_letter return True return False def check_column_containing_move_for_win(self): total = 0 for row in range(3): total = total + int(self.letter_dict[self.state_of_game.board[row][self.column_index_of_move]]) if abs(total) == 3: winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move] self.game_outcome = winning_letter return True return False def check_main_diagonal_for_win_iff_it_contains_move(self): if self.row_index_of_move == self.column_index_of_move: total = 0 for diagonal_indexing in range(3): total = total + int(self.letter_dict[self.state_of_game.board[diagonal_indexing][diagonal_indexing]]) if abs(total) == 3: winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move] self.game_outcome = winning_letter return True return False def check_off_diagonal_for_win_iff_it_contains_move(self): if self.row_index_of_move + self.column_index_of_move == 2: total = 0 for off_diagonal_indexing in range(3): total = total + int(self.letter_dict[self.state_of_game.board[off_diagonal_indexing][2 - off_diagonal_indexing]]) if abs(total) == 3: winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move] self.game_outcome = winning_letter return True return False def check_for_tie(self): if len(self.state_of_game.available_squares) == 0: self.game_outcome = 'Tie' return True return False </code></pre>
[]
[ { "body": "<pre><code>def check_row_containing_move_for_win(self):\n total = 0\n for column in range(3):\n total = total + int(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]])\n if abs(total) == 3:\n winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]\n self.game_outcome = winning_letter\n return True\n return False\n</code></pre>\n\n<p>There are a few things wrong with the above code, and a few things which can be greatly improved.</p>\n\n<ul>\n<li><code>self.letter_dict[ ]</code> is a dictionary containing the values <code>1</code>, <code>-1</code>, and <code>0</code>. Since these are already integer values, you don’t need the <code>int( ... )</code> call to convert the values to integers.</li>\n<li><code>total = total + ...</code> is almost always written <code>total += ...</code></li>\n<li>Since <code>total</code> is initialized to <code>0</code>, and can only be incremented or decremented by <code>1</code> each time through the loop, you can only get to <code>+3</code> or <code>-3</code> after all 3 passes through the loop. Having the <code>if abs(total) == 3:</code> test inside the loop is inefficient; it should be moved outside of, just after the loop.</li>\n<li>Since you are summing up values in a loop, you can use the Python <code>sum( )</code> function, with list comprehension instead of a loop.</li>\n</ul>\n\n<p>With the above changes, this function could become:</p>\n\n<pre><code>def check_row_containing_move_for_win(self):\n total = 0\n for column in range(3):\n total += self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]]\n if abs(total) == 3:\n winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]\n self.game_outcome = winning_letter\n return True\n return False\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>def check_row_containing_move_for_win(self):\n total = sum(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]]\n for column in range(3))\n if abs(total) == 3:\n winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]\n self.game_outcome = winning_letter\n return True\n return False\n</code></pre>\n\n<p>Similar comments for your column and diagonal win tests.</p>\n\n<hr>\n\n<p>Your 5 <code>if</code> statements ...</p>\n\n<pre><code> if self.check_row_containing_move_for_win():\n return self.game_outcome\n if self.check_column_containing_move_for_win():\n return self.game_outcome\n if self.check_main_diagonal_for_win_iff_it_contains_move():\n return self.game_outcome\n if self.check_off_diagonal_for_win_iff_it_contains_move():\n return self.game_outcome\n if self.check_for_tie():\n return self.game_outcome\n</code></pre>\n\n<p>can be simplified by combining into a single <code>if</code> statement:</p>\n\n<pre><code> if ( self.check_row_containing_move_for_win() or\n self.check_column_containing_move_for_win() or\n self.check_main_diagonal_for_win_iff_it_contains_move() or\n self.check_off_diagonal_for_win_iff_it_contains_move() or \n self.check_for_tie()):\n return self.game_outcome\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T22:50:29.700", "Id": "413777", "Score": "0", "body": "These changes all look good. Since you didn't mention the find_winner_or_tie method, does this mean that the five if statements in that method are the best way to call each of the functions that you helped cleanup? (I got it in my head that when a function has a ton of if statements then it isn't as clean as it could be)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T13:22:56.763", "Id": "414586", "Score": "0", "body": "I just noticed your edit and accepted the answer... that singe if statement with the or between each call works perfectly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T21:46:24.040", "Id": "213916", "ParentId": "213857", "Score": "1" } }, { "body": "<p>(Note: no code in this post has been run- beware errors.)</p>\n\n<p>I have a couple of issues with your design, and with your review request.</p>\n\n<p>First, you say that you are committed to using five different functions for the checking. That's unfortunate, since this problem is very amenable to being solved with iteration.</p>\n\n<p>Next, you have a <code>class GameOutcome</code> that is being asked to identify a winner or tie. I disagree with this- this is something the game itself should do. The game outcome, IMO, would be a data class just collecting results. The name <code>GameOutcome</code> suggest that this class would have no knowledge of the sequence of moves, or the state of the game board.</p>\n\n<p>With those out of the way, let's talk about your code.</p>\n\n<h1>Those names!</h1>\n\n<p>I hate your naming style. You have fallen into the trap of making excessively long names for no good purpose. I <em>strongly suggest</em> you review code written by other people (either here on CodeReview or look through github or the pypi repositories) to get a sense of how names should be chosen. </p>\n\n<p>Consider this line:</p>\n\n<pre><code> if self.check_row_containing_move_for_win():\n</code></pre>\n\n<p>The method <code>check_row_containing_move_for_win</code> is an internal method. It is not intended for use by arbitrary external callers, it is only a method in order to package up its code behind a name. </p>\n\n<p>For an internal function, why not just call it <code>_check_row</code>. </p>\n\n<p>Similarly, you have an externally callable method named <code>find_winner_or_tie</code>. The declaration:</p>\n\n<pre><code>def find_winner_or_tie(self, state_of_game, row_index_of_move, column_index_of_move):\n</code></pre>\n\n<p>Here's a better approach:</p>\n\n<pre><code>def find_winner_or_tie(self, state, row, col):\n \"\"\" Check if either player has won, or if a tie has been forced. Return 'X' or 'O' \n for a win, 'Tie' for a tie, and None when the game is not over.\n\n Parameters:\n state: state of the game\n row: row of the last move\n col: column of the last move\n \"\"\"\n</code></pre>\n\n<p>Providing in-depth explanation is the function of comments, not names. Your names should be as long as they need to be, but no longer.</p>\n\n<h1>Builtins <code>any()</code> and <code>all()</code></h1>\n\n<p>You are writing code that checks for various conditions. Python supplies the <a href=\"https://docs.python.org/3.7/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any()</code></a> and <a href=\"https://docs.python.org/3.7/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all()</code></a> built-ins for situations like this. The trick is to learn to construct iterables in line, and that means using <a href=\"https://docs.python.org/3/reference/expressions.html?highlight=generator%20expression#generator-expressions\" rel=\"nofollow noreferrer\"><em>generator expressions.</em></a></p>\n\n<p>A generator expression is an inside-out for loop in parentheses, like:</p>\n\n<pre><code>(abs(x) for x in somelist)\n</code></pre>\n\n<p>They resemble, and are related to, list, dictionary, and set comprehensions. In all cases there is an iteration keyword (for ... in ...) and some kind of leading expression. With a generator expression, you are constructing a generator in-line and storing it, evaluating it, or passing it as parameters.</p>\n\n<p>How does this help you? Well, suppose you have a group of functions you want to evaluate for success. Say ... five of them? You might decide that you were going to return if <strong>any of those conditions</strong> were true. Well ...</p>\n\n<pre><code>def find_winner_or_tie(self, state, row, column):\n \"\"\" ... \"\"\"\n self.set_board_and_move(state, row, column)\n\n checks = (self.check_row, self.check_column, self.check_diag_lr, self.check_diag_rl, self.check_tie)\n\n if any(check() for check in checks): # If any check is true, we know the outcome\n return self.game_outcome\n\n return None\n</code></pre>\n\n<h1>Less code, more data!</h1>\n\n<p>The thing about most games is that they are based on lots of data. And if you write your code correctly, you will find more and more data, with less and less code. That's the case here. Let's take a look at one of your check-functions:</p>\n\n<pre><code>def check_row_containing_move_for_win(self):\n total = 0\n for column in range(3):\n total = total + int(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]])\n if abs(total) == 3:\n winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]\n self.game_outcome = winning_letter\n return True\n return False\n</code></pre>\n\n<p>Honestly, that's so long that it's unreadable. So let's refactor out the names:</p>\n\n<pre><code>def check_row(self):\n \"\"\"Check row containing latest move for a win.\"\"\"\n bias = self.letter_dict\n board = self.state_of_game.board\n row = self.row_index_of_move\n\n total = 0\n for column in range(3):\n total = total + bias[board[row][column]]\n\n if abs(total) == 3:\n self.game_outcome = board[row][0]\n return True\n return False\n</code></pre>\n\n<p>I think some people have already pointed out <code>sum</code> and some other options. But let's actually spell out what the row and column choices are:</p>\n\n<pre><code>ROWS = [ ((0, 0), (0, 1), (0, 2)),\n ((1, 0), (1, 1), (1, 2)),\n ((2, 0), (2, 1), (2, 2)),\n]\n</code></pre>\n\n<p>Now, you could write code to generate that. In one line, even! But that's not important. What's important is that we know that there's a <code>ROWS</code> variable that can be indexed by row-number and which has a sequence of (row, col) tuples identifying the cells to look at.</p>\n\n<p>Now, how does that help? Well, it helps because you can write a <strong>helper function</strong> that does the checking for you given a sequence of cells. Like this:</p>\n\n<pre><code>def check_cells(self, indices):\n \"\"\" Return True if all gameboard[][] cells specified by indices have same value,\n else False.\n \"\"\"\n board = self.state_of_game.board\n values = [board[row][col] for row,col in indices]\n v0 = values[0]\n return all(v == v0 for v in values)\n</code></pre>\n\n<p>Then you can write the <code>check_</code> functions in terms of that:</p>\n\n<pre><code>def check_row(self):\n \"\"\"Check row containing latest move for a win.\"\"\"\n indices = ROWS[self.row_index_of_move]\n return self.check_cells(indices)\n</code></pre>\n\n<p>You'll have to put in some validation on the diagonals, so you only call the <code>check_cells</code> if the move really was on a diagonal. The key here is that this uses the <code>check_</code> functions to provide <em>more data</em> to the underlying <code>check_cells</code>, and so the bottom level code where the work is getting done is mainly data-driven.</p>\n\n<h1>Extra credit: detect forced ties</h1>\n\n<p>Your tie-detector only triggers at the last minute. But there are plenty of circumstances where a tie is inevitable. Why not code your tie-checker to recognize them?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T00:17:52.013", "Id": "413781", "Score": "0", "body": "You have almost repeated my answer (:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T01:16:33.880", "Id": "413784", "Score": "0", "body": "@outoftime \"Great minds think alike!\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:23:51.290", "Id": "413836", "Score": "0", "body": "your `check_cells` can be even shorter if you use a `set` instead of a list: `return len({board[row][col] for row, col in indices}) == 1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T01:08:54.103", "Id": "413930", "Score": "0", "body": "@AJNeufeld according to the program, it's only called on the row containing a recent move. So the row should never be all blanks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:37:28.457", "Id": "213922", "ParentId": "213857", "Score": "4" } }, { "body": "<blockquote>\n <p>.. I'm pretty set on breaking the checks into 5 different functions because I'm specifically practicing making functions short and single-purposed ...</p>\n</blockquote>\n\n<p>I can not agree that you can avoid sanity during study. If you do not need 5 functions - you should not use them. If you want to practice in making functions - find corresponding usage for it that will make sense.</p>\n\n<blockquote>\n <p>.. But I'm not at all set on my 5 if statements in the <code>find_winner_or_tie</code> method. Does somebody know a more elegant solution for the <code>find_winner_or_tie</code> method so it doesn't have 5 if statements in it? ..</p>\n</blockquote>\n\n<p>You have over complicated everything.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.letter_dict\n</code></pre>\n\n<p>looks like it have to be used for presentation (in the view if we talk about MVC). You have no need to use it at all and can get rid of it simply.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.row_index_of_move\nself.column_index_of_move\n</code></pre>\n\n<p>again, it can help during presentation. During computation you have all data in the arguments so you can pass it deeper and didn't store useless data.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.game_outcome\n</code></pre>\n\n<p>yet another class property you are using just to transfer data, in this case back to caller. Use <code>return</code> statement instead and return tuple of 2 objects if you needed.</p>\n\n<blockquote>\n <p>.. Does somebody know a more elegant solution for the <code>find_winner_or_tie</code> method ..</p>\n</blockquote>\n\n<p>You can try to think in terms of patterns and ask yourself \"what presentation of the pattern will cover all cases at once?\". I suggest that list of coordinates can describe any win case. It's creation will have same loops as you already have but they will be used for <code>patterns</code> generation.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>patterns = []\nfor i in range(3):\n patterns.append( tuple(itertools.product(range(3), [i])) )\n patterns.append( tuple(itertools.product([i], range(3))) )\npatterns.append( zip(range(3), range(3)) )\npatterns.append( zip(range(3), range(2, -1, -1)) )\n</code></pre>\n\n<p>You can generate patterns during initialization and this is the only think I'd like to see as the field of <code>GameOutcome</code> class. Main purpose - caching, so readonly property will be awesome.</p>\n\n<p>Function <code>check_...</code> will simply check every pattern, if all symbols are the same - victorious and return symbol from any pattern coordinates.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for pattern in patterns:\n a, b, c = [self.state_of_game.board[row][col] for row, col in pattern]\n if a == b == c != ' ':\n return (True, a)\nreturn (False, None)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T03:44:28.177", "Id": "413790", "Score": "1", "body": "`a == b and b == c` can be written `a == b == c`. In either case, it repeats the error of detecting 3-blanks-in-a-row. You really want `a == b == c != ' '`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T00:13:45.247", "Id": "213926", "ParentId": "213857", "Score": "1" } }, { "body": "<p>Some point regarding the game</p>\n\n<ul>\n<li>The game has 9 positions. </li>\n<li>The order of moves does not affect the game result.</li>\n<li>Player may not move over another.</li>\n<li>There are 8 possible winning combinations of moves.</li>\n<li>The game is symmetrically invariant so column, row need only be relative, and does not need to match actual board positions.</li>\n</ul>\n\n<p>That means you can encode all the moves for both players in two 9 bit ints</p>\n\n<pre><code>self.moves = {\"X\" : 0, \"O\" : 0}\n\ndef playerMove(self, player, row, col):\n self.moves[player] |= 1 &lt;&lt; (row * 3 + col)\n</code></pre>\n\n<p>You can use a mask to check for a winning move</p>\n\n<pre><code>self.wins = [7,56,448,273,84,292,146,73] \n\ndef isWin(self, player):\n for win in self.wins:\n if (self.moves[player] &amp; win) == win:\n self.game_outcome = player\n return True\n return False\n</code></pre>\n\n<p>You can check for a draw by or'ing (Same as adding because there is no overlap) both players moves</p>\n\n<pre><code>def isDraw(self):\n if (self.moves[\"X\"] + self.moves[\"O\"]) == 511:\n self.game_outcome = 'Tie'\n return True\n return False\n</code></pre>\n\n<p>To reset the game</p>\n\n<pre><code>def reset(self):\n self.moves[\"X\"] = 0\n self.moves[\"O\"] = 0\n</code></pre>\n\n<p>Thus the whole thing becomes</p>\n\n<pre><code>class GameOutcome:\n def __init__(self):\n self.moves = {'X' : 0, 'O' : 0}\n self.game_state = ''\n self.wins = [7, 56, 448, 273, 84, 292, 146, 73] # each has 3bits set\n # bits 0 to 8 in order of above array\n # 000000111,000111000,111000000,100010001,001010100,100100100,010010010,001001001\n # fold them into a 3by3 to get the following patterns\n # 000 000 111 100 001 100 010 001\n # 000 111 000 010 010 100 010 001\n # 111, 000, 000, 001, 100, 100, 010, 001\n\n def get_game_state(self):\n if self.is_win('X') or self.is_win('O'):\n return self.game_state\n self.is_draw()\n return self.game_state\n\n def player_move(self, player, row, col):\n self.moves[player] |= 1 &lt;&lt; (row * 3 + col)\n return None\n\n def is_win(self, player):\n for win in self.wins:\n if (self.moves[player] &amp; win) == win:\n self.game_state = player\n return True\n return False\n\n def is_draw(self):\n if (self.moves[\"X\"] + self.moves[\"O\"]) == 511:\n self.game_state = 'Tie'\n return True\n return False\n\n def reset(self):\n self.moves[\"X\"] = 0\n self.moves[\"O\"] = 0\n self.game_state = ''\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:25:52.153", "Id": "413837", "Score": "0", "body": "I don't like your representation of the winning codes. Why not use binary integer literals like `0b000_000_111` instead of `7`, and a `set` would be a better data structure then a `list`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T20:00:24.547", "Id": "413899", "Score": "0", "body": "@MaartenFabré The `list` is \"static\" (in its use) and does not need protection from item duplication. For performance the `list` beats a `set` when iterating and that is its only use. Because many newbies don't understand that `0b10101010` and `170` are identical items. I wished to highlight that it is a list of ints not a list of (magic) binary numbers, hence the comment below it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T20:08:05.230", "Id": "413901", "Score": "0", "body": "You're correct on the list, i read wrongly you used it to check whether a combination was in the win combination. Whether a comment or the binary representation USD Mort clear is open for debate" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:39:35.373", "Id": "213935", "ParentId": "213857", "Score": "2" } } ]
{ "AcceptedAnswerId": "213916", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T07:59:06.653", "Id": "213857", "Score": "2", "Tags": [ "python", "tic-tac-toe" ], "Title": "Tic Tac Toe check for win/tie in Python" }
213857
<p>i'm trying to make a French timetable in Python, but there's too many if and elif.</p> <pre><code>class Teacher: def __init__(self, name, room): self.room = room self.name = nam def __str__(self): return '{}: {}'.format(self.name, self.room) class Day: def __init__(self, name, week, lessons): self.name = name self.week = week self.lessons = lessons def __str__(self): return '{} {}\n{}'.format( self.name, self.week, '\n'.join(' {!s}'.format(x) for x in self.lessons) a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p = "rien", "rien","rien", "rien", "rien", "rien", "rien", "rien","rien", "rien", "rien", "rien", "rien", "rien","rien", "rien" prog = input("Bonjour! Voulez-vous programmer une matiere dans la semaine? (o/n):").lower() while prog == "o": print("1-Dessin, 2-English, 3-Maths, 4-Info, 5-Electronique, 6-Biochimie:\nChoisissez le chiffre de la matiere a programmer") x = input() print("1-Lundi, 2-Mardi, 3-Mercredi, 4-Jeudi, 5-Vendredi, 6-Samedi:\nChoisissez le chiffre du jour") y = input() print("1- A |8H-11H|, 2- A |11H-13H| , 3- A |14H-17H| :\nA quel heure?") z = input() if ( x == '1' and y == '1' and z == '1' ): if ( a == "rien" ): a=E1 elif ( a != "rien" ): print("!!!!!!DESOLE la session est deja occupee!!!!!! ") elif ( x == '1' and y == '1' and z == '2' ): if ( b == "rien" ): b=E1 elif ( b != "rien" ): print("!!!!!!DESOLE la session est deja occupee!!!!!! ") elif ( x == '1' and y == '1' and z == '3' ): if ( c == "rien" ): c=E1 elif ( c != "rien" ): print("!!!!!!DESOLE la session est deja occupee!!!!!! ") elif ( x == '1' and y == '2' and z == '1' ): if ( d == "rien" ): d=E1 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '2' and z == '2' ): if ( e == "rien" ): e=E1 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '2' and z == '3' ): if ( f == "rien" ): f=E1 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '3' and z == '1' ): if ( g == "rien" ): g=E1 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '3' and z == '2' ): if ( h == "rien" ): h=E1 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi!!! ") elif ( x == '1' and y == '4' and z == '1' ): if ( i == "rien" ): i=E1 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '4' and z == '2' ): if ( j == "rien" ): j=E1 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '4' and z == '3' ): if ( k == "rien" ): k=E1 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '5' and z == '1' ): if ( l == "rien" ): l=E1 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '5' and z == '2' ): if ( m == "rien" ): m=E1 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '5' and z == '3' ): if ( n == "rien" ): n=E1 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '6' and z == '1' ): if ( o == "rien" ): o=E1 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '6' and z == '2' ): if ( p == "rien" ): p=E1 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '1' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi ") if ( x == '2' and y == '1' and z == '1' ): if ( a == "rien" ): a=E2 elif ( a != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '1' and z == '2' ): if ( b == "rien" ): b=E2 elif ( b != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '1' and z == '3' ): if ( c == "rien" ): c=E2 elif ( c != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '2' and z == '1' ): if ( d == "rien" ): d=E2 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '2' and z == '2' ): if ( e == "rien" ): e=E2 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '2' and z == '3' ): if ( f == "rien" ): f=E2 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '3' and z == '1' ): if ( g == "rien" ): g=E2 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '3' and z == '2' ): if ( h == "rien" ): h=E2 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi ") elif ( x == '2' and y == '4' and z == '1' ): if ( i == "rien" ): i=E2 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '4' and z == '2' ): if ( j == "rien" ): j=E2 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '4' and z == '3' ): if ( k == "rien" ): k=E2 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '5' and z == '1' ): if ( l == "rien" ): l=E2 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '5' and z == '2' ): if ( m == "rien" ): m=E2 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '5' and z == '3' ): if ( n == "rien" ): n=E2 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '6' and z == '1' ): if ( o == "rien" ): o=E2 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '6' and z == '2' ): if ( p == "rien" ): p=E2 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '2' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi ") if ( x == '3' and y == '1' and z == '1' ): if ( a == "rien" ): a=E3 elif ( a != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '1' and z == '2' ): if ( b == "rien" ): b=E3 elif ( b != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '1' and z == '3' ): if ( c == "rien" ): c=E3 elif ( c != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '2' and z == '1' ): if ( d == "rien" ): d=E3 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '2' and z == '2' ): if ( e == "rien" ): e=E3 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '2' and z == '3' ): if ( f == "rien" ): f=E3 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '3' and z == '1' ): if ( g == "rien" ): g=E3 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '3' and z == '2' ): if ( h == "rien" ): h=E3 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi ") elif ( x == '3' and y == '4' and z == '1' ): if ( i == "rien" ): i=E3 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '4' and z == '2' ): if ( j == "rien" ): j=E3 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '4' and z == '3' ): if ( k == "rien" ): k=E3 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '5' and z == '1' ): if ( l == "rien" ): l=E3 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '5' and z == '2' ): if ( m == "rien" ): m=E3 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '5' and z == '3' ): if ( n == "rien" ): n=E3 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '6' and z == '1' ): if ( o == "rien" ): o=E3 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '6' and z == '2' ): if ( p == "rien" ): p=E3 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '3' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi ") if ( x == '4' and y == '1' and z == '1' ): if ( a == "rien" ): a=E4 elif ( a != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '1' and z == '2' ): if ( b == "rien" ): b=E4 elif ( b != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '1' and z == '3' ): if ( c == "rien" ): c=E4 elif ( c != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '2' and z == '1' ): if ( d == "rien" ): d=E4 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '2' and z == '2' ): if ( e == "rien" ): e=E4 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '2' and z == '3' ): if ( f == "rien" ): f=E4 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '3' and z == '1' ): if ( g == "rien" ): g=E4 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '3' and z == '2' ): if ( h == "rien" ): h=E4 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi ") elif ( x == '4' and y == '4' and z == '1' ): if ( i == "rien" ): i=E4 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '4' and z == '2' ): if ( j == "rien" ): j=E4 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '4' and z == '3' ): if ( k == "rien" ): k=E4 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '5' and z == '1' ): if ( l == "rien" ): l=E4 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '5' and z == '2' ): if ( m == "rien" ): m=E4 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '5' and z == '3' ): if ( n == "rien" ): n=E4 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '6' and z == '1' ): if ( o == "rien" ): o=E4 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '6' and z == '2' ): if ( p == "rien" ): p=E4 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '4' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi") if ( x == '5' and y == '1' and z == '1' ): if ( a == "rien" ): a=E5 elif ( a != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '1' and z == '2' ): if ( b == "rien" ): b=E5 elif ( b != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '1' and z == '3' ): if ( c == "rien" ): c=E5 elif ( c != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '2' and z == '1' ): if ( d == "rien" ): d=E5 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '2' and z == '2' ): if ( e == "rien" ): e=E5 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '2' and z == '3' ): if ( f == "rien" ): f=E5 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '3' and z == '1' ): if ( g == "rien" ): g=E5 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '3' and z == '2' ): if ( h == "rien" ): h=E5 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi ") elif ( x == '5' and y == '4' and z == '1' ): if ( i == "rien" ): i=E5 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '4' and z == '2' ): if ( j == "rien" ): j=E5 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '4' and z == '3' ): if ( k == "rien" ): k=E5 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '5' and z == '1' ): if ( l == "rien" ): l=E5 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '5' and z == '2' ): if ( m == "rien" ): m=E5 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '5' and z == '3' ): if ( n == "rien" ): n=E5 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '6' and z == '1' ): if ( o == "rien" ): o=E5 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '6' and z == '2' ): if ( p == "rien" ): p=E5 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '5' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi ") if ( x == '6' and y == '1' and z == '1' ): if ( a == "rien" ): a=E6 elif ( a != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '1' and z == '2' ): if ( b == "rien" ): b=E6 elif ( b != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '1' and z == '3' ): if ( c == "rien" ): c=E6 elif ( c != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '2' and z == '1' ): if ( d == "rien" ): d=E6 elif ( d != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '2' and z == '2' ): if ( e == "rien" ): e=E6 elif ( e != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '2' and z == '3' ): if ( f == "rien" ): f=E6 elif ( f != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '3' and z == '1' ): if ( g == "rien" ): g=E6 elif ( g != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '3' and z == '2' ): if ( h == "rien" ): h=E6 elif ( h != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '3' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le mercredi ") elif ( x == '6' and y == '4' and z == '1' ): if ( i == "rien" ): i=E6 elif ( i != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '4' and z == '2' ): if ( j == "rien" ): j=E6 elif ( j != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '4' and z == '3' ): if ( k == "rien" ): k=E6 elif ( k != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '5' and z == '1' ): if ( l == "rien" ): l=E6 elif ( l != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '5' and z == '2' ): if ( m == "rien" ): m=E6 elif ( m != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '5' and z == '3' ): if ( n == "rien" ): n=E6 elif ( n != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '6' and z == '1' ): if ( o == "rien" ): o=E6 elif ( o != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '6' and z == '2' ): if ( p == "rien" ): p=E6 elif ( p != "rien" ): print("!!!DESOLE la session est deja occupee!!! ") elif ( x == '6' and y == '6' and z == '3' ): print("!!!DESOLE les cours s'arretent a midi le samedi ") if ( a == b and b != 'rien' ): print("La matiere programmee Lundi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") b = 'rien' if ( a == c and c != 'rien' ): print("La matiere programmee Lundi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") c = 'rien' if ( b == c and c != 'rien' ): print("La matiere programmee Lundi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") c = 'rien' if ( d == e and e != 'rien' ): print("La matiere programmee Mardi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") e = 'rien' if ( d == f and f != 'rien' ): print("La matiere programmee Mardi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") f = 'rien' if ( e == f and f != 'rien' ): print("La matiere programmee Mardi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") f = 'rien' if ( g == h and h != 'rien' ): print("La matiere programmee Mercredi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") h = 'rien' if ( i == j and j != 'rien' ): print("La matiere programmee Jeudi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") j = 'rien' if ( i == k and k != 'rien' ): print("La matiere programmee Jeudi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") k = 'rien' if ( j == k and k != 'rien' ): print("La matiere programmee Jeudi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") k = 'rien' if ( l == m and m != 'rien' ): print("La matiere programmee Vendredi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") m = 'rien' if ( l == n and n != 'rien' ): print("La matiere programmee Vendredi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") n = 'rien' if ( m == n and n != 'rien' ): print("La matiere programmee Vendredi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") n = 'rien' if ( o == p and p != 'rien' ): print("La matiere programmee Samedi a franchi la limite des 3h de cours, les heures supp seront retires automatiquement") p = 'rien' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T08:54:10.500", "Id": "413643", "Score": "0", "body": "Welcome to CR, can you explain the logic of code in the description please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T08:57:26.707", "Id": "413644", "Score": "0", "body": "what are `a`, `b` etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:07:23.487", "Id": "413656", "Score": "1", "body": "Pleas [edit] the title of your question so it contains what this code achieves (a scheduling application?) and not what you want out of a review. Otherwise we would soon run out of variations of \"How to make my code better\" as question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:18:40.903", "Id": "413659", "Score": "0", "body": "what does `a=E4` do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:00:06.930", "Id": "413714", "Score": "0", "body": "E1, E2...E6 are courses that are not variables...a,b,c.... Are the actual House for each course in the timetable e.g monday we have 3 courses so 'a\" is the firste one, b the second and c the third, tuesday we also have 3 courses so \"d\", \"e\" and \"f\" are their courses and so on, also they are all set to \"rien\" which means \"nothing\" at the beginning and compare ony by one...every day has 3 courses except wednesday and saturday that only got 2" } ]
[ { "body": "<p>You should think about the whole code if it is not possible to create a completely different way. I do not really know what the meaning of this code is.</p>\n\n<p>But you could simplify your code:</p>\n\n<pre><code>if (\n x == '1' and y == '1' and z == '1'\n ):\n if ( \n a == \"rien\" \n ):\n a=E1\n elif ( \n a != \"rien\" \n ):\n print(\"!!!!!!DESOLE la session est deja occupee!!!!!! \")\n elif (...)\n</code></pre>\n\n<p>using this:</p>\n\n<pre><code>result = x+y+z\n\nif result == '111' and a =='rien':\n a = E1\nelif result == '112' and b == 'rien':\n b = E1\nelif ...\n\nelse:\n print(\"!!!!!!DESOLE la session est deja occupee!!!!!! \")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:53:51.263", "Id": "413712", "Score": "0", "body": "Hey, this is smart...thx bro" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:07:40.900", "Id": "213861", "ParentId": "213858", "Score": "3" } }, { "body": "<p>First thing you should consider is creating a function with the parameters x,y,z in it that return the <strong><em>result</em></strong>.</p>\n\n<p>Premièrement tu devrais créer une fonction qui a comme paramatres x,y,z et return le <strong><em>resultat</em></strong></p>\n\n<p>like so:</p>\n\n<pre><code>def function_name(x,y,z):\n if (\n x == '1' and y == '1' and z == '1'\n ):\n...\nreturn result\n</code></pre>\n\n<p>and use dictonaries learn about dictonaries here:\n<a href=\"https://www.tutorialspoint.com/python/python_dictionary.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/python/python_dictionary.htm</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:51:19.123", "Id": "413710", "Score": "0", "body": "Mercii, thank u will try and let you know" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:33:18.527", "Id": "213865", "ParentId": "213858", "Score": "1" } }, { "body": "<p>What about this:</p>\n\n<pre><code>timetable = [[None]*3 for _ in range(6)]\n\nwhile True:\n cours = input(\"0-Dessin, 1-English, 2-Maths, 3-Info, 4-Electronique, 5-Biochimie:\\nChoisissez le chiffre de la matiere a programmer\\n\")\n if cours == '': break\n jour = input(\"0-Lundi, 1-Mardi, 2-Mercredi, 3-Jeudi, 4-Vendredi, 5-Samedi:\\nChoisissez le chiffre du jour\\n\")\n heure = input(\"0- A |8H-11H|, 1- A |11H-13H| , 2- A |14H-17H| :\\nA quel heure?\")\n jour, heure, cours = (int(i) for i in (jour, heure, cours))\n if timetable[jour][heure] is not None:\n timetable[jour][heure] = cours\n</code></pre>\n\n<p>It creates an array you can access with <code>timetable[jour][heure]</code> to get the course at that particular time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:51:42.270", "Id": "413711", "Score": "0", "body": "Impressive...will look at it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:37:21.727", "Id": "413722", "Score": "0", "body": "hen i tried i have error \"list indices must be integer or slices, not str\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:42:13.263", "Id": "413723", "Score": "0", "body": "Right, your input must be converted to int, I edited my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:02:23.913", "Id": "413732", "Score": "0", "body": "Thank u, now it says that list index out of range when i tried different number (3-3-3)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:10:10.583", "Id": "413734", "Score": "0", "body": "Note that the number in my example start at zero, if you wish to change that. Then change `(int(i) for i in (jour, heure, cours))` to `(int(i) - 1 for i in (jour, heure, cours))`. (`Dessin` is `0`)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:42:37.833", "Id": "213869", "ParentId": "213858", "Score": "2" } }, { "body": "<h1>Enums</h1>\n\n<p>You have a definite number of courses, weekdays and timeslots. So instead of using numbers to represent them, you can better use <code>Enum</code>s</p>\n\n<pre><code>from enum import Enum\nclass Courses(Enum):\n Dessin = 1\n English = 2\n Maths = 3\n Info = 4\n Electronique = 5\n Biochimie = 6\n\nclass Timeslots(Enum):\n morning = \"|8H-11H|\"\n noon = \"|11H-13H|\"\n afternoon = \"|14H-17H|\"\n\nclass Weekdays(Enum):\n Lundi = 1\n Mardi = 2\n Mercredi = 3\n Jeudi = 4\n Vendredi = 5\n Samedi = 6\n</code></pre>\n\n<h1><code>\"rien\"</code></h1>\n\n<p>You use <code>\"rien\"</code> as a sentinel value. A better way to express this would be to use <code>None</code></p>\n\n<h1>input</h1>\n\n<p>There is a lot of reused code to get the input, and no validation. Better would be to use a separate function to gather the input</p>\n\n<pre><code>def get_input(inputs, message=\"\"):\n while True:\n try:\n msg = \", \".join(f\"{value.value}-{value.name}\" for value in inputs)\n msg += message\n value= input(msg)\n if value.isdigit():\n return inputs(int(value))\n return inputs[value]\n except (KeyError, ValueError):\n pass\n</code></pre>\n\n<p>This can be used as:</p>\n\n<pre><code>course = get_input(Courses, \"\"\"\nChoisissez le chiffre de la matiere a programmer\n\"\"\")\nday = get_input(Weekdays, \"\"\"\nChoisissez le chiffre du jour\n\"\"\")\ntimeslot = get_input(Timeslots, \"\"\"\nChoisissez la heure\n\"\"\")\n</code></pre>\n\n<p>The last one might need a slightly different approach</p>\n\n<h1>if-elif</h1>\n\n<p>Then at least the long <code>if-elif-else</code> would be clear:</p>\n\n<pre><code>if (course = Courses.Dessin and day = Weekdays.Lundi and timeslot = Timeslots.morning):\n...\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>if x == \"1\" and y == \"1\" and z == \"1\":\n</code></pre>\n\n<h1>dict</h1>\n\n<p>Even better would be to use a datastructure to capture the schedule, instead of variables <code>a</code> to <code>p</code>. You can easily create a dict of class times:</p>\n\n<pre><code>from itertools import product\nschedule= {\n day: {\n time: None\n for time in Timeslots\n if not (\n day in {Weekdays.Mercredi, Weekdays.Samedi}\n and time == Timeslots.afternoon\n )\n }\n for day in Weekdays\n}\n</code></pre>\n\n<p>This results in:</p>\n\n<pre><code>{&lt;Weekdays.Lundi: 1&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None,\n &lt;Timeslots.afternoon: '|14H-17H|'&gt;: None},\n &lt;Weekdays.Mardi: 2&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None,\n &lt;Timeslots.afternoon: '|14H-17H|'&gt;: None},\n &lt;Weekdays.Mercredi: 3&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None},\n &lt;Weekdays.Jeudi: 4&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None,\n &lt;Timeslots.afternoon: '|14H-17H|'&gt;: None},\n &lt;Weekdays.Vendredi: 5&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None,\n &lt;Timeslots.afternoon: '|14H-17H|'&gt;: None},\n &lt;Weekdays.Samedi: 6&gt;: {&lt;Timeslots.morning: '|8H-11H|'&gt;: None,\n &lt;Timeslots.noon: '|11H-13H|'&gt;: None}}\n</code></pre>\n\n<p>Now to check whether a slot has been taken already, instead of the long if-elif-else, you get</p>\n\n<pre><code>if schedule[day][timeslot] is not None:\n print(\"!!!!!!DESOLE la session est deja occupee!!!!!! \")\n</code></pre>\n\n<p>and program a class with</p>\n\n<pre><code>else:\n schedule[day][timeslot] = course\n</code></pre>\n\n<p>Now to tackle the fact that on Saturday there is only one slot, you can precede this with:</p>\n\n<pre><code>if time not in schedule[day]:\n print(\"!!!DESOLE les cours s'arretent a midi le mercredi et samedi\")\n</code></pre>\n\n<p>Even better would be to abstract this in a different functions, but I suggest you already try to incorporate these tips, and then see how far you get, and open a next question if you need more help. </p>\n\n<p>Some future way forwards:</p>\n\n<ul>\n<li>return values instead of printing messages</li>\n<li>externalize the checks whether a certain course can be taken at a certain time</li>\n<li>use <code>Exception</code>s to communicate failures, instead of print messages</li>\n<li>To tackle the choice of not allowing the same course on one day, you can implement a small validator</li>\n<li>Abstract the schedule to a <code>Class</code> instead of a <code>dict</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:50:48.923", "Id": "413709", "Score": "0", "body": "Hello, thank you for your reoly, it helped me alot, altough i have an error somehow it says \"name day is not defined\" on {if schedule[day][timeslot] not NONE}...and also i dont know how to print each days with its respectives courses and hours" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:57:24.823", "Id": "213871", "ParentId": "213858", "Score": "4" } } ]
{ "AcceptedAnswerId": "213871", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T08:25:00.400", "Id": "213858", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Making a timetable based on user choices, in French" }
213858
<p>I did another exercise, this time it simulates n games of craps(dice game) and outputs the wins and win percentage!</p> <pre><code>#craps.py -- Simulates multiple games of craps # and estimates the probability that the player wins. import random def output(wins, total): winrate = wins / total print("The player won {0} of {1} games ({2:0.2%})".format(wins, total, winrate)) def rolldies(): dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) roll = dice1 + dice2 return roll def simOneGame(): initial_roll = rolldies() if initial_roll == 2 or initial_roll == 3 or initial_roll == 12: return True # won elif initial_roll == 7 or initial_roll == 11: return False #lost else: #Roll until roll is 7 or initial roll roll = rolldies() while roll != 7 and roll != initial_roll: roll = rolldies() if roll == 7: return True #won else: #roll is inital_roll return False #lost def simNGames(games_to_sim): wins = 0 for i in range(games_to_sim): if simOneGame(): wins += 1 return wins def main(): games_to_sim = int(input("How many games to simulate? ")) wins = simNGames(games_to_sim) output(wins, games_to_sim) if __name__ == "__main__": main() </code></pre> <p>Always open for suggestions on what to improve/do differently or more pythonic.</p>
[]
[ { "body": "<p>First, Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which programmers are encouraged to follow. This makes it easier for other Python programmers to read your code. PEP8 recommends using <code>lower_case</code> both for variable and function names, which I have used in the code below.</p>\n\n<p>In your <code>output</code> function you use string formatting (good). However note that if you just want to paste the values in order, there is no need to explicitly mention the indices. So you could write <code>\"The player won {} of {} games ({:0.2%})\".format(wins, total, winrate)</code>. But there is an even easier way in <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">Python 3.6+: f-strings</a>. I also think this is not enough to put it into a function, I would just leave it as a single line in <code>main</code>:</p>\n\n<pre><code>print(f\"The player won {wins} of {total} games ({wins/total:0.2%})\")\n</code></pre>\n\n<p>Your <code>rolldies</code> function could be made more general if it accepted a parameter telling it how many dice to roll. You can also use a list comprehension here, or <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a>:</p>\n\n<pre><code>def roll_dice(n=2):\n return sum(random.randint(1, 6) for _ in range(n))\n\nDIE = [1, 2, 3, 4, 5, 6]\ndef roll_dice(n=2):\n return sum(random.choices(DIE, k=n))\n</code></pre>\n\n<p>Note that the singular is \"die\" and the plural is \"dice\", not \"dies\".</p>\n\n<p>In your <code>simOneGame</code> function, instead of chaining a lot of comparisons with <code>or</code>, just use <code>in</code>:</p>\n\n<pre><code>def sim_game():\n initial_roll = roll_dice()\n if initial_roll in {2, 3, 12}:\n return True # won\n elif initial_roll in {7, 11}:\n return False # lost\n</code></pre>\n\n<p>Your rolling in the <code>else</code> branch can also be a bit shortened:</p>\n\n<pre><code> else:\n #Roll until roll is 7 or initial roll\n roll = roll_dice()\n while roll not in {7, initial_roll}:\n roll = roll_dice()\n return roll == 7 # 7 wins\n</code></pre>\n\n<p>You could theoretically replace the <code>while</code> loop with a single <code>random.choices</code> call, but you would have to manually set the probabilities to the right values.</p>\n\n<p>The <code>simNGames</code> function can be shortened a lot by using the fact that <code>False == 0</code> and <code>True == 1</code>:</p>\n\n<pre><code>def sim_n_games(n):\n return sum(sim_game() for _ in range(n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:40:28.670", "Id": "413645", "Score": "0", "body": "What is the difference between \"in (2,3,12)\" and \"in {2,3,12}\" ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:42:05.520", "Id": "413646", "Score": "0", "body": "@Meph-: The first one is a `tuple` and the latter one a `set`. For small collections there will be basically no difference, but a `set` has `O(1)` membership testing, while a `tuple` is slightly faster to construct, but has `O(n)` membership testing. On my machine `1 in (2, 3, 12)` takes 53.9 ns ± 0.361 ns and `1 in {2, 3, 12}` takes 55.2 ns ± 2.07 ns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:47:15.490", "Id": "413648", "Score": "0", "body": "@Meph-: And for completeness sake (and to show that it is better than chaining `or`), `1 == 2 or 1 == 3 or 1 == 12` takes 73.3 ns ± 0.658 ns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:59:42.463", "Id": "413654", "Score": "1", "body": "I'll put the formatting changes to use! Thanks. As to using \"in\", i simply havent learned that yet(tuples, sets),it will probably come later in my programming book, but I'll implement it right away. Really seems to be the better choice. Sorry for the die/dice mixup haha." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:17:33.547", "Id": "413658", "Score": "0", "body": "Okay, it seems like\n`print(f\"The player won {wins} of {total} games ({wins/total:0.2%})\")` doesn't work. i think you can't calculate anything in there" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:19:39.137", "Id": "413661", "Score": "0", "body": "@Kevin: No, it should work. You can use arbitrary Python expressions inside f-strings (and even some subset of Python expressions like attribute and item access in the format string you are using)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:20:50.117", "Id": "413662", "Score": "0", "body": "@Graipher it recognizes the `:` in `{wins/total:0.02}` as the end of the whole statement in the brackets, not sure why. Everything after and including the `:` is seen as string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:21:42.957", "Id": "413663", "Score": "0", "body": "@Kevin: Well, I just copy & pasted it (from your comment), just to be sure, with `wins, total = 10, 23` and it works on my machine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:22:19.823", "Id": "413664", "Score": "0", "body": "@Kevin: Maybe you are missing the `%`? You either need that or a `:0.2f`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:24:12.810", "Id": "413665", "Score": "0", "body": "@Graipher Here's a screenshot: https://imgur.com/a/nMUsSFY" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:25:25.533", "Id": "413666", "Score": "0", "body": "@Kevin: Looks fine to me? It even correctly colors the expression part. Have you tried running that line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:26:51.190", "Id": "413667", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/89969/discussion-between-graipher-and-kevin)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:28:59.007", "Id": "413668", "Score": "0", "body": "@Graipher It prints `The player won 100 of 200 games (0.5)`. What throws me off is that the last `}` isn't in red, but in green, indicating it's part of the string." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T09:35:03.527", "Id": "213866", "ParentId": "213859", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T08:43:20.897", "Id": "213859", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "simulation" ], "Title": "Craps Simulator Exercise" }
213859
<p>I have coded multiple variations on this and would like to make it generic, to avoid coding any more variations. </p> <p>Comments and suggested improvements, please, (typos also), and what about that ToDo ?</p> <p>I often want to parse a text file and split it into chunks, generally those lines between two lines containing known keywords.</p> <p>E.g.</p> <ul> <li>zero or more lines of text</li> <li>A start </li> <li>zero or more lines of text -A end</li> <li>zero or more lines of text</li> <li>B start</li> <li>zero or more lines of text</li> <li>B end</li> <li>zero or more lines of text</li> <li>B start</li> <li>zero or more lines of text</li> <li>C end</li> <li>zero or more lines of text</li> </ul> <p>Note that “zero or more”. </p> <p>Also, note that some sections are optional. For instance, knowing that there are no lines between sections, to get the A related text, I can specify a start as any line containing “A start” and an end as any line containing “A end”. BUT, since B and C are optional, my end for A is any one of “A end”, “B end” or “C end”.</p> <p>And sometimes I know that I am on the start line (it may not even contain a keyword).</p> <p>More detail in the header comment (where it belongs). Please help me to improve this code.</p> <pre><code># +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ # Given the lines and current line number, this function reads # from the current line (or the first following line containing the start string, # returning empty string if not found) and returns all lines between # the line after that and the first line containing any of the end strings # (or end of lines) - not including the line with the terminating string. # # @param [in] lines - list of strings # # @param [in] lineNumber - current index to lines parameter # # @param [in] searcrhForStartString - Bool; set to False if currently positioned # at the start line, and there is no start # string to search for # # @param [in] startStrings - list of strings (even if there is only one) # If param searcrhForStartString == True # then search param lines until one contains # one of these lines. Returned lines will start # at the next line, skipping the keyword # (start at current line if param # searcrhForStartString is False). # # Will return an empty list if no match is found # @param [in] endStrings - a list (even if there is only one) of strings. # Search until a line containing one of these is found # (or end of lines) and return all lines # from the first until the line prior to this # (do not include keyword line) # # @param [in] errorOnEndOfLines - if True, will return an empty list # if no end string is found # before the end of param lines # @return - list of strings # # ToDo: consider (a) parameter(s) to indicate that lines must start with, # or be equal to, a search string, rather than just containing? # That would make this even more generic, but would require (an) extra parameter(s) # def GetLinesBetween(lines,lineNumber, searcrhForStartString, startStrings, endStrings, errorOnEndOfLines): try: result = [] # emmpty list line = lines[lineNumber] if searcrhForStartString: while not any(keyword in line for keyword in startStrings): lineNumber += 1 if lineNumber == len(lines): if errorOnEndOfLines: result.clear() return result line = lines[lineNumber] #serach string matched, if requested, so advance one line to skip it lineNumber += 1 line = lines[lineNumber] # Line number now indexes the first line of what we want to return while lineNumber &lt; len(lines): if any(keyword in line for keyword in endStrings): return result result.append(line) lineNumber += 1 if not lineNumber == len(lines): line = lines[lineNumber] if lineNumber == len(lines): if errorOnEndOfLines: result.clear() return result #----------------------- except Exception as err: print('Exception:') exc_type, exc_value, exc_tb = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_tb) sys.exit(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:29:43.803", "Id": "413669", "Score": "4", "body": "The function specification itself is rather complicated, and could probably be improved, if you included the code that calls this function. Including some sample inputs and outputs would help clarify the expected behavior as well." } ]
[ { "body": "<p>This is some interesting code, thanks for posting it here. Good work Mawg.</p>\n\n<p><strong>Nitpicking</strong></p>\n\n<blockquote>\n<pre><code># +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n# Given the lines and current line number, this function reads\n# from the current line (or the first following line containing the start string,\n</code></pre>\n</blockquote>\n\n<p>Please get rid of banners like this. If you are using an IDE such as PyCharm it can generate documentation comments for you. Current python industry standard regarding documentation is PEP-287.</p>\n\n<ol>\n<li><a href=\"https://www.python.org/dev/peps/pep-0287/\" rel=\"nofollow noreferrer\">PEP-287</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format\">Related SO Question</a></li>\n</ol>\n\n<blockquote>\n<pre><code>lines,lineNumber,\n</code></pre>\n</blockquote>\n\n<p>Use consistent spacing. I personally like to use <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">black</a> to format my code. But you can use anything that formats to PEP8.</p>\n\n<blockquote>\n<pre><code>GetLinesBetween, lineNumber, ...\n</code></pre>\n</blockquote>\n\n<p>Please use correct PEP8 style such as <code>get_lines_between</code> and <code>line_number</code>?</p>\n\n<blockquote>\n<pre><code>#-----------------------\nexcept Exception as err:\n print('Exception:')\n exc_type, exc_value, exc_tb = sys.exc_info()\n</code></pre>\n</blockquote>\n\n<p>This is sloppy exception handling. </p>\n\n<ul>\n<li>If you must use a catch-all: Maybe use a higher level method that captures exceptions and change this to\n<code>try_get_lines_between</code> or <code>_get_lines_between</code> as a more readable alternative. \n<strong>Why</strong>: separation of error handling and application logic - It is up to you to decide if this is best course of action.</li>\n<li>You\ncan also create your own exceptions if that is more suitable to you. You can for example raise them instead of returning empty list if it is more suitable. </li>\n<li>Use a <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\">logger</a> instead of print to log exceptions. <code>logger.exception</code> is more suitable for this.</li>\n<li>Instead of <code>sys.exit(0)</code> - maybe exit with non zero value so you know that there was an error.</li>\n</ul>\n\n<blockquote>\n <p>emmpty, serach</p>\n</blockquote>\n\n<p>Please use a spell checker plugin in your IDE.</p>\n\n<blockquote>\n<pre><code># ToDo: consider (a) parameter(s) to indicate that lines must start with,\n# or be equal to, a search string, rather than just containing?\n# That would make this even more generic, but would require (an) extra parameter(s)\n#\n</code></pre>\n</blockquote>\n\n<p>People sometimes forget to do to-dos. Use a software like JIRA, Github Projects to track your tasks and remove them from code. It's OK to create tasks for yourself.</p>\n\n<p><strong>How would I design this better?</strong></p>\n\n<ul>\n<li>Use generators instead of creating lists, so you can create pipeline of functions and can even read multiple files, and also save some memory.</li>\n<li>Maybe use <a href=\"https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm\" rel=\"nofollow noreferrer\">Aho-Corasick</a> algorithm (Trie based) to match against multiple strings.</li>\n<li>Sensible defaults - there are lot of parameters for this function. If you add default values then API would be easier to use.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:46:31.297", "Id": "413697", "Score": "0", "body": "Thanks very much for the feedback. 1) \"generate documentation comments for you\" - wilco 2) \"Use consistent spacing\" - I thought that I did, but will check 3) \"use correct PEP8 style\" for variable/function names - alas, several decades of embedded C programming have ingrained this, so I am unlikely to change :-( 4) \"This is sloppy exception handling ... •Use a higher level methods that captures exceptions and a try_get_lines_between method\" - I don't see what that would buy me, just shoving it upwards into a wrapper; what am I missing? --->" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:47:44.897", "Id": "413698", "Score": "0", "body": "---> 5) \"Use a logger instead of print to log exceptions\" - sounds good. Thanks for all of your feedback. Btw, 6) what do you think of the ToDo? and 7) the function does not have to return `lines` as it never changes it (I just did my own review :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:11:22.730", "Id": "413716", "Score": "1", "body": "@Mawg there are various ways to do your todo. You can for example pass lambda functions as arguments (default to `in`), pass `lambda line, keyword: line.startswith(keyword)` when you want to handle starts with. Flag functions however become more complex overtime so be warned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:15:22.383", "Id": "413718", "Score": "1", "body": "I've added more points to answer as well." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:33:15.933", "Id": "213868", "ParentId": "213867", "Score": "2" } } ]
{ "AcceptedAnswerId": "213868", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:03:14.707", "Id": "213867", "Score": "2", "Tags": [ "python", "python-3.x", "file" ], "Title": "Python code to get all lines between two keyword lines in a file (with exceptions)" }
213867
<p>I have been given a list of simple Customer objects to work with. This would be an example of a customer list:</p> <pre><code>customers = [ Customer(active=True, age=38, gender='F'), Customer(active=False, age=18, gender='M'), None, Customer(active=False, gender='F'), None, Customer(age=64), Customer(active=True, age=23), None, Customer(age=23, gender='M'), None, ] </code></pre> <p>The list contains <code>None</code> values for customers that have been deleted and <code>active</code>, <code>gender</code> and <code>age</code> are not required properties of <code>Customer</code> and so they can be un-set.</p> <p>To find the number of active customers:</p> <pre><code>def number_of_active_customers(customers): # Assumption: A customer is only active if active=True is set return len([customer for customer in customers if customer is not None and customer.active is True]) </code></pre> <p>To find the number of inactive customers:</p> <pre><code>def number_of_inactive_customers(customers): # Assumption: Deleted customers also count as inactive return len([customer for customer in customers if customer is None or customer.active in (False, None)]) </code></pre> <p>To find out if the list of customers has any <code>None</code> values:</p> <pre><code>def list_has_none_values(customers): # any() won't work here since a list of None's always evaluates to False. We don't need to know the length # of the list so we can simply loop over each element and return True when we encounter the first None value for customer in customers: if customer is None: return True return False </code></pre> <p>To find out if the list has any customers with <code>active=None</code>:</p> <pre><code>def list_has_active_equals_none_customers(customers): # any() works here because we can stop processing at the first True value in the list return any([customer for customer in customers if customer is not None and customer.active is None]) </code></pre> <p>To find the average age of male customers:</p> <pre><code>def average_age_of_male_customers(customers): try: # Round average to 1 digit return round( mean( (customer.age for customer in customers if customer is not None and customer.gender == 'M' and isinstance(customer.age, int)) ), 1) except StatisticsError: # Return 0 when there are no male customers return 0 </code></pre> <p>My code should be as pythonic and efficient as possible. I'm fairly sure I got it, I'm just second-guessing myself a little. This is not a school assignment and I am allowed to ask for help.</p>
[]
[ { "body": "<p>If you need to do more data analysis on this afterwards, then this might be a good time to learn about <a href=\"http://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><code>pandas</code></a> which has data frames, allowing you to modify whole records at a time.</p>\n\n<p>First, read in your list into a data frame:</p>\n\n<pre><code>import pandas as pd\n\ndf = pd.DataFrame([[customer.active, customer.age, customer.gender]\n for customer in filter(None, customers)],\n columns=[\"active\", \"age\", \"gender\"])\n</code></pre>\n\n<p>Here the <code>filter(None, it)</code> filters out all <code>None</code> values (and all falsey values, but an object that exists is by default truthy, so unless you overwrote <code>Customer.__eq__</code> or <code>Customer.__bool__</code>, it should be fine).</p>\n\n<p>Now we have a data frame like this:</p>\n\n<pre><code>print(df)\n# active age gender\n# 0 True 38.0 F\n# 1 False 18.0 M\n# 2 False NaN F\n# 3 None 64.0 None\n# 4 True 23.0 None\n# 5 None 23.0 M\n</code></pre>\n\n<p>To make handling of the left over <code>None</code> values easier, we replace them with <code>numpy.nan</code>:</p>\n\n<pre><code>import numpy as np\n\ndf = df.replace([None], np.nan)\nprint(df)\n# active age gender\n# 0 True 38.0 F\n# 1 False NaN M\n# 2 False NaN F\n# 3 NaN 64.0 NaN\n# 4 True 23.0 NaN\n# 5 NaN 23.0 M\n</code></pre>\n\n<p>Now to get to your tasks:</p>\n\n<ul>\n<li><p>Number of active customers:</p>\n\n<pre><code>active_users = df.active.sum()\n# 2\n</code></pre></li>\n<li><p>Number of inactive customers:</p>\n\n<pre><code>deleted_users = sum(customer is None for customer in customers)\ninactive_users = len(df) + deleted_users - active_users\n# 8\n</code></pre></li>\n<li><p>Any customer deleted:</p>\n\n<pre><code>deleted_users &gt; 0\n# True\n</code></pre></li>\n<li><p>Any customer with active=None:</p>\n\n<pre><code>df.active.isna().any()\n# True\n</code></pre></li>\n<li><p>Average of male customers (NaNs are automatically ignored):</p>\n\n<pre><code>df[df.gender == \"M\"].age.mean()\n# 20.5\n</code></pre>\n\n<ul>\n<li><p>If there are no people of that gender, it will return a <code>numpy.nan</code> instead of <code>0</code>, though:</p>\n\n<pre><code>df[df.gender == \"X\"].age.mean()\n# nan\n</code></pre></li>\n</ul></li>\n</ul>\n\n<p>From there on you can also do more fancy stuff:</p>\n\n<ul>\n<li><p>Average age per gender:</p>\n\n<pre><code>df.groupby(\"gender\").age.mean()\n# gender\n# F 38.0\n# M 20.5\n# Name: age, dtype: float64\n</code></pre></li>\n</ul>\n\n<p>Using this makes your code both more efficient to write (since most things you could want to do are already implemented) as well as faster to run (since the methods are usually implemented in C, instead of running in Python. So if you have lots of customers, this will certainly be better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-24T19:16:11.850", "Id": "414184", "Score": "0", "body": "Thanks for your elaborate review! I had thought about using pandas but the assignment was to keep it as simple as possible. Definitely a good option for the future though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:21:39.867", "Id": "213874", "ParentId": "213870", "Score": "2" } }, { "body": "<p>I want to encourage you to be more pythonic in a couple of ways.</p>\n\n<h3>0. Provide reviewable code!</h3>\n\n<p>You didn't provide a solid block of code that I could copy/paste. You didn't provide even a dummy class definition for <code>Customer</code>. You got three \"likes\" before my review, and an answer from at least one other person (@Graipher). Respect the time of the reviewers and readers by making their jobs as stress-free as possible: provide reviewable code that compiles, runs, includes all the necessary imports, etc.</p>\n\n<h3>1. Write PEP-8 code</h3>\n\n<p>Seriously: go and read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. It's not that long, it's not difficult, and it's full of advice that, while you may not agree with it, will provide you with a consistent, readable Python coding style that will seem familiar and \"Pythonic\" to other coders.</p>\n\n<p>In your specific case, I mean for you to tighten up your names and start structuring your code using docblocks:</p>\n\n<pre><code>def number_of_active_customers(customers):\n # Assumption: A customer is only active if active=True is set\n return len([customer for customer in customers if customer is not None and customer.active is True])\n</code></pre>\n\n<p>Should be something like:</p>\n\n<pre><code>def count_active(customers):\n \"\"\" Return number of active customers.\n\n A customer is active if the .active attribute is set to True.\n \"\"\"\n return len([customer for customer in customers if customer is not None and customer.active is True])\n</code></pre>\n\n<h3>2. Use iteration instead of lists</h3>\n\n<p>Let's look at that last function again:</p>\n\n<pre><code>def number_of_active_customers(customers):\n\n return len([customer for customer in customers if customer is not None and customer.active is True])\n</code></pre>\n\n<p>What you are doing is calling <code>len</code> on a <em>list comprehension</em> in order to count the number of customers that are active. The problem is that you're <em>building a list</em> in order to count it. Lists consume memory and slow things down, while iterating will produce the same result without allocating any storage that you will immediately throw away at the end of the expression.</p>\n\n<p>Tragically, you can't just replace your list with a <a href=\"https://stackoverflow.com/q/47789/4029014\"><em>generator expression</em></a> and get the same result, since generators don't come with a <code>len</code> method. But you can check out the <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipes</a> and find <code>quantify</code>:</p>\n\n<pre><code>def quantify(iterable, pred=bool):\n \"\"\"Count how many times the predicate is true\"\"\"\n return sum(map(pred, iterable))\n\ndef number_of_active_customers(customers):\n return quantify(customer for customer in customers if customer is not None and customer.active is True)\n\n# or ...\ndef number_of_active_customers(customers):\n return quantify(customers, lambda c: c is not None and c.active)\n</code></pre>\n\n<h3>3. Laziness is next to ... godliness?</h3>\n\n<p>Well, maybe laziness is next to lethargy. But it's also one of the <a href=\"http://threevirtues.com/\" rel=\"nofollow noreferrer\"><em>three virtues of a <strong>great</strong> programmer</em></a> and that has to count for something!</p>\n\n<p>You say: </p>\n\n<pre><code>customer in customers if customer is not None and customer.active is True\n\ncustomer in customers if customer is None or customer.active in (False, None)\n</code></pre>\n\n<p>Be lazy! In Python, the truthiness of <code>None</code> is false. And the expression <code>a is b</code> is a boolean expression. And the expression <code>a in b</code> is a boolean expression. So go ahead and say:</p>\n\n<pre><code>customer in customers if customer is not None and customer.active\n\ncustomer in customers if customer is None or not customer.active\n</code></pre>\n\n<h3>4. Don't Repeat Yourself!</h3>\n\n<p>How can I be saying this? Let's look at your code:</p>\n\n<pre><code>return len([customer for customer in customers if customer is not None and customer.active is True])\n\nreturn any([customer for customer in customers if customer is not None and customer.active is None])\n\n(customer.age for customer in customers if customer is not None\n and customer.gender == 'M' and isinstance(customer.age, int))\n</code></pre>\n\n<p>There sure is a lot of repetition in there!</p>\n\n<p>Consider <code>customer in customers if customer is not None</code>. What is that? Well, sadly <code>None</code> is a valid customer entry since that how deleted items appear. But couldn't we just pick a name for that? How about <strong>remaining customers?</strong></p>\n\n<pre><code>def remaining_customers(customers):\n \"\"\"Return only non-deleted customers (deleted items are set to None)\"\"\"\n return (customer for customer in customers if customer is not None)\n</code></pre>\n\n<p>As soon as you define that one function (note: it returns an <em>iterable</em> not a list) everything else gets shorter! To wit:</p>\n\n<pre><code>return len([customer for customer in remaining_customers() if customer.active])\n\nreturn any([customer for customer in remaining_customers() if customer.active is None])\n\n(customer.age for customer in remaining_customers() \n if customer.gender == 'M' and isinstance(customer.age, int))\n</code></pre>\n\n<p><strong>But wait! There's more!</strong></p>\n\n<p>Because in addition to some <em>conditional expressions</em> that are repeated, I see a lot of <em>structure</em> that is repeated. Many of your functions take the form \"iterate over the customers, selecting values that match some condition\". I wonder if there's a shortcut for that? </p>\n\n<p>You could use the built-in <a href=\"https://docs.python.org/3.7/library/functions.html#filter\" rel=\"nofollow noreferrer\"><code>filter(function, iterable)</code></a> function,\nbut that doesn't quite get it:</p>\n\n<pre><code>return quantify(filter((lambda c: c.active), remaining_customers(customers)))\n</code></pre>\n\n<p>However, a little applied laziness leads to the observation that most of your operations boil down to:</p>\n\n<ul>\n<li>ask if any customer matches a conditon</li>\n<li>count how many customers match a condition</li>\n<li>select all customers matching a condition and return them</li>\n</ul>\n\n<p>You can write those functions directly:</p>\n\n<pre><code>from typing import Callable, Iterable\n\ndef any_customers(customers, where: Callable[[Customer], bool]) -&gt; bool:\n \"\"\"Return whether the callable returns True for any customer.\"\"\"\n return any(where(c) for c in customers)\n\ndef count_customers(customers, where: Callable[[Customer], bool]) -&gt; int:\n \"\"\"Count when callable returns True over all customers.\"\"\"\n return quantify(customers, where)\n\ndef select_customers(customers, where: Callable[[Customer], bool]) -&gt; Iterable[Customer]:\n \"\"\"Yield each customer where callable returned True.\"\"\"\n return filter(where, customers)\n</code></pre>\n\n<p>With those in hand:</p>\n\n<pre><code>def count_active_customers(customers):\n return count_customers(remaining_customers(customers), lambda c: bool(c.active))\n\ndef count_inactive_customers(customers):\n return count_customers(customers, lambda c: c is None or not c.active)\n\ndef have_deleted_customers(customers):\n return any_customers(customers, lambda c: c is None)\n\ndef have_active_none_customers(customers):\n return any_customers(remaining_customers(customers), lambda c: c.active is None)\n</code></pre>\n\n<p>Finding the average age of male customers requires two steps because of the necessity to extract the <code>.age</code> field. If you write your <code>select_customers()</code>\nfunction with enough parameters, you might be able to eliminate that (take a <code>fields=</code> parameter, return tuples, except with only one field return the values directly, maybe parse simple SQL statements, etc...). But you probably ain't gonna need that!</p>\n\n<pre><code>def avg_age_males(customers):\n male_customers = select_customers(remaining_customers(customers),\n lambda c: c.gender == 'M')\n try:\n # Round average to 1 digit\n return round(\n mean(c.age for c in male_customers if isinstance(c.age, int)),\n 1)\n except StatisticsError:\n # Return 0 when there are no male customers\n return 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-24T19:16:50.717", "Id": "414185", "Score": "0", "body": "thanks for your elaborate review! Some great tips here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T04:09:30.977", "Id": "214001", "ParentId": "213870", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T10:46:11.417", "Id": "213870", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Statistical queries on a list of customers" }
213870
<p>I am working on a utility function to get the current date and time. My objective is to do this in a generic and portable way. I would like to stay way from platform specific code to allow the functionally of this method to be portable.</p> <p>I had originally asked a <a href="//stackoverflow.com/q/54762432">question</a> over at Stack Overflow followed up by <a href="//stackoverflow.com/q/54779677">another question</a>.</p> <p>The question(s) that I had asked in the former Stack Overflow Q/A is more relevant that the first in regards to this question or set of questions.</p> <hr> <p>Here is the code that I had written to get the current date and time:</p> <h2>DateAndTime.h</h2> <pre><code>#pragma once #include &lt;ctime&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; namespace util { enum class TimeLocale { LOCAL = 0x01, GMT = 0x02, BOTH = (LOCAL | GMT) }; inline TimeLocale operator|(TimeLocale a, TimeLocale b) { return static_cast&lt;TimeLocale&gt;(static_cast&lt;int&gt;(a) | static_cast&lt;int&gt;(b)); } #pragma warning( push ) #pragma warning( disable : 4996 ) inline void currentDateAndTime(std::stringstream&amp; stream, TimeLocale locale) { std::time_t t = std::time(nullptr); if (locale == TimeLocale::GMT) { stream &lt;&lt; "UTC: " &lt;&lt; std::put_time(std::gmtime(&amp;t), "%c, %Z") &lt;&lt; '\n'; } if (locale == TimeLocale::LOCAL) { stream &lt;&lt; "LOCAL: " &lt;&lt; std::put_time(std::localtime(&amp;t), "%c, %Z") &lt;&lt; '\n'; } if (locale == TimeLocale::BOTH) { stream &lt;&lt; "UTC: " &lt;&lt; std::put_time(std::gmtime(&amp;t), "%c, %Z") &lt;&lt; '\n' &lt;&lt; "LOCAL: " &lt;&lt; std::put_time(std::localtime(&amp;t), "%c, %Z") &lt;&lt; '\n'; } } #pragma warning( pop ) } // namespace util </code></pre> <h2>main.cpp</h2> <pre><code>#include "DateAndTime.h" #include &lt;ctime&gt; #include &lt;exception&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; using namespace util; int main() { try { std::stringstream stream1; currentDateAndTime(stream1, TimeLocale::GMT); std::cout &lt;&lt; stream1.str() &lt;&lt; '\n'; std::stringstream stream2; currentDateAndTime(stream2, TimeLocale::LOCAL); std::cout &lt;&lt; stream2.str() &lt;&lt; '\n'; std::stringstream stream3; currentDateAndTime(stream3, TimeLocale::BOTH); std::cout &lt;&lt; stream3.str() &lt;&lt; '\n'; std::stringstream stream4; currentDateAndTime(stream4, TimeLocale::GMT | TimeLocale::LOCAL); std::cout &lt;&lt; stream4.str() &lt;&lt; '\n'; } catch ( const std::exception&amp; e ) { std::cout &lt;&lt; "Exception Thrown: " &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } catch (...) { std::cout &lt;&lt; __FUNCTION__ &lt;&lt; " Caught Unknown Exception" &lt;&lt; std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <p>And the above code would generate a nicely formatted possible result:</p> <pre><code>UTC: 02/20/19 05:44:38, Eastern Standard Time Local: 02/20/19 00:44:38, Eastern Standard Time UTC: 02/20/19 05:44:38, Eastern Standard Time Local: 02/20/19 00:44:38, Eastern Standard Time UTC: 02/20/19 05:44:38, Eastern Standard Time Local: 02/20/19 00:44:38, Eastern Standard Time </code></pre> <p>Currently as it stands, this is acceptable for me considering my current situation. I'm not quite able to use the new features that can be found in <code>&lt;std::chrono&gt;</code> for its <code>calendar</code> resources, as I'm stuck with Visual Studio 2017 and C++17. </p> <hr> <p>There are a few things that I would like to know about the above function and its functionality.</p> <ul> <li>Other than using library functions that have been marked deprecated such as <code>std::gmtime</code> and <code>std::localtime</code> and having to suppress the compiler warning, is the overall above code considered good design, and is it considered readable and reliable?</li> <li>Is there anything that could be done to improve this: Are there any corner case errors that I may have missed, can this be made more efficient.</li> <li>Would this above code be considered portable, cross-platform? </li> </ul> <p>The last thing I would like to know are there any other standard ways to achieve this through the standard library without using platform specific code? </p> <hr> <p>I wouldn't mind using <code>chrono</code> but its newer features are not quite yet available; and I don't want to use any third party libraries like <code>boost</code> for example. </p> <p>I am aware of the fact that different operating systems as well as different hardware (processors) retrieve and calculate the current time differently, and that different regions have different types of calendars and time zone formats. </p> <p>Above are some of the reasons that made it a formidable challenge to retrieve the current date and time using only standard C++. I might just have to wait for the release of Visual Studio 2019 for C++20 to arrive. </p> <p>I'm looking forward to any and all feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:30:10.260", "Id": "413673", "Score": "0", "body": "What's \"deprecated\" about the `<ctime>` functions? I don't think there's any proposal to remove them in the C++20 timeframe, or even beyond." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:25:20.567", "Id": "413676", "Score": "0", "body": "@TobySpeight With my current IDE & Compiler Visual Studio 2017 using `c++ latest draft standard` which should be C++17; if I remove the `#pragma warning(push) #pragma warning(disable : 4996) #pragma warning(pop)` away from the `currentDateAndTime(...)` function my compiler yells at me that `std::gmtime` and `std::localtime` are not considered safe and that they have been marked for deprecation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:27:31.050", "Id": "413677", "Score": "0", "body": "@TobySpeight I'm thinking they might be marked as deprecated because of the `std::chrono` `calendar` features that will be added to the standard come C++20 in Visual Studio 2019 and or other compilers that will support C++20 when it is officially released." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:39:39.793", "Id": "413678", "Score": "0", "body": "Sounds like one vendor's opinion, rather than a Standard statement. Perhaps they're suggesting that you'd want `gmtime_r()` and the like, or their platform's equivalent. But if you're writing a single-threaded program, there's no need to panic!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:43:01.523", "Id": "413679", "Score": "0", "body": "@TobySpeight That's quite possible, but I don't have a copy of the full standard available, so it's quite hard for me to look through it to find out what I need to know. Besides that: even though `Microsoft` does give a plethora of information, they also lack a lot of details and aren't very forthcoming in their examples and descriptions, yes they do have a lot of vital information, but many times it can be quite hard to find, or is incomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T13:01:04.473", "Id": "413680", "Score": "1", "body": "@FrancisCugler In case you don't know, you can look at [this](http://eel.is/c++draft) for an up-to-date C++ standard draft if you don't own a copy of the standard. Should suffice for most cases :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:02:50.487", "Id": "213872", "Score": "2", "Tags": [ "c++", "datetime", "c++17", "portability" ], "Title": "A portable cross platform C++17 method to retrieve the current date and time" }
213872
<p><a href="https://github.com/koutoftimer/sqrc/blob/91eedb8a46f8f34e3a67b0ff53077064b38002a2/c%2B%2B/sqrc-qt/qsquarelayout.h" rel="nofollow noreferrer"><code>qsquarelayout.h</code></a></p> <pre><code>#ifndef QSQUARELAYOUT_H #define QSQUARELAYOUT_H #include &lt;QLayout&gt; #include &lt;QLayoutItem&gt; class QVSquareLayout : public QLayout { Q_OBJECT public: QVSquareLayout(QWidget* parent=nullptr); ~QVSquareLayout(); // QLayoutItem interface public: virtual QSize sizeHint() const; virtual void setGeometry(const QRect &amp;rect); // QLayout interface public: virtual void addItem(QLayoutItem* item); virtual QLayoutItem* itemAt(int index) const; virtual QLayoutItem* takeAt(int index); virtual int count() const; virtual QSize minimumSize() const; private: QList&lt;QLayoutItem *&gt; _items; }; #endif // QSQUARELAYOUT_H </code></pre> <p><a href="https://github.com/koutoftimer/sqrc/blob/91eedb8a46f8f34e3a67b0ff53077064b38002a2/c%2B%2B/sqrc-qt/qsquarelayout.cpp" rel="nofollow noreferrer"><code>qsquarelayout.cpp</code></a></p> <pre><code>#include "qsquarelayout.h" QVSquareLayout::QVSquareLayout(QWidget* parent) : QLayout (parent) { } QVSquareLayout::~QVSquareLayout() {} void QVSquareLayout::addItem(QLayoutItem* item) { _items.append(item); } QLayoutItem* QVSquareLayout::itemAt(int index) const { if (index &lt; 0 || index &gt;= count()) return nullptr; return _items.at(index); } QLayoutItem* QVSquareLayout::takeAt(int index) { if (index &lt; 0 || index &gt;= count()) return nullptr; return _items.takeAt(index); } int QVSquareLayout::count() const { return _items.count(); } QSize QVSquareLayout::minimumSize() const { return QSize(10, 10); } QSize QVSquareLayout::sizeHint() const { int width = 0, height = 0, n = count(); foreach (QLayoutItem* item, _items) { QSize size = item-&gt;sizeHint(); int min = qMin(size.width(), size.height()); width = qMax(width, min); height += min; } return {width, height + n * spacing()}; } void QVSquareLayout::setGeometry(const QRect &amp;rect) { int n = count(); if (n &lt; 1 || rect == this-&gt;geometry()) return; QLayout::setGeometry(rect); int left, right, top, bottom; getContentsMargins(&amp;left, &amp;top, &amp;right, &amp;bottom); int min = qMin(rect.width(), rect.height() / n); QPoint baseLine{rect.width()/2 - min/2 + left, top}; QSize square{min, min}; foreach (QLayoutItem *item, _items) { item-&gt;setGeometry(QRect{baseLine, square}); baseLine.ry() += min; } } </code></pre> <p>Main idea is: when you need something to take square shape - just put it in this layout.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:20:34.813", "Id": "213873", "Score": "2", "Tags": [ "c++", "c++11", "qt" ], "Title": "QVSquareLayout implementation for Qt that makes all internal items to be squared" }
213873
<h1>Preface</h1> <p>At some point I was tired of writing &amp; supporting <code>__repr__</code> methods, so I've decided to write it once and reuse everywhere in my classes.</p> <p>Since I'm trying to write classes as simple as possible, most of them ends in something like</p> <pre><code>class MyClass: def __init__(self, param, other_param, ...): self.param = param self.other_param = other_param ... </code></pre> <p>i.e. initializer parameters names corresponds to fields names, so we can get initializer arguments by simply <code>getattr</code>'ing corresponding fields.</p> <p>Main ideas are:</p> <ol> <li><p>I want to have informative string which includes parameters involved in instance creation. For simple cases it should be possible to copy string &amp; paste in some place (e.g. REPL session) and have similar object definition with as less work as possible. This helps a lot during debugging sessions, logging, especially in failed test cases with randomly generated data.</p> <p>Great examples are <code>Counter</code> &amp; <code>OrderedDict</code> from <code>collections</code> standard library:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter(range(2)) Counter({0: 1, 1: 1}) &gt;&gt;&gt; Counter(range(2)) == Counter({0: 1, 1: 1}) True &gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; OrderedDict.fromkeys(range(2)) OrderedDict([(0, None), (1, None)]) &gt;&gt;&gt; OrderedDict.fromkeys(range(2)) == OrderedDict([(0, None), (1, None)]) True </code></pre></li> <li><p>Once signature change, <code>__repr__</code> should handle this automatically for simple cases like renaming/removing/changing order of parameters.</p></li> </ol> <h1>Attempt</h1> <p><em>Note</em>: following code requires Python3.5+ due to <code>yield from</code> statement</p> <pre><code>import inspect from collections import (OrderedDict, abc) from typing import (Any, Callable, Iterable, TypeVar, Union) Domain = TypeVar('Domain') Range = TypeVar('Range') Map = Callable[[Domain], Range] Constructor = Callable[..., Domain] Initializer = Callable[..., None] def generate_repr(constructor_or_initializer: Union[Constructor, Initializer], *, field_seeker: Callable[[Domain, str], Any] = getattr ) -&gt; Map[Domain, str]: signature = inspect.signature(constructor_or_initializer) parameters = OrderedDict(signature.parameters) # remove `self` parameters.popitem(0) to_positional_argument_string = repr to_keyword_argument_string = '{}={!r}'.format def __repr__(self: Domain) -&gt; str: return (type(self).__qualname__ + '(' + ', '.join(to_arguments_strings(self)) + ')') def to_arguments_strings(object_: Domain) -&gt; Iterable[str]: for parameter_name, parameter in parameters.items(): field = field_seeker(object_, parameter_name) if parameter.kind == inspect._VAR_POSITIONAL: if isinstance(field, abc.Iterator): yield '...' else: yield from map(to_positional_argument_string, field) elif parameter.kind == inspect._VAR_KEYWORD: yield from map(to_keyword_argument_string, field.keys(), field.values()) elif parameter.kind in {inspect._POSITIONAL_ONLY, inspect._POSITIONAL_OR_KEYWORD}: yield to_positional_argument_string(field) else: yield to_keyword_argument_string(parameter_name, field) return __repr__ </code></pre> <h1>Test</h1> <p>Let's define our class like</p> <pre><code>class A: def __init__(self, positional, *variadic_positional, keyword_only, **variadic_keyword): self.positional = positional self.variadic_positional = variadic_positional self.keyword_only = keyword_only self.variadic_keyword = variadic_keyword __repr__ = generate_repr(__init__) </code></pre> <p>After that</p> <pre><code>&gt;&gt;&gt; A(1, 2, 3, keyword_only='some', a={'sample': 42}, b={1, 2}) A(1, 2, 3, keyword_only='some', b={1, 2}, a={'sample': 42}) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:57:41.373", "Id": "413779", "Score": "1", "body": "[`@dataclass`](https://docs.python.org/3/library/dataclasses.html) does this for you. It has even been [backported to 3.6](https://pypi.org/project/dataclasses/)" } ]
[ { "body": "<p>Honestly it looks like most of your code can't be simplified. However I found:</p>\n\n<ol start=\"2\">\n<li><code>to_positional_argument_string</code> is a mouth full, and people would understand your code easier if you just use <code>repr</code>.</li>\n<li><code>to_keyword_argument_string</code> is another mouth full and so you could call it <code>kw_repr</code>.</li>\n<li>You may want to add a comment explaining what <code>isinstance(field, abc.Iterator)</code> is for. This is because at first it confused me.</li>\n<li>[Controversial] You can change your code so that you don't need to be passed <code>constructor_or_initializer</code>. To do this you'd create <code>parameters</code> when <code>__repr__</code> is first used.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:30:17.547", "Id": "413703", "Score": "0", "body": "about `self`: this is incorrect, because for `__new__` (which can be used for immutable types) first parameter is `cls`, not `self`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:30:56.223", "Id": "413704", "Score": "0", "body": "about \"major unusable bug\": this can be simply handled by passing custom `field_seeker`, no need in extra mapping parameter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:32:57.357", "Id": "413705", "Score": "0", "body": "@AzatIbrakov It can actually be anything you want it to be, but yes you're correct in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:35:53.413", "Id": "413706", "Score": "0", "body": "@AzatIbrakov Ah yes it can. That would make `field_seeker` quite unsightly imo." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:22:09.013", "Id": "213892", "ParentId": "213875", "Score": "1" } }, { "body": "<p>I don't know about you but I prefer decorators. I have two solutions:</p>\n\n<ol>\n<li>for any immutable.</li>\n<li>(similar to yours except there is is no <code>yield from</code> or other wizardry :o) for any objects that respect your convention:</li>\n</ol>\n\n<pre><code>def __init__(self, &lt;args&gt;): self.&lt;args&gt; = &lt;args&gt;\n</code></pre>\n\n<p>The thing is (in my mind at least), that if you make a module, we don't care how complicated it is on the inside, but what matters is how easy it is to use it. Which is why I prefer decorators, they are non-intrusive by nature.</p>\n\n<p><strong>custom_module1.py:</strong> <em>(for any immutable)</em></p>\n\n<pre><code>def repr_maker(cls):\n class Representer(cls):\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n\n def __repr__(self):\n return cls.__name__ + '(' + ', '.join(\n [repr(i) for i in self._args]\n + [i + '=' + repr(j) for i, j in self._kwargs.items()]\n ) + ')'\n return Representer\n</code></pre>\n\n<p><strong>custom_module2.py:</strong> <em>(for any object that respect your convention)</em></p>\n\n<pre><code>def repr_maker(cls):\n def represent(self):\n params = list(inspect.signature(cls.__init__).parameters.items())\n return cls.__name__ + '(' + ', '.join(\n [repr(getattr(self, name))\n for name, param in params\n if (param.kind.name == 'POSITIONAL_OR_KEYWORD'\n and name != 'self')]\n + [', '.join(repr(value) for value in getattr(self, name))\n for name, param in params\n if param.kind.name == 'VAR_POSITIONAL']\n + [name + '=' + repr(getattr(self, name))\n for name, param in params\n if param.kind.name == 'KEYWORD_ONLY']\n + [', '.join(kw + '=' + repr(value)\n for kw, value in getattr(self, name).items())\n for name, param in params\n if param.kind.name == 'VAR_KEYWORD']\n ) + ')'\n cls.__repr__ = represent\n return cls\n</code></pre>\n\n<p><strong>my_program.py</strong></p>\n\n<pre><code>from custom_module import repr_maker\n\n@repr_maker\nclass A:\n def __init__(self, positional, *variadic_positional, keyword_only,\n **variadic_keyword):\n self.positional = positional\n self.variadic_positional = variadic_positional\n self.keyword_only = keyword_only\n self.variadic_keyword = variadic_keyword\n\n\nprint(repr(A(1, 2, 3, 4, 5, keyword_only=10, babar=\"le plus beau des éléphants\")))\n# A(1, 2, 3, 4, 5, keyword_only=10, babar='le plus beau des éléphants')\n</code></pre>\n\n<p>It is clean, reusable and does not pollute the actual code with extra stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:24:12.590", "Id": "413740", "Score": "1", "body": "[As pointed out in the comments to my answer](https://codereview.stackexchange.com/q/213875#comment413703_213892) this is intended to work with `__new__` too. Yours, currently, only works with `__init__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T20:02:34.980", "Id": "413761", "Score": "0", "body": "I am not familiar with `__new__` but it seems to me that it would be the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T20:31:24.123", "Id": "413764", "Score": "0", "body": "I edited my function, this looks like the simplest solution, you could also pass an argument to the decorator but then you have to nest functions even more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T20:39:40.960", "Id": "413765", "Score": "0", "body": "Just to note `__new__` can be created without the `args` and `kwargs` parameters. And still be the intended target. Infact, as pointed out in `A` those are just standard names, which can be replaced with anything. I'd also like to point out, that this deviates quite a bit from the question in that there is no `field_seeker`. If you look at my edits you'll see it's a rather _useful_ aspect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T21:02:46.833", "Id": "413766", "Score": "1", "body": "Yes, 'args' and 'kwargs' are the default, meaning that the only way it has changed is if you overload `__new__`. I will agree this is ugly, I will revert it and let's let leave this answer there. I stay convinced that decorators are the way to go here even if my particular implementation didn't meet your needs." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:45:54.430", "Id": "213893", "ParentId": "213875", "Score": "0" } }, { "body": "<blockquote>\n <p>Since I'm trying to write classes as simple as possible, most of them ends in something like [...] initializer parameters names corresponds to fields names, so we can get initializer arguments by simply getattr'ing corresponding fields.</p>\n</blockquote>\n\n<p>This feels exactly like what <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\"><code>dataclasses</code></a> were added for. The advantage for your use case is that support for <code>__repr__</code> is built-in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T12:44:07.197", "Id": "413966", "Score": "0", "body": "there is no `dataclasses` module in Python3.5 (and can't be due to [variable annotations syntax support](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep526)), which is my main option now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T12:53:01.613", "Id": "413973", "Score": "0", "body": "@AzatIbrakov Since you mentionned Python 3.5+, I thought I’d give it a try. Didn't know it was 3.5 exactly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T12:07:22.017", "Id": "214030", "ParentId": "213875", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T11:31:29.930", "Id": "213875", "Score": "11", "Tags": [ "python", "python-3.x", "formatting", "reflection", "meta-programming" ], "Title": "Simple generic auto __repr__" }
213875
<p>This is a C++17 <code>is_integral</code> trait implementation.</p> <p>Most implementations exhaust all integral types: </p> <ul> <li><code>bool</code></li> <li><code>char</code>, <code>char16_t</code>, <code>char32_t</code>, <code>wchar_t</code></li> <li><code>[unsigned] short</code></li> <li><code>[unsigned] [long [long]] int</code></li> </ul> <p>However, it is possible that the implementation defines some <a href="http://eel.is/c++draft/basic.fundamental#1" rel="nofollow noreferrer"><em>extended signed integer types</em></a> and <a href="http://eel.is/c++draft/basic.fundamental#2" rel="nofollow noreferrer"><em>extended unsigned integer types</em></a>. One workaround is to exhaust all the implementations using <code>#ifdef</code>s, but this workaround is not theoretically (in the language lawyer's point of view) portable. For example, if Mickey Mouse just rolls out a brand-new standard-conforming extended integer type, such workarounds fail.</p> <p>I theorized that for any type <code>T</code>, <code>is_integral&lt;T&gt;::value</code> is <code>true</code> if and only if it is convertible to <code>std::intmax_t</code> or <code>std::uintmax_t</code> via a <strong>non-narrowing</strong> <em>standard conversion sequence</em>. I tried to deploy this fact, enforcing the two restrictions respectively, by:</p> <ul> <li><p>using the so-called "uniform initialization" syntax (formally <em>list-initialization</em>) to prevent narrowing conversions; and</p></li> <li><p>using a dummy class (which I call a <em>generator</em> class) with a conversion operator to prevent user-defined conversion sequences.</p></li> </ul> <p>I tested with the cases of standard integral types (expecting true,) standard floating point types (expecting false,) user-defined types convertible to some standard integral type (expecting false.) <strong>All tests passed.</strong></p> <p>Here is my code, within 40 lines.</p> <pre><code>// C++17 is_integral implementation // which handles extended integer types // in a portable way // (without resorting to #ifdef chains) #include &lt;cinttypes&gt; // for std::intmax_t, std::uintmax_t #include &lt;type_traits&gt; // for std::is_same, std::bool_constant // can be trivially defined manually, just lazy namespace my_std { namespace detail { // Generator type to bypass user-defined conversions template &lt;typename T&gt; struct Generator { operator T(); }; // helper type to designate substitution failure struct Failed {}; // check functions (exploit SFINAE) // uses brace syntax to prevent narrowing conversions template &lt;typename T&gt; auto check_signed(int) -&gt; decltype(std::intmax_t{Generator&lt;T&gt;{}}); template &lt;typename T&gt; auto check_signed(...) -&gt; Failed; template &lt;typename T&gt; auto check_unsigned(int) -&gt; decltype(std::uintmax_t{Generator&lt;T&gt;{}}); template &lt;typename T&gt; auto check_unsigned(...) -&gt; Failed; // function invoker trait template &lt;typename T&gt; struct Int_trait { static constexpr bool is_signed_int = !std::is_same_v&lt; Failed, decltype(check_signed&lt;T&gt;(0)) &gt;; static constexpr bool is_unsigned_int = !std::is_same_v&lt; Failed, decltype(check_unsigned&lt;T&gt;(0)) &gt;; static constexpr bool is_int = is_signed_int || is_unsigned_int; }; } // "the" trait template &lt;typename T&gt; struct is_integral :std::bool_constant&lt;detail::Int_trait&lt;T&gt;::is_int&gt; { }; } </code></pre> <p>Any criticism or suggestion is highly appreciated!</p> <p><sub>&lt;joke&gt;The absolute best implementation with maximum portability and simplicity and clarity that is guaranteed to work on all machines is:</sub></p> <pre><code>#include &lt;type_traits&gt; namespace my_std { template &lt;typename T&gt; struct is_integral :std::is_integral&lt;T&gt; { }; } </code></pre> <p><sup>&lt;/joke&gt;</sup></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:43:23.873", "Id": "413724", "Score": "3", "body": "I like your joke! More seriously, why would you \"manually [replace] `intmax_t`s with `__int128_t`\"? Doesn't it defeat you initial purpose to provide a platform-independent implementation? And doesn't it prove that another plat-form could as well provide a similar extension that your code wouldn't take into account? Besides, to comply with the standard, `std::is_integral_v<__int128_t>` should be false, because it is neither a standard integer type nor an extended integer type, but a language extension." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:32:16.323", "Id": "413803", "Score": "0", "body": "@papagaga Well... You are very helpful. I explained it too badly... The problem is, I am unable to find a single accessible implementation with a real extended integer type. And `__int128_t` was the closest I could find, although it is still not a real one. As a workaround, I faked `intmax_t` to test it with a (fake) one... I was appreciate if there is actually one I can test on ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T19:32:49.007", "Id": "416931", "Score": "0", "body": "\"I found that for any type `T`, `is_integral<T>::value` is true if and only if: it is convertible to `std::intmax_t` or `std::uintmax_t` via a non-narrowing standard conversion sequence.\" — This is true for the _standard_ integral types, but as you yourself realized, it's not true for the implementation-defined _extended_ integral types. For the situation with `__int128_t`, see [Is `__int128` integral?](https://quuxplusone.github.io/blog/2019/02/28/is-int128-integral/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T00:58:42.120", "Id": "416965", "Score": "0", "body": "@Quuxplusone I know `__int128_t` is not an integral type at all. Just have no nondirty way to test... I will delete that part anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T01:05:51.670", "Id": "416966", "Score": "0", "body": "\"I know `__int128_t` is not an integral type at all.\" — No, you *think* `__int128_t` is not an integral type at all. Both libc++ (in all modes) and libstdc++ (in `-std=gnu++XX` mode) disagree with you, though. See the blog post [Is `__int128` integral?](https://quuxplusone.github.io/blog/2019/02/28/is-int128-integral/) for more details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T01:07:27.343", "Id": "416967", "Score": "0", "body": "@Quuxplusone Sorry, I meant \"I know the way I tested `__int128_t` (with gcc in an ordinary mode) is one in which `__int128_t` is not an integral type at all.\" I read you blog post and it seems to suggest that I can do this test in clang or in `-std=gnu++XX` gcc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T01:13:00.060", "Id": "416968", "Score": "0", "body": "But [it says `false`.](https://wandbox.org/permlink/tu22ltmjrrVi7fIX)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T01:14:36.000", "Id": "416969", "Score": "0", "body": "Here's side-by-side comparison of your `my_std::is_integral<__int128>` with `std::is_integral<__int128>`. https://godbolt.org/z/Ka9F6V I **really, really, highly recommend** just reading the blog post! It goes into great detail on what happens and why it happens." } ]
[ { "body": "<blockquote>\n <p>I tested with the cases of standard integral types (expecting true,) standard floating point types (expecting false,) user-defined types convertible to some standard integral type (expecting false.) <strong>All tests passed.</strong></p>\n</blockquote>\n\n<p>You should have tested with all the other kinds of types in C++. Reference types, pointer types, enum types, <code>nullptr_t</code>, <code>void</code>, pointer-to-member types, etc. etc.</p>\n\n<p>Your <code>is_integral</code> incorrectly reports that <code>int&amp;</code> is an integral type. (<a href=\"https://godbolt.org/z/PUcV72\" rel=\"nofollow noreferrer\">Godbolt.</a>)</p>\n\n<p>It's not a hard fix, of course; but the code-review feedback is \"Write more tests.\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-28T07:50:30.253", "Id": "469855", "Score": "0", "body": "You're right. I will need more tests when writing template stuff. Or simply stop reinventing the wheel ... :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-28T04:35:11.700", "Id": "239544", "ParentId": "213876", "Score": "2" } } ]
{ "AcceptedAnswerId": "239544", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:10:14.697", "Id": "213876", "Score": "9", "Tags": [ "c++", "reinventing-the-wheel", "template-meta-programming", "c++17", "sfinae" ], "Title": "C++17 is_integral trait implementation" }
213876
<p>For the moment I'm executing my code as follows:</p> <pre><code>foreach (int data in dataList) { PreProcess(data); } foreach (int data in dataList) { Process(data); } </code></pre> <p>First I have to loop over some data (from a list) and to do some pre-processing after which then I do have to loop again over the <strong>same</strong> data list and do some processing, but those loops have to be run one after another, and <strong>cannot</strong> be merged as follows...</p> <pre><code>foreach (int data in dataList) { PreProcess(data); Process(data); // Cannot be run in the same loop with PreProcess(data); } </code></pre> <p>...because <code>PreProcess(data)</code> and <code>Process(data)</code> are logging a lot of information which could be interlaced in case both are looping together.</p> <hr> <p>The only alternative I've found will be using Linq, but still has the same duplicate <code>ForEach</code>:</p> <pre><code>dataList.ForEach(data =&gt; { PreProcess(data); }); dataList.ForEach(data =&gt; { Process(data); }); </code></pre> <hr> <p>Is there any way to rewrite this in order to remove the redundancy for two loops with same range, but still looping sequentially first over <code>PreProcess(data)</code> and <code>Process(data)</code> afterwards?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:08:31.767", "Id": "413686", "Score": "0", "body": "Why don't you like using two loops? If there is no other way then there isn't. To me it looks more like an xy-problem where you are trying to _optimize_ the looping instead of telling us what the real problem is, this is, why you cannot process your data at the same time with a single loop. Without this information this question severely lacks context and should be closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:10:39.807", "Id": "413687", "Score": "0", "body": "Few words about codereview's community: if you have questions like \"how to do something?\" better do not ask here, only working solutions are discussed here. You can simply rephrase your post in order to avoid such questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:33:14.580", "Id": "413691", "Score": "0", "body": "@t3chb0t: this is an overly simplified example of my real production code. I do not know how to explain or abstract it better, but I'm just using very often identical loops (more than 2) and wanted to know if there is a better approach than the normal one, and have less repeating foreach declarations. I do not see any other \"core\"-problem in my context than redundancy and the wish to redefine loop range in one place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:42:54.990", "Id": "413694", "Score": "0", "body": "@t3chb0t: sorry I've did not managed to edit the comment in time and adding the information you requested (also added it in the question): PreProcess(data) and Process(data) are logging a lot of information which could be interlaced in case both are looping together." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:45:27.897", "Id": "413695", "Score": "0", "body": "@outoftime: thanks for the feedback and I will rephrase it accordingly. Do you think that Stackoverflow would have been a better place for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:50:49.600", "Id": "413700", "Score": "0", "body": "I think SO would as bad as any other community because you are not telling us anything about the real problem. You don't want to _optimize_ any of these loops because it doesn't make any sense without knowing anything about what they are for and if you are using them for logging then most likely is your logging logic that needs to be improved." } ]
[ { "body": "<h1>First Class Collection</h1>\n\n<p>The First Class Collection is an idea of the <a href=\"https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf\" rel=\"nofollow noreferrer\">Object Calisthenics</a>.</p>\n\n<blockquote>\n <p>Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home. </p>\n</blockquote>\n\n<p>We can wrap <code>dataList</code> into its own class</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class DataList \n{\n\n private List&lt;int&gt; list;\n\n // ...\n}\n</code></pre>\n\n<h1><a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a></h1>\n\n<blockquote>\n <p>A method accesses the data of another object more than its own data.</p>\n</blockquote>\n\n<p>Since the collection <code>dataList</code> could be wrapped into its own class and gets modified by <code>PreProcess</code> and <code>Process</code> you have an Feature Envy.</p>\n\n<p>We could put the methods <code>PreProcess</code> and <code>Process</code> into the class <code>DataList</code></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class DataList \n{\n\n private List&lt;Data&gt; list;\n\n public void PreProcess() \n {\n /* ... */ \n } \n\n public void Process() \n {\n /* ... */ \n } \n}\n</code></pre>\n\n<p>Now when you call it from the outside you simple call the methods</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>dataList.PreProcess();\ndataList.Process();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:52:17.137", "Id": "213881", "ParentId": "213877", "Score": "1" } }, { "body": "<p>You could also define something like</p>\n\n<pre><code>private void MyLoop&lt;T&gt;(Action&lt;T&gt; action, IEnumerable&lt;T&gt; dataList) \n{\n foreach (var data in dataList)\n {\n action(data);\n }\n}\n</code></pre>\n\n<p>and use it</p>\n\n<pre><code>MyLoop(Process, dataList);\n</code></pre>\n\n<p>or using Action</p>\n\n<pre><code>Action&lt;Action&lt;int&gt;&gt; myLoop= action =&gt;\n{\n foreach (var data in dataList)\n {\n action(data);\n }\n};\n</code></pre>\n\n<p>and use it like this</p>\n\n<pre><code>myLoop(Process);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:58:06.583", "Id": "213883", "ParentId": "213877", "Score": "2" } }, { "body": "<pre class=\"lang-cs prettyprint-override\"><code>interface IActionStrategy\n{\n void applyTo(RequiredDataType data);\n}\n// ...\nforeach (IActionStrategy strategy in strategyQueue)\n foreach (RequiredDataType data in dataList)\n strategy.applyTo(data);\n</code></pre>\n\n<p>Each strategy have to implement common interface in order to do it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:07:51.270", "Id": "213888", "ParentId": "213877", "Score": "-1" } } ]
{ "AcceptedAnswerId": "213883", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:13:38.247", "Id": "213877", "Score": "1", "Tags": [ "c#" ], "Title": "Alternative for two sequentially executed loops with identical ranges" }
213877
<p>I was playing arround with some CSS and ended up in making some 3D hover icons with font awesome.</p> <p>I wanted to ask for some feedback on my CSS: Best-practices, any other comments, maybe bad things that you should not do...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>article { position: relative; left: 50%; transform: translateX(-50%); min-height: 100%; } article h2{ text-transform: uppercase; } .intro-contact { height: 100vh; display: flex; align-items: center; justify-content: center; } .ul_icons { position: relative; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; margin-top: 30px; margin-bottom: 20px; } .ul_icons .li_icons { position: relative; list-style-type: none; width: 60px; height: 60px; margin: 0 30px; transform: rotate(-30deg) skew(25deg); background: #ccc; } .ul_icons .li_icons span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #000; transition: 0.5s; display: flex !important; align-items: center; justify-content: center; color: #fff; font-size: 30px !important; } .ul_icons .li_icons:hover span:nth-child(5) { transform: translate(40px, -40px); opacity: 1; } .ul_icons .li_icons:hover span:nth-child(4) { transform: translate(30px, -30px); opacity: 0.8; } .ul_icons .li_icons:hover span:nth-child(3) { transform: translate(20px, -20px); opacity: 0.6; } .ul_icons .li_icons:hover span:nth-child(2) { transform: translate(10px, -10px); opacity: 0.4; } .ul_icons .li_icons:hover span:nth-child(1) { transform: translate(0, 0); opacity: 0.2; } .ul_icons .li_icons:nth-child(1) span { background: #3b5999; } .ul_icons .li_icons:nth-child(2) span { background: #87CEEB; } .ul_icons .li_icons:nth-child(3) span { background: #E3D094; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/&gt; &lt;section id="main" class="intro_contact no-mobile"&gt; &lt;article&gt; &lt;h2&gt;Contact&lt;/h2&gt; &lt;ul class="ul_icons"&gt; &lt;li class="li_icons"&gt; &lt;a href="#mail"&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span class="fa fa-envelope" aria-hidden="true"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="li_icons"&gt; &lt;a href="#phone"&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span class="fa fa-phone" aria-hidden="true"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="li_icons"&gt; &lt;a href="#personal"&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span class="fa fa-user" aria-hidden="true"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:44:19.457", "Id": "213880", "Score": "1", "Tags": [ "css" ], "Title": "CSS 3D contact icons" }
213880
<p>I wrote a function to implement a generalised version of binary search that can find the minimum or maximum index in a given sorted list that satisfies a provided predicate. </p> <p><strong>My Code</strong> </p> <pre><code>def xbinsearch(pred, lst, type = "min", default = None): """ * Finds the minimum or maximum index of a sorted list such that the value at that index satisfies a given predicate. * Params: * `pred`: Predicate function. * Params: * `idx`: The index of the value to be tested. * `lst`: The list to search for said value in. * Return: An ordered pair of the form `(x, y)`. * `x`: Boolean indicates whether or not `lst[idx]` satisfies the predicate. * `y`: `-1`, `1` or `None`. * `-1` indicates that if `lst[idx]` does not satisfy the predicate, then all values below `lst[idx]` also do not satisfy the predicate. * `1` indicates that if `lst[idx]` does satisfy the predicate, then all values above `lst[idx]` also do not satisfy the predicate. * `None` is given with `True` for the first index of the ordered pair. * It is used to determine which "half" to discard in the binary search. """ low, hi, best = 0, len(lst)-1, default while low &lt;= hi: mid = (low+hi)//2 p = pred(mid, lst) if p[0]: #The current element satisfies the given predicate. if type == "min": if best == default or lst[mid] &lt; lst[best]: best = mid hi = mid-1 elif type == "max": if best == default or lst[mid] &gt; lst[best]: best = mid low = mid+1 elif p[1] == 1: #For all `x` &gt; `lst[mid]` not `P(x)`. hi = mid - 1 elif p[1] == -1: #For all `x` &lt; `lst[mid]` not `P(x)`. low = mid + 1 return best </code></pre> <hr> <h2>Sample Use Case</h2> <p><strong>Problem</strong> <a href="https://www.codewars.com/kata/element-equals-its-index/train/python" rel="nofollow noreferrer">Element equals its index</a> </p> <blockquote> <p>Given a sorted array of distinct integers, write a function <code>index_equals_value</code> that returns the lowest index for which array[index] == index<code>.<br> Return</code>-1` if there is no such index.<br> Your algorithm should be very performant. </p> <p>[input] array of integers ( with <code>0</code>-based nonnegative indexing )<br> [output] integer </p> <h3>Examples:</h3> <pre><code>input: [-8,0,2,5] output: 2 # since array[2] == 2 input: [-1,0,3,6] output: -1 # since no index in array satisfies array[index] == index </code></pre> <h3>Random Tests Constraints:</h3> <p>Array length: 200 000 </p> <p>Amount of tests: 1 000 </p> <p>Time limit: 1.5 s </p> </blockquote> <p><strong>My Code</strong> </p> <pre><code>def identity(idx, lst): tpl, val = [None, None], lst[idx] tpl[0] = val == idx if val &lt; idx: tpl[1] = -1 elif val &gt; idx: tpl[1] = 1 return tuple(tpl) def xbinsearch(pred, lst, type = "min", default = None): low, hi, best = 0, len(lst)-1, default while low &lt;= hi: mid = (low+hi)//2 p = pred(mid, lst) if p[0]: #The current element satisfies the given predicate. if type == "min": if best == default or lst[mid] &lt; lst[best]: best = mid hi = mid-1 elif type == "max": if best == default or lst[mid] &gt; lst[best]: best = mid low = mid+1 elif p[1] == 1: #For all `x` &gt; `lst[mid]` not `P(x)`. hi = mid - 1 elif p[1] == -1: #For all `x` &lt; `lst[mid]` not `P(x)`. low = mid + 1 return best def index_equals_value(lst): return xbinsearch(identity, lst, default = -1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T17:26:53.257", "Id": "413728", "Score": "0", "body": "Could you give a use case for this code? What would the parameters be? I'm having a hard time comming up with a predicate function that fits this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:15:00.173", "Id": "413736", "Score": "0", "body": "(I hope the doc string is accurate with `Finds the minimum or maximum index` (*not* value as in the introductory sentence).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:39:26.440", "Id": "413827", "Score": "0", "body": "@greybeard I changed from value to index as I found the latter more useful, but forgot to update the question itself (as opposed to just the code)." } ]
[ { "body": "<p>You may be a little confused about how a binary search operates. Your doc comment seems to suggest you understand and my cursory look at your code didn't reveal any bugs (but then again, I didn't look too hard). But, this function doesn't really make logical sense.</p>\n\n<p>The purpose of a binary search is to find an item in <code>O(log(n))</code> time instead of doing a full scan of a linear datastructure (or at least scanning until you find the item, which worst case is <code>O(n)</code>). This of course requires the datastructure to already be sorted. Your comment indicates you understand this. But what you end up doing with <code>pred</code> makes it seem like you confused yourself.</p>\n\n<p>Why? Well if <code>pred</code> is not a constant time operation, then your binary search is no longer <code>O(log(n))</code> (I suspect this is the case, because instead of passing <code>lst[mid]</code> to <code>pred</code> you pass the entire <code>lst</code> and index <code>mid</code>). Let's say <code>pred</code> is <code>O(n)</code>. Now the total runtime of <code>xbinsearch</code> is <code>O(n*log(n))</code>, which is significantly worse. In this case, a linear search may be better.</p>\n\n<p>Now, let's just assume <code>pred</code> is a constant time function. Now the overall runtime remains <code>O(log(n))</code>, but the return value of <code>pred</code> still doesn't make sense. Why is this? Well, the list must already be sorted by some ordering. If <code>pred</code> is constant time, it can only make decisions about the value at <code>mid</code> (and maybe a few surrounding values), but it can't scan <code>lst</code> to make decisions. So this means there must be some sort of dependency between the return value of <code>pred</code> and the sort order of <code>lst</code>. If there wasn't, your search probably wouldn't work (if say <code>lst</code> was sorted by ascending value but <code>pred</code> negated the values before comparing them, it would throw out the wrong half of the list).</p>\n\n<p>So now we assume that <code>pred</code> is a constant time function that has some dependency on the sort order of <code>lst</code>. We've shown previously that if either of these doesn't hold, your algorithm is either inefficient or breaks. We now arrive at the last issue. <code>pred</code>'s comparison criteria must be monotone over the sorted list. That is just a fancy way of saying that when <code>lst</code> is sorted then <code>pred</code>'s comparison criteria must also be sorted. In which case, there isn't a purpose for <code>pred</code>, since the value of the item itself (which <code>lst</code> is sorted by this item value) is a proxy for the <code>pred</code> comparison criteria.</p>\n\n<p>If you didn't follow all of that, don't be too worried. The important point is that you're probably misusing a binary search here. If you want to find the smallest value satisfying a predicate in a list you can just do: <code>min(lst, key=pred)</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>people = [\n # (name, age)\n ('Doe Jane', 52),\n ('John Doe', 33),\n ('Jane Doe', 42),\n]\n\n# Min tuple from people by age\nyoungest_person = min(people, key=lambda p: p[1])\n</code></pre>\n\n<p>Note that with <code>namedtuple</code> this example becomes even more clear:</p>\n\n<pre><code>from collections import namedtuple\n\nPerson = namedtuple('Person', 'name age')\n\npeople = [\n # (name, age)\n Person('Doe Jane', 52),\n Person('John Doe', 33),\n Person('Jane Doe', 42),\n]\n\nyoungest_person = min(people, key=lambda p: p.age)\n</code></pre>\n\n<p>Now you may notice <code>people</code> is not sorted. You could pass in a sorted list though, but it doesn't make much sense to sort the list, because it's not like you can perform multiple of these operations. <code>min</code> of a list (that you don't modify) will always be the same. If you change <code>key</code> then you'd need to resort the list. If you wanted both the min and max, use <code>min</code> and <code>max</code>. If performance is of concern (which is unlikely), you could optimize this by having one function that scans over the entire list and keeps track of both the min and max values. If you want to modify the list, then you're probably better off using a heap, which remains sorted with inserts and removals.</p>\n\n<p>Some extraneous issues:</p>\n\n<p><code>default=None</code> isn't a very common pattern in Python. Sure you see it with <code>dict.get</code> (and less commonly with <code>iter</code>), but those are the two places where I can think of. These places have appropriate uses of allowing a default value. For your function a default value doesn't make much sense. Since it returns an index, what use would a \"default index\" be? I see two options:</p>\n\n<ol>\n<li><code>return None</code> (and only <code>None</code>). This simplifies the interface you provide. Allowing for a default value makes it hard for a user of your function to understand what's going on (it's just one more thing to wrap your head around). This way you can explain the function in a sentence: \"Returns the minimum or maximum index of the item satisfying a predicate in a sorted list, or None\"</li>\n<li>Raise an exception (say <code>ValueError</code>) if no items satisfy the predicate. This is a very common approach in Python: <code>dict</code>s raise <code>KeyError</code> if a key doesn't exist (instead of returning <code>None</code>), <code>list</code>s raise <code>IndexError</code> if an index is out of bounds (instead of returning <code>None</code>). This is probably the right choice for you, because a predicate not being satisfied by anything in the list provided is probably an exceptional case that needs to be handled differently (eg. if you were to return <code>None</code> you couldn't treat it like a number if you wanted to do indexing with it).</li>\n</ol>\n\n<p>Your use of string constants to indicate the mode (<code>type=\"min\"</code>) while common in numpy is a dangerous pattern IMO. You do no <code>assert type in ('min', 'max')</code>, so what if someone passes in <code>type=\"median\"</code>? What if they make a typo: <code>type=\"mIn\"</code>? Both of these appear to lead to behavior you don't want. Worst case (although your code doesn't appear to do this), this could cause an error inside your function. How frustrating would that be for a user of your function to see an error inside your function? This forces them to understand its internals to see if this is a bug in your function or a bug in their use of it. At the least, prefer an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>Enum</code></a> so that if they choose an invalid type they get a <code>AttributeError</code> (if they tried to do <code>type=SearchMode.PENULTIMATE</code>, for example).</p>\n\n<p>PEP8 your code. Your spacing needs work. Also wrap to 79 chars, it's really annoying to need to scroll right to read the docs. They're almost surely indented too far.</p>\n\n<p>Instead of doing <code>p[0]</code> and <code>p[1]</code>, consider tuple unpacking to give those values more descriptive names:</p>\n\n<pre><code>predicate_satisfied, direction = pred(mid, lst)\n</code></pre>\n\n<p>You should probably use required kwargs for <code>type</code> and <code>default</code>, otherwise, the function call site becomes unclear. Eg. is it <code>xbinsearch(my_pred, 'min', 1)</code> or <code>xbinsearch(my_pred, 1, 'min')</code>. Much clearer: <code>xbinsearch(my_pred, type='min', default=1)</code>:</p>\n\n<pre><code>def xbinsearch(pred, lst, *, type='min', default=None):\n # ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:38:12.743", "Id": "413804", "Score": "1", "body": "Nice answer, I'd just add a last note on `pred`'s return value: there is no need for it to be a couple, since the second element alone can be used to infer the first one (if `-1` or `1` it was false, otherwise it was true), so better return `-1`, `0`, or `1` as usual for a comparison function. Or [use `bisect` with a key function](https://code.activestate.com/recipes/577197-sortedcollection/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:43:12.543", "Id": "413829", "Score": "0", "body": "`pred` is constant time. I pass the entire list, because for the problem that made me design this generalisation of binary search the predicate was: `lst[idx] == idx`. `pred` needs to know at what index the element in the list occurs. It is generally a constant time function. I will add a sample use case to my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:54:45.847", "Id": "413832", "Score": "0", "body": "I have added the sample use case. I did not actually create the generalised binary search to solve that problem (I solved it first, then upon reflecting on the code I used to solve it, came up with the generalised version)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:47:52.303", "Id": "213924", "ParentId": "213882", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:52:38.013", "Id": "213882", "Score": "4", "Tags": [ "python", "performance", "beginner", "algorithm", "binary-search" ], "Title": "Generalisation of Binary Search" }
213882
<p>I implemented a console version of the classic snake game. I wanted it to be portable but some of the functions like setting console position and <code>_kbhit</code> weren't available on Non-Windows operating systems, thus as is, this code is Windows only but I tried to isolate the non-portable parts in <code>controls.h</code>. I would especially like comments about the object-oriented design.<br> Here's the code:</p> <h1>main.cpp</h1> <pre><code>#include "GamePlay.h" int main() { GamePlay gamePlay; gamePlay.play(); return 0; } </code></pre> <h1>Cell.h</h1> <pre><code>#ifndef SNAKE_CELL_H #define SNAKE_CELL_H #include &lt;iostream&gt; // Base class for snake cell, field cell and other cell types class Cell { public: // the type each cell holds and prints as its content using cell_content_type = char; explicit Cell(const cell_content_type&amp; = ' ', bool = false, bool prize_ = false); // an empty cell by default friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;os, const Cell&amp; cell); // if the cell helds something bool isOccupied() const { return occupied; } void setOccupid(bool o) { occupied = o; } bool get_prize() { return prize; } //pure virtual destructor to make this class abstract virtual ~Cell() = 0; protected: // whether or not the cell is holds something (part of // the snake/border) bool occupied; // if this cell is edible bool prize; // each cell prints this when draw method is called cell_content_type content; }; #endif // !SNAKE_CELL_H </code></pre> <h1>Cell.cpp</h1> <pre><code>#include "Cell.h" Cell::Cell(const cell_content_type&amp; content_, bool occupied_, bool prize_) : content(content_) , occupied(occupied_) , prize(prize_) { } Cell::~Cell() { } std::ostream &amp; operator&lt;&lt;(std::ostream &amp; os, const Cell &amp; cell) { os &lt;&lt; cell.content; return os; } </code></pre> <h1>Field.h</h1> <pre><code>#ifndef SNAKE_FIELD_H #define SNAKE_FIELD_H #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;memory&gt; #include "Cell.h" #include "Field_border_cell.h" class Field { public: // friends friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const Field&amp;); // havind Cell-based objects in this field using stored_type = Cell; // "matrix" for container using field_vector_type = std::vector&lt;std::shared_ptr&lt;stored_type&gt;&gt;; using field_container_type = std::vector&lt;field_vector_type&gt;; using size_type = field_container_type::size_type; // side-length of the square field static const size_type field_height = 20; static const size_type field_width = 20; Field(); Field(Field&amp;) = delete; // being / end auto begin() { return container.begin(); } auto end() { return container.end(); } auto begin() const { return container.begin(); } auto end() const { return container.end(); } auto cbegin() const { return begin(); } auto cend() const { return end(); } // swipe the cells within the container // intended to be used to move the snake void swipe_cells(size_type col1, size_type row1, size_type col2, size_type row2); void add_to_field(std::shared_ptr&lt;Cell&gt;, size_type, size_type); bool cellIsOccupied(size_type, size_type) const; field_vector_type&amp; operator[](size_type index) { return container[index]; } void reset_cell(size_type, size_type); private: field_container_type container; bool isBorder(size_type col, size_type row) { return (col == 0 || row == 0 || col == field_height - 1 || row == field_width - 1); } std::shared_ptr&lt;Field_cell&gt; default_field_cell; std::shared_ptr&lt;Field_border_cell&gt; default_field_border_cell; }; #endif // !SNAKE_FIELD_H </code></pre> <h1>Field.cpp</h1> <pre><code>#include &lt;utility&gt; #include &lt;iostream&gt; #include "Field.h" #include "Field_cell.h" #include "Field_border_cell.h" using std::size_t; using std::make_shared; using std::cout; using std::endl; Field::Field() : default_field_cell(make_shared&lt;Field_cell&gt;()) , default_field_border_cell(make_shared&lt;Field_border_cell&gt;()) { // fill in the container with empty `Field_cell`s for (size_t icol = 0; icol != field_height; ++icol) { container.push_back(field_vector_type()); for (size_t irow = 0; irow != field_width; ++irow) { // if on borders, add a border cell // else add a normal field_cell container.back().push_back( (isBorder(icol, irow) ? default_field_border_cell : default_field_cell) ); } } } // swipe the cells within the container // intended to be used to move the snake void Field::swipe_cells(size_type col1, size_type row1, size_type col2, size_type row2) { std::swap(container[col1][row1], container[col2][row2]); } void Field::add_to_field(std::shared_ptr&lt;Cell&gt; cell, size_type col , size_type row) { container[col][row] = cell; } bool Field::cellIsOccupied(size_type col, size_type row) const { return container[col][row]-&gt;isOccupied(); } void Field::reset_cell(size_type col, size_type row) { add_to_field(default_field_cell, col, row); } std::ostream &amp; operator&lt;&lt;(std::ostream &amp;os, const Field &amp;field) { // for each row for (const auto&amp; row : field) { // for each element in that row for (const auto&amp; elem : row) { cout &lt;&lt; *elem; } // break the line after each row cout &lt;&lt; '\n'; } // finish off drawing the board with // flushing the buffer cout &lt;&lt; endl; return os; } </code></pre> <h1>Field_border_cell.h</h1> <pre><code>#ifndef SNAKE_FIELD_BORDER_CELL_H #define SNAKE_FIELD_BORDER_CELL_H #include "Field_cell.h" // Same as a Field_cell // except that this is occupied // and prints an 'x' instead of ' ' class Field_border_cell : public Field_cell { public: Field_border_cell(); ~Field_border_cell() = default; }; #endif // !SNAKE_FIELD_BORDER_CELL_H </code></pre> <h1>Field_border_cell.cpp</h1> <pre><code>#include "Field_border_cell.h" Field_border_cell::Field_border_cell() : Field_cell('x', true) { } </code></pre> <h1>Field_cell.h</h1> <pre><code>#ifndef SNAKE_FIELD_CELL_H #define SNAKE_FIELD_CELL_H #include "Cell.h" class Field_cell : public Cell { public: // an explicitly empty cell explicit Field_cell(const cell_content_type&amp; = ' ', bool = false); ~Field_cell() override = default; protected: // nothing yet }; #endif // !SNAKE_FIELD_CELL_H </code></pre> <h1>Field_cell.cpp</h1> <pre><code>#include "Field_cell.h" Field_cell::Field_cell(const cell_content_type&amp; content_, bool occupied_) :Cell(content_, occupied_) { } </code></pre> <h1>GamePlay.h</h1> <pre><code>#ifndef SNAKE_GAME_PLAY_H #define SNAKE_GAME_PLAY_H #include &lt;iostream&gt; #include "Field.h" #include "Snake.h" #include "Prize_cell.h" #include "controls.h" class GamePlay { public: GamePlay(); void play(); private: using size_type = Field::size_type; // How many prize cells have been eaten: size_type score; // how fast the snake moves: smaller number = faster size_type game_wait_time; Field field; Snake snake; // converts a char to direction Snake::Direction get_direction(int ch); // update the display with new version of the field void update_display(); // create a prize randomly in the field void add_prize_to_field(size_type = 1); // the opening screen void initial_display(); }; #endif // !SNAKE_GAME_PLAY_H </code></pre> <h1>GamePlay.cpp</h1> <pre><code>#include "GamePlay.h" #include &lt;random&gt; #include &lt;ctime&gt; #include &lt;memory&gt; #include "Prize_cell.h" #include "Field_cell.h" using std::cout; using std::endl; using std::cin; using std::default_random_engine; using std::uniform_int_distribution; using std::shared_ptr; using std::make_shared; GamePlay::GamePlay() : field() , snake(field) , score(0) , game_wait_time(0) { } void GamePlay::play() { // opening screen initial_display(); bool move_succeded = true; // When prize_counter reaches prize_cnt, a new prize appears size_type prize_counter = 0; // main game loop // the loop goes on until snake.slither returns false while (move_succeded) { // if a key is pressed, the snake should move in the // corresponding direction if (a_key_pressed()) { move_succeded = snake.slither(get_direction(get_pressed_key())); } // else the snake should continue moving in the previous direction else { move_succeded = snake.slither(Snake::Direction::CONTINUE); } // draw the new version of the board update_display(); if (snake.ate_this_move) { add_prize_to_field(); ++score; snake.ate_this_move = false; } // wait a little before the next move sleep(game_wait_time); } cout &lt;&lt; "Game Over" &lt;&lt; endl; keep_window_open(); } Snake::Direction GamePlay::get_direction(int ch) { switch (ch) { case 'w': return Snake::Direction::UP; case 's': return Snake::Direction::DOWN; case 'a': return Snake::Direction::LEFT; case 'd': return Snake::Direction::RIGHT; default : return Snake::Direction::CONTINUE; } } inline void GamePlay::update_display() { gotoxy(0, 0); std::cout &lt;&lt; field; std::cout &lt;&lt; "Score: " &lt;&lt; score &lt;&lt; '\n'; } void GamePlay::add_prize_to_field(size_type prize_amount) { static default_random_engine e(std::time(0)); static uniform_int_distribution&lt;size_type&gt; dis_height(0, Field::field_height - 1); static uniform_int_distribution&lt;size_type&gt; dis_width(0, Field::field_width - 1); static std::shared_ptr&lt;Prize_cell&gt; default_prize_cell = make_shared&lt;Prize_cell&gt;(); static size_type col = 0, row = 0; // if we don't find an empty spot in this many tries // we just give up size_type prize_rand_try_count = Field::field_height * Field::field_width; do { col = dis_height(e); row = dis_width(e); if (--prize_rand_try_count == 0) { return; } } while (field.cellIsOccupied(col, row)); field.add_to_field(default_prize_cell, col, row); } void GamePlay::initial_display() { cout &lt;&lt; "Welcome to Snake\n"; cout &lt;&lt; "Controls:\n" &lt;&lt; " W\n" &lt;&lt; " A S D\n\n\n"; cout &lt;&lt; "Pick enter a speed number between 1 and 10 (larger==faster)" &lt;&lt; endl; size_type speed_numb = 11; cin &gt;&gt; speed_numb; while (speed_numb &gt; 10) { cout &lt;&lt; "This was out of range, plase try again." &lt;&lt; endl; cin.clear(); cin &gt;&gt; speed_numb; } // add 1 to avoid dividing by 0 ++speed_numb; // the wait time is the difference in msec game_wait_time = 1050 - speed_numb * 100; clear_scrn(); } </code></pre> <h1>Prize_cell.h</h1> <pre><code>#ifndef SNAKE_PRIZE_CELL_H #define SNAKE_PRIZE_CELL_H #include "Cell.h" class Prize_cell : public Cell { public: Prize_cell(); ~Prize_cell() override = default; }; #endif // !SNAKE_PRIZE_CELL_H </code></pre> <h1>Prize_cell.cpp</h1> <pre><code>#include "Prize_cell.h" using std::size_t; Prize_cell::Prize_cell() : Cell('*', false, true) // the cell is not occupied although it is not empty // because hitting an occupied cell would kill the snake { } </code></pre> <h1>Snake_cell.h</h1> <pre><code>#ifndef SNAKE_SNAKE_CELL_H #define SNAKE_SNAKE_CELL_H #include "Cell.h" class Snake_cell : public Cell { public: Snake_cell(); ~Snake_cell() override = default; }; #endif // !SNAKE_SNAKE_CELL_H </code></pre> <h1>Snake_cell.cpp</h1> <pre><code>#include "Snake_cell.h" Snake_cell::Snake_cell() : Cell('o', true) { } </code></pre> <h1>Snake.h</h1> <pre><code>#ifndef SNAKE_SNAKE_H #define SNAKE_SNAKE_H #include &lt;list&gt; #include &lt;tuple&gt; #include "Field.h" #include "Snake_cell.h" class Snake { public: using size_type = Field::size_type; Snake(Field&amp;); // directions in which snake may move. // CONTINUE means keep on going in the // previous direction. Opposite sides are // are multiplied by -1 enum class Direction { UP = 1, DOWN = -1, LEFT = 2, RIGHT = -2, CONTINUE = 3 }; Snake(Snake&amp;) = delete; // bool slither(Direction) : move snake in the field. // Returns false if snake hits something // and game should be over. true otherwise bool slither(Direction); // size of the snake in cells (how many cells // it has) size_type size() { return container.size(); } // a signal to game to create a new prize bool ate_this_move = true; private: using cell_ptr = std::shared_ptr&lt;Snake_cell&gt;; const size_type starting_snake_size; // details about a cell: a (shared) pointer to the cell, // column number and row number using cell_detail_type = std::tuple&lt;cell_ptr, size_type, size_type&gt;; using snake_container_type = std::list&lt;cell_detail_type&gt;; Field&amp; field; snake_container_type container; // called when eaten something causes the snake // to grow by 1 void grow(); // pushes tail to back and pops from front void move_tail_back(); // returns true if the position within // the field and it is not occupied. false other wise bool pos_is_valid(size_type col, size_type row); // used by the slither function to get // the new col and row pos bool newPos(size_type&amp;, size_type&amp;, Direction); // update the cell with new position details in cell_detail_type object void update_cell_pos_info(cell_detail_type&amp; cdt, size_type col, size_type row); std::shared_ptr&lt;Snake_cell&gt; default_snake_cell; // if and when a prize is eaten, this becomes true // until the snake has moved and is grown accordingly bool waiting_eaten = false; }; #endif // !SNAKE_SNAKE_H </code></pre> <h1>Snake.cpp</h1> <pre><code>#include "Snake.h" #include &lt;memory&gt; using std::make_shared; using std::make_tuple; using std::get; Snake::Snake(Field&amp; field_) : field(field_) , default_snake_cell(make_shared&lt;Snake_cell&gt;()) , starting_snake_size(3) { size_type height_half = Field::field_height / 2; size_type width_half = Field::field_width / 2; for (size_type icell = 0; icell != starting_snake_size; ++icell) { container.push_back( make_tuple( default_snake_cell, height_half - icell, width_half ) ); // put those `Snake_cell`s into the field field.add_to_field(get&lt;0&gt;(container.back()), get&lt;1&gt;(container.back()), get&lt;2&gt;(container.back()) ); } } bool Snake::slither(Direction direction) { // the new position we the snake is moving to auto newCol = get&lt;1&gt;(container.back()); auto newRow = get&lt;2&gt;(container.back()); // update newCol and newRow if (!newPos(newCol, newRow, direction)) { return true; } // if the cell we just moved is occupied, the game is over // thus, we return false if (!pos_is_valid(newCol, newRow)) { return false; } if (field[newCol][newRow]-&gt;get_prize()) grow(); // if a prize is eaten, move accordingly if (waiting_eaten) { field.add_to_field(default_snake_cell, newCol, newRow); waiting_eaten = false; } else { // swipe the tail and the (empty) cell it is moving to field.swipe_cells(newCol, newRow, get&lt;1&gt;(container.front()), get&lt;2&gt;(container.front())); } // update the position of the cell in snake's own container update_cell_pos_info(container.front(), newCol, newRow); // move the tail to the back making it the new head move_tail_back(); return true; } void Snake::grow() { container.push_front( make_tuple( default_snake_cell, get&lt;1&gt;(container.back()), get&lt;2&gt;(container.back()) ) ); waiting_eaten = true; ate_this_move = true; } // pushes tail to back and pops from front inline void Snake::move_tail_back() { container.push_back(container.front()); container.pop_front(); } // returns true if the position within // the field and it is not occupied. false other wise inline bool Snake::pos_is_valid(size_type col, size_type row) { return col &lt; Field::field_height &amp;&amp; row &lt; Field::field_width &amp;&amp; !field.cellIsOccupied(col, row); } bool Snake::newPos(size_type &amp;newCol, size_type &amp;newRow, Direction direction) { static auto previous = Direction::UP; // if the directions are opposite, snake cannot do this move if (direction == Direction::CONTINUE || direction == Direction(int(previous) * -1)) direction = previous; // this switch case does the actual movement calculation. // There are some moves (like UP when previous was DOWN) // that snake cannot do and those have no effect switch (direction) { case Direction::UP: --newCol; break; case Direction::DOWN: ++newCol; break; case Direction::RIGHT: ++newRow; break; case Direction::LEFT: --newRow; break; } previous = direction; return true; } // update the cell with new position details in cell_detail_type object inline void Snake::update_cell_pos_info(cell_detail_type &amp; cdt, size_type col, size_type row) { std::get&lt;1&gt;(cdt) = col; std::get&lt;2&gt;(cdt) = row; } </code></pre> <h1>controls.h</h1> <pre><code>#ifndef SNAKE_CONTROLS_H #define SNAKE_CONTROLS_H #include &lt;thread&gt; // std::this_thread::sleep_for #include &lt;chrono&gt; // std::chrono::seconds #include &lt;iostream&gt; #if defined _WIN32 #include &lt;conio.h&gt; #define a_key_pressed() _kbhit() #define get_pressed_key() _getch() #define clear_scrn() system("cls") #include &lt;Windows.h&gt; inline void gotoxy(short x, short y) { COORD pos = { x, y }; HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(output, pos); } #elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__) || defined(__APPLE__) // Unix-like operating systems are not supported yet static_assert(false); #define clear_scrn() system("clear") int get_pressed_key(); bool a_key_pressed(); inline void gotoxy(short x, short y); void clear(); #endif // OS check // Universal tools inline void sleep(long long msec) { std::this_thread::sleep_for(std::chrono::milliseconds(msec)); } inline void keep_window_open() { std::cout &lt;&lt; "Press Enter to close the window" &lt;&lt; std::endl; std::cin.get(); std::cin.get(); } #endif //SNAKE_CONTROLS_H </code></pre> <p>Here is a screenshot:<br> <a href="https://i.stack.imgur.com/4tBDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4tBDh.png" alt="A screenshot from the game"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T13:01:59.113", "Id": "213884", "Score": "4", "Tags": [ "c++", "snake-game" ], "Title": "Classic Snake Game on console" }
213884
<p>This quiz is on <a href="https://doc.rust-lang.org/book/ch08-03-hash-maps.html#summary" rel="nofollow noreferrer">The Rust Programming Language online ebook</a>.</p> <blockquote> <p>Given a list of integers, use a vector and return the mean (the average value), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.</p> </blockquote> <p>As a novice Rust programmer, I'd like get my code reviewed and learn more about programming Rust.</p> <p>There are a couple of things I'd like to know:</p> <ul> <li>getting input using <code>io::stdin().read_line()</code> is ok for this case,</li> <li>if there's better looping (user-input) and quitting pattern,</li> <li>handling user input errors with helpful error message (<code>Your input is invalid. Please enter whitespace-separated integers.</code>) then re-ask with prompt, instead of panicking,</li> <li>whether type casting using <code>as</code> is commonly-used (ex: <code>i32</code> -> <code>f32</code>),</li> <li>implementation of <code>get_median()</code> and <code>get_mode()</code> can be simpler than now</li> </ul> <p>Here's my code:</p> <pre><code>use std::collections::HashMap; use std::io::{self, prelude::*}; fn main() { let stdin = io::stdin(); 'mainloop: loop { print!("Enter space-separated numbers (q for quit)&gt; "); io::stdout().flush().expect("flush failed"); let mut line = String::new(); stdin.read_line(&amp;mut line).expect("Failed to read line"); if line == "q\n" { break 'mainloop; } // TODO: handling ParseIntError let nums: Vec&lt;i32&gt; = line .split_whitespace() .map(|s| s.parse::&lt;i32&gt;().unwrap()) .collect(); let mean = nums.iter().sum::&lt;i32&gt;() as f32 / nums.len() as f32; println!( "numbers: {:?}, mean: {}, median: {}, mode: {}", nums, mean, get_median(&amp;nums), get_mode(&amp;nums) ); } } fn get_median(v: &amp;Vec&lt;i32&gt;) -&gt; f32 { if v.len() &lt; 1 { return 0.0; } let mut vec = v.clone(); vec.sort(); if vec.len() % 2 == 1 { return *vec.get(vec.len() / 2).unwrap() as f32; } return (*vec.get(vec.len() / 2 - 1).unwrap() + *vec.get(vec.len() / 2).unwrap()) as f32 / 2.0; } fn get_mode(v: &amp;Vec&lt;i32&gt;) -&gt; i32 { let mut map = HashMap::new(); for num in v { let count = map.entry(num).or_insert(0); *count += 1; } return **map.iter().max_by_key(|(_, v)| *v).unwrap().0; } </code></pre> <ul> <li>This code is on <a href="https://github.com/philipjkim/mean-median-mode/blob/v1/src/main.rs" rel="nofollow noreferrer">GitHub</a> also.</li> <li>I found there are similar questions related to the same quiz on Code Review, but the implementations differ. So I think they're not duplicated question.</li> </ul>
[]
[ { "body": "<p>Good job! I'm sure there are problems with my take, but, for what it's worth, here's how I might suggest improving things a bit.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::collections::HashMap;\nuse std::io::{self, Write}; // Personal preference, but I prefer avoiding glob imports\nuse std::num::ParseIntError;\n\nfn main() {\n let stdin = io::stdin();\n let mut stdout = io::stdout();\n\n // Allocate a String buffer once and keep reusing it, instead of allocating multiple times.\n let mut line = String::new();\n\n // No need to name the loop since it's the only one. Loop naming\n // isn't very idiomatic in rust; it's typically used only when there\n // are loops within loops and naming is needed to solve ambiguity.\n loop {\n print!(\"Enter space-separated numbers (q for quit)&gt; \");\n // Unwrap here seems OK, since if flush() fails, something went terribly wrong.\n stdout.flush().unwrap();\n\n // Clear the String buffer to prepare for reuse.\n line.clear();\n // Unwrap here seems OK, for similar reasoning as above.\n stdin.read_line(&amp;mut line).unwrap();\n\n if line == \"q\\n\" {\n break;\n }\n\n // Let the closure passed to map return a Result, then collect into a\n // Result&lt;Vec&lt;_&gt;, ParseIntError&gt;, which will be Ok if all parsing succeeded\n // or Err if any parsing failed. After that, match on your Result to handle errors.\n let mut nums = match line\n .split_whitespace()\n .map(|s| s.parse::&lt;i32&gt;())\n .collect::&lt;Result&lt;Vec&lt;i32&gt;, ParseIntError&gt;&gt;()\n {\n Ok(vec) =&gt; {\n if vec.is_empty() {\n // Error handling: If user didn't give you any input, try again.\n continue;\n }\n vec\n }\n Err(_) =&gt; {\n // Error handling: If user gave you bad input, try again.\n println!(\"Invalid input. Only integer values are accepted. Please try again.\");\n continue;\n }\n };\n\n // Casting i32 to f32 is fine.\n let mean = nums.iter().sum::&lt;i32&gt;() as f32 / nums.len() as f32;\n let median = get_median(&amp;mut nums);\n let mode = get_mode(&amp;nums);\n\n println!(\n \"numbers: {:?}, mean: {}, median: {}, mode: {:?}\",\n &amp;nums, // No need to consume nums (even though in this case you never use it again)\n mean,\n median,\n mode,\n );\n\n break;\n }\n}\n\n// Avoid the clone by passing a mutable reference\nfn get_median(vec: &amp;mut Vec&lt;i32&gt;) -&gt; f32 {\n // is_empty() is slightly more idiomtic than vec.len() &lt; 1\n if vec.is_empty() {\n return 0.0;\n }\n\n vec.sort();\n\n // * `vec.len() / 2` is reusable code; so make it it's own varible\n // * Instead of using `vec.get(index).unwrap()`, use `vec[index]`,\n // as we know our index is valid.\n let index = vec.len() / 2;\n\n if vec.len() % 2 == 1 {\n vec[index] as f32\n } else {\n (vec[index - 1] as f32 + vec[index] as f32) / 2.0\n }\n}\n\n// * Whenever you want to pass &amp;Vec&lt;_&gt; as an argument to a function,\n// consider passing &amp;[_] instead. It works with more types.\n// * Mode is not necessarily unique; so return a Vec&lt;i32&gt;.\nfn get_mode(slice: &amp;[i32]) -&gt; Vec&lt;i32&gt; {\n if slice.is_empty() {\n // bail early if the input is empty; so that we avoid\n // unnecessarily allocating a HashMap.\n return vec![];\n }\n\n // Waste a little space by allocating from the start a HashMap\n // of maximum possible size; this avoids the possibility of\n // having to rellocate once the size has grown bigger than\n // capacity. It's a micro optimization, but in general in rust\n // if you know how big a heap allocated thing (like Vec, String, HashMap)\n // etc. needs to be in advance; take advantage of that information.\n let mut map = HashMap::with_capacity(slice.len());\n for num in slice {\n let count = map.entry(num).or_insert(0);\n *count += 1;\n }\n\n // Unwrap is OK because we know the map is non-empty.\n let max_value = map.values().map(|v| *v).max().unwrap();\n\n // Use into_iter() as we don't need the map anymore and\n // that will more efficiently create the vec than\n // if we had used iter()\n let mut vec = map\n .into_iter()\n .filter_map(|(k, v)| if v == max_value { Some(*k) } else { None })\n .collect::&lt;Vec&lt;i32&gt;&gt;();\n\n // Sort because it makes the output deterministic\n vec.sort();\n\n vec\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:08:28.107", "Id": "213897", "ParentId": "213886", "Score": "3" } } ]
{ "AcceptedAnswerId": "213897", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T13:45:58.680", "Id": "213886", "Score": "2", "Tags": [ "rust" ], "Title": "Rust: calculating mean, median, and mode for numbers from stdin" }
213886
<p>I've been working for few days to develop a basic Java Swing Calculator that could Add, Subtract, Multiply or Divide two numbers and also has other options like inverse(1/x) and square root</p> <p>I would like you to analyze my code that it follows basic OOPS concepts like Abstraction, Encapsulation, Polymorphism etc. </p> <pre><code>import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; class Cal extends javax.swing.JFrame implements ActionListener { private DigitButton plusminus, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bpoint; private OpButton add, sub, mul, div, del, clear, inv, sqrt, equal; JTextField tf; static double a = 0, b = 0, result = 0; static int operator = 0; private int point; private Image icon; Cal() { super("Calculator"); point = 0; icon = Toolkit.getDefaultToolkit().getImage("icon.png"); // Loading icon image into memory /************* Initialising buttons ************/ b1 = new DigitButton("1"); b2 = new DigitButton("2"); b3 = new DigitButton("3"); b4 = new DigitButton("4"); b5 = new DigitButton("5"); b6 = new DigitButton("6"); b7 = new DigitButton("7"); b8 = new DigitButton("8"); b9 = new DigitButton("9"); b0 = new DigitButton("0"); bpoint = new DigitButton("."); inv = new OpButton("1/x"); sqrt = new OpButton("√"); plusminus = new DigitButton("±"); del = new OpButton("DEL"); add = new OpButton("+"); sub = new OpButton("-"); mul = new OpButton("×"); div = new OpButton("÷"); clear = new OpButton("C"); equal = new OpButton("="); // TextField in which result is to be displayed tf = new JTextField(); tf.setEditable(false); tf.setFont(new Font("Segoi UI", Font.BOLD, 25)); // Setting font // tf.setBackground(Color.DARK_GRAY.darker().darker()); // tf.setForeground(Color.WHITE.brighter()); tf.setBackground(Color.WHITE); tf.setForeground(Color.BLACK); tf.setText("0"); tf.setBorder(null); /********** Setting the location of the buttons ***********/ JPanel panel = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(); JPanel panel4 = new JPanel(); panel.add(b7); panel.add(b8); panel.add(b9); panel.add(b4); panel.add(b5); panel.add(b6); panel.add(b1); panel.add(b2); panel.add(b3); panel2.add(plusminus); panel2.add(b0); panel2.add(bpoint); panel3.add(div); panel3.add(mul); panel3.add(sub); panel3.add(add); panel3.add(equal); panel4.add(clear); panel4.add(sqrt); panel4.add(inv); panel4.add(del); GridLayout grid = new GridLayout(3, 3); GridLayout grid2 = new GridLayout(1, 2); GridLayout grid3 = new GridLayout(5, 1); GridLayout grid4 = new GridLayout(1, 4); panel.setLayout(grid); panel.setBounds(0, 160, 240, 240); panel2.setLayout(grid2); panel2.setBounds(0, 400, 240, 80); panel3.setLayout(grid3); panel3.setBounds(240, 160, 80, 320); panel4.setLayout(grid4); panel4.setBounds(0, 80, 320, 80); tf.setBounds(0, 0, 320, 80); tf.setHorizontalAlignment(JTextField.RIGHT); // Setting alignment /******** Adding Panels to the Frame ***********/ add(panel); add(panel2); add(panel3); add(panel4); add(tf); /* Adding ActionListeners to the buttons */ b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); bpoint.addActionListener(this); clear.addActionListener(this); equal.addActionListener(this); add.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); div.addActionListener(this); plusminus.addActionListener(this); sqrt.addActionListener(this); inv.addActionListener(this); del.addActionListener(this); //////////////////////////////////////////// setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setIconImage(icon); setLocationRelativeTo(null); setSize(335, 515); setLayout(null); setVisible(true); } private boolean isZero(String Text) { if (Text.equals("0")) return true; else return false; } private void getInput(ActionEvent e) { if (tf.getText().equals("∞")) { } else if (tf.getText().equals("Invalid input")) { } else if (e.getSource().equals(b0)) { if (isZero(tf.getText())) { tf.setText("0"); } else { tf.setText(tf.getText().concat("0")); } } else if (e.getSource().equals(b1)) { if (isZero(tf.getText())) { tf.setText("1"); } else { tf.setText(tf.getText().concat("1")); } } else if (e.getSource().equals(b2)) { if (isZero(tf.getText())) { tf.setText("2"); } else { tf.setText(tf.getText().concat("2")); } } else if (e.getSource().equals(b3)) { if (isZero(tf.getText())) { tf.setText("3"); } else { tf.setText(tf.getText().concat("3")); } } else if (e.getSource().equals(b4)) { if (isZero(tf.getText())) { tf.setText("4"); } else { tf.setText(tf.getText().concat("4")); } } else if (e.getSource().equals(b5)) { if (isZero(tf.getText())) { tf.setText("5"); } else { tf.setText(tf.getText().concat("5")); } } else if (e.getSource().equals(b6)) { if (isZero(tf.getText())) { tf.setText("6"); } else { tf.setText(tf.getText().concat("6")); } } else if (e.getSource().equals(b7)) { if (isZero(tf.getText())) { tf.setText("7"); } else { tf.setText(tf.getText().concat("7")); } } else if (e.getSource().equals(b8)) { if (isZero(tf.getText())) { tf.setText("8"); } else { tf.setText(tf.getText().concat("8")); } } else if (e.getSource().equals(b9)) { if (isZero(tf.getText())) { tf.setText("9"); } else { tf.setText(tf.getText().concat("9")); } } else if (e.getSource().equals(bpoint)) { if (point &lt; 1) { tf.setText(tf.getText().concat(".")); point = 1; } else { } } else if (e.getSource().equals(sqrt)) { double val = Double.parseDouble(tf.getText()); if (val &lt; 0) { tf.setText("Invalid input"); } else { point = 1; val = Math.sqrt(val); tf.setText(String.valueOf(val)); } } else if (e.getSource().equals(inv)) { double val = Double.valueOf(tf.getText()); if (val == 0) { tf.setText("∞"); } else { point = 1; val = 1 / val; tf.setText(String.valueOf(val)); } } else if (e.getSource().equals(plusminus)) { double val = Double.valueOf(tf.getText()); if (val == 0) { tf.setText("0"); } else { point = 1; val = -val; tf.setText(String.valueOf(val)); } } } public void actionPerformed(ActionEvent e) { if (tf.getText().equals("+") || tf.getText().equals("-") || tf.getText().equals("×") || tf.getText().equals("÷")) { tf.setText(""); getInput(e); } else if (e.getSource().equals(clear)) { point = 0; tf.setText("0"); } else if (e.getSource().equals(del)) { String s = tf.getText(); tf.setText(""); if (s.equals("∞")) { tf.setText("0"); point = 0; } else if (s.equals("Invalid input")) { tf.setText("0"); point = 0; } else if (Double.valueOf(s) &lt; 0) { if (s.length() &lt; 3) { if (s.matches("-")) { point = 0; tf.setText("0"); } else { point = 0; tf.setText("0"); } } else { for (int i = 0; i &lt; s.length() - 1; i++) { tf.setText(tf.getText() + s.charAt(i)); } if (tf.getText().contains(".")) { point = 1; } else { point = 0; } } } else { if (s.length() &lt; 2) { /* * if (s.matches("-")) { Text = "0"; tf.setText(Text); } else { */ point = 0; tf.setText("0"); // } } else { for (int i = 0; i &lt; s.length() - 1; i++) { tf.setText(tf.getText() + s.charAt(i)); } if (tf.getText().contains(".")) { point = 1; } else { point = 0; } } } } else if (tf.getText().equals("∞")) { } else if (tf.getText().equals("Invalid input")) { } else if (e.getSource().equals(add)) { a = Double.valueOf(tf.getText()); operator = 1; tf.setText("+"); } else if (e.getSource().equals(sub)) { a = Double.valueOf(tf.getText()); operator = 2; tf.setText("-"); } else if (e.getSource().equals(mul)) { a = Double.valueOf(tf.getText()); operator = 3; tf.setText("×"); } else if (e.getSource().equals(div)) { a = Double.valueOf(tf.getText()); operator = 4; tf.setText("÷"); } else if (e.getSource().equals(equal)) { point = 1; tf.setText(calcInput(operator, a)); } else { getInput(e); } } private String calcInput(int operator, double a) { b = Double.valueOf(tf.getText()); String Result; switch (operator) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: if (b != 0) result = a / b; else { result = 0; tf.setText("∞"); } } if (b == 0) Result = "∞"; else Result = String.valueOf(result); operator = 0; return Result; } } public class Calc { public static void main(String[] args) { new Cal(); } } class OpButton extends JButton { private Color bgcolor, frcolor; OpButton(String op) { super(op); setBorderPainted(false); setFocusPainted(false); setFont(new Font("Segoi UI", Font.PLAIN, 22)); bgcolor = new Color(0, 153, 255); frcolor = Color.WHITE; setContentAreaFilled(false); setOpaque(true); setBackground(bgcolor); setForeground(frcolor); setText(op); addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent evt) { if (getModel().isPressed()) { setBackground(bgcolor.darker().darker()); } else if (getModel().isRollover()) { setBackground(bgcolor.darker()); } else { setBackground(bgcolor); } } }); } } class DigitButton extends JButton { private Color bgcolor, color2; final static long serialVersionUID = 2; DigitButton(String digit) { super(digit); setBorderPainted(false); setFocusPainted(false); bgcolor = Color.WHITE; color2 = new Color(0, 153, 255); setFont(new Font("Segoi UI", Font.BOLD, 22)); setContentAreaFilled(false); setOpaque(true); // setForeground(Color.BLACK.darker().darker()); setText(digit); setBackground(bgcolor); setForeground(color2); addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent evt) { /* * if (getModel().isPressed()) { setBackground(bgcolor.darker().darker()); // * setForeground(Color.WHITE); } else if (getModel().isRollover()) { * setBackground(bgcolor.darker().darker()); // setForeground(Color.WHITE); } * else { // setForeground(color2); setBackground(bgcolor.darker()); } */ if (getModel().isPressed()) { setBackground(bgcolor.darker().darker()); setForeground(Color.WHITE); } else if (getModel().isRollover()) { setBackground(bgcolor.darker()); setForeground(Color.WHITE); } else { setBackground(bgcolor); setForeground(color2); } } }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:48:10.947", "Id": "413708", "Score": "5", "body": "\"Could you please help me to extend it two more that two numbers.\", This is not a codewriting service. We can however give feedback on the code you *have* written" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:32:57.583", "Id": "413798", "Score": "0", "body": "Look for the source code of GNU shell utils \"expr\" command. It has everything you need to support expression evaluation. I've ported it to Java for my own needs and it worked perfectly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T09:38:09.830", "Id": "413812", "Score": "0", "body": "A note, as this is a nice & useful product, but it does not separate things in Model-View-Controller style. And that is a pity: many fields/variables. GUI and calculating mixed; `tf.setText`s. Expect some criticism on a nice application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:53:03.167", "Id": "413859", "Score": "3", "body": "John, to emphasize on what Ludisposed said, you should edit your question to remove this request if you want your actual code to be reviewed, otherwise your question will probably get closed" } ]
[ { "body": "<p>I suggest to exctract the ActionListener into separate classes and bind them to the Buttons :</p>\n\n<pre><code>button.addActionListener(new AdditionButtonListener())\n\npublic class AdditionActionListener implenents ActionListener{} \n</code></pre>\n\n<p>I also suggest to separate your view from your Model. Invent A separate Calculator that consists the actual state of your Calculator and use the ActionListeners registered on your GUI buttons to manipulate your calculator state. </p>\n\n<p>In general I would recommend to read about common design patterns so you get A feeling for seperating things and building some kind of logical flow in your application. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:56:28.067", "Id": "213894", "ParentId": "213890", "Score": "0" } }, { "body": "<p>Just more than two terms? How about many terms and operands? You're doing it the hard way, and as you're seeing, it's not easily extensible. You need a different approach.</p>\n\n<p>If you want to evaluate functions of arbitrary complexity, I would suggest the ANTLR4 framework for your expression evaluator. Java is the \"native language\" of ANTLR4, and by using the Visitor pattern and a simple expression grammar, you can achieve a lot of capability with far less code than you show here. </p>\n\n<p>As an example, see Bart Kiers's <a href=\"https://github.com/bkiers/Mu\" rel=\"nofollow noreferrer\">Mu project</a> on github on how to do some very powerful things with little code in ANTLR4.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:03:02.183", "Id": "213896", "ParentId": "213890", "Score": "0" } }, { "body": "<h1>Object Oriented Programming</h1>\n\n<blockquote>\n <p>I would like you to analyze my code that it follows basic OOPS concepts like Abstraction, Encapsulation, Polymorphism etc</p>\n</blockquote>\n\n<p>In general it is about sending messages (interact with methods) from one object to an other.</p>\n\n<p>The code uses the keyword <code>class</code> but this makes no program object-oriented. To analyze the code and to make it object-oriented takes time and should be done by you.</p>\n\n<p>Some guide lines based the code you provide us:</p>\n\n<ul>\n<li>A class should have only one responsibility</li>\n<li>A class should be small</li>\n<li>A method should be small</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">A class should be open for extension, but closed for modification</a> </li>\n<li>A class should have a reduced number of members</li>\n</ul>\n\n<hr>\n\n<h1><a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model-View-Controller</a></h1>\n\n<p>Currently the business logic and view logic has a high cohesion. With MVC you can decouple the view from the business logic. So it could be imaginable to switch the a view from the \"normal\" numerals to Roman numerals without changing the business logic. </p>\n\n<hr>\n\n<h1>Code Smell</h1>\n\n<h2>Don't Make me Think</h2>\n\n<p>What is a <code>Cal</code>? Is it a abbreviation for <em>Calculation</em>? Let me take a look into the class.. Ok.. there is a <code>b0</code>, <code>b1</code>, .. they could represent the buttons of a calculator. So <code>Cul</code> stands for <em>Calculator</em>.</p>\n\n<p>Rename <code>Cul</code> to <code>Calculator</code> </p>\n\n<h2>Commented-Out Code</h2>\n\n<p>Robert C Martin <a href=\"http://www.informit.com/articles/article.aspx?p=1334908\" rel=\"nofollow noreferrer\">sad</a></p>\n\n<blockquote>\n <p>When you see commented-out code, delete it! Don’t worry; the source code control system still remembers it. If anyone really needs it, he or she can go back and check out a previous version. Don’t suffer commented-out code to survive.</p>\n</blockquote>\n\n<p>A example from the code you provided</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>/*\n* if (getModel().isPressed()) { setBackground(bgcolor.darker().darker()); //\n* setForeground(Color.WHITE); } else if (getModel().isRollover()) {\n* setBackground(bgcolor.darker().darker()); // setForeground(Color.WHITE); }\n* else { // setForeground(color2); setBackground(bgcolor.darker()); }\n*/\n</code></pre>\n</blockquote>\n\n<p>What does it mean to the person how read it? Should the person ignore it, like a compiler, or shout it be a hind, that this could work? Now one knows.. </p>\n\n<h2>Comments</h2>\n\n<blockquote>\n <p><a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">Don’t Use a Comment When You Can Use a Function or a Variable</a></p>\n</blockquote>\n\n<p>To improve the readability of he code we could wrap the following in methods</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>/************* Initialising buttons ************/\nb1 = new DigitButton(\"1\");\nb2 = new DigitButton(\"2\");\n// ...\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void initializeButtons() {\n b1 = new DigitButton(\"1\");\n b2 = new DigitButton(\"2\");\n // ...\n}\n</code></pre>\n\n<p>and </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>// TextField in which result is to be displayed\ntf = new JTextField();\ntf.setEditable(false);\n// ...\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void createTextfield() {\n tf = new JTextField();\n tf.setEditable(false);\n //..\n}\n</code></pre>\n\n<p>till the constructor looks like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Cal() {\n initializeButtons();\n createTextfield();\n giveButtonLocations();\n giveButtonsActionListeners();\n}\n</code></pre>\n\n<h2>Follow the Standard</h2>\n\n<p>When I first saw the statement <code>Text.equals(\"0\")</code> I thought <code>Text</code> would be a class with a static method <code>equals</code>.</p>\n\n<p>But <code>Text</code> is just a <code>String</code></p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private boolean isZero(String Text)\n</code></pre>\n</blockquote>\n\n<p><code>Text</code> should be renamed to <code>text</code> so it is clear that it is a variable.</p>\n\n<h2>Empty Blocks</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (tf.getText().equals(\"∞\")) {\n\n} else if (tf.getText().equals(\"Invalid input\")) {\n\n}\n</code></pre>\n</blockquote>\n\n<p>As a reader I do not know if there is code missing and if these blocks should be empty that I have to thing about it why they are empty. But if you remove these two empty blocks the logic will be the same.</p>\n\n<h2>Duplicate Code</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>} else if (e.getSource().equals(b0)) {\n if (isZero(tf.getText())) {\n tf.setText(\"0\");\n } else {\n tf.setText(tf.getText().concat(\"0\"));\n }\n} else if (e.getSource().equals(b1)) {\n if (isZero(tf.getText())) {\n tf.setText(\"1\");\n } else {\n tf.setText(tf.getText().concat(\"1\"));\n }\n} else if (e.getSource().equals(b2)) {\n // ...\n}\n// ...\n</code></pre>\n</blockquote>\n\n<h3>Put Buttons Into a Map</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Calculator {\n private Map&lt;DigitButton&gt; digitButtons;\n\n Calculator() {\n initializeButtons();\n // ...\n }\n\n private void initializeButtons() {\n Map&lt;DigitButton&gt; digitButtons = new HashMap();\n digitButtons.put(\"0\", new DigitButton(\"0\"));\n digitButtons.put(\"1\", new DigitButton(\"1\"));\n // ..\n this.digitButtons = digitButtons;\n }\n}\n</code></pre>\n\n<p>A other way would be to accept a map of buttons through the constructor.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Calculator {\n private Map&lt;String, DigitButton&gt; digitButtons;\n // ...\n\n Calculator(Map&lt;String, DigitButton&gt; digitButtons) {\n this.digitButtons = digitButtons;\n // ...\n }\n}\n</code></pre>\n\n<h3>Replace If-Statements by <code>get</code></h3>\n\n<p>Since a <code>DigitButton</code> is a <code>JButton</code> it is possible to get the text of the button via <code>getText</code>. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void getInput(ActionEvent e) {\n DigitButton button = digitButtons.get(e.getSource());\n String digit = button.getText();\n if (isZero(tf.getText())) {\n tf.setText(digit);\n } else {\n tf.setText(tf.getText().concat(digit));\n }\n // ...\n}\n</code></pre>\n\n<h2>Wrap the Map into a First-Class-Collection</h2>\n\n<p>The First Class Collection [FCC] is an idea of the <a href=\"https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf\" rel=\"nofollow noreferrer\">Object Calisthenics</a>.</p>\n\n<blockquote>\n <p>Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home.</p>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>class DigitButtonColletion {\n private Map&lt;String, DigitButton&gt; digitButtons;\n\n DigitButtonColletion(Map&lt;String, DigitButton&gt; digitButtons) {\n this.digitButtons = digitButtons;\n }\n\n public DigitButton findBySymbol(String symbol) {\n return digitButtons.get(symbol);\n }\n\n // example for another method\n public DigitButton findAllLessThan(String symbol) {\n //...\n }\n}\n</code></pre>\n\n<p>When you do same for the <code>OpButtons</code> the <code>Calculator</code> could look like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Calculator {\n private DigitButtonCollection digitButtons;\n private OperationButtonCollection operationButtons;\n // ...\n\n Calculator(DigitButtonCollection digitButtons,\n OperationButtonCollection operationButtons) {\n this.digitButtons = digitButtons;\n this.operationButtons = operationButtons;\n // ...\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-10T11:15:27.517", "Id": "438734", "Score": "0", "body": "Thank You @Roman for you detailed review.... :-) As I am a _newbie_ to programming I made many mistakes in the program, but thank you for your guidance and for taking out time to review my code..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:14:16.077", "Id": "213942", "ParentId": "213890", "Score": "2" } } ]
{ "AcceptedAnswerId": "213942", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T14:45:56.837", "Id": "213890", "Score": "-1", "Tags": [ "java", "object-oriented", "calculator", "swing" ], "Title": "A Java Calculator that could perform basic Mathematical Operations" }
213890
<p>So I am learning hooks and context, and I wanted to make a simple router. I wanted a simple API where you can just pass in routes. <code>initialRoute</code> should be optional, and it should pick it up from the pathname, otherwise it defaults to the first route.</p> <p>I want to expand it to be able to work when server side rendering, since it heavily relys on window location pathname. So I am looking for critic on my typings, my hook usage, how to prepare for server side rendering. Also just looking for any feedback if this is a good way to do a router :)</p> <p>Below I have linked to a repo where I use this code, and a gist with a <code>usage.tsx</code> file to see how I am using it.</p> <pre class="lang-js prettyprint-override"><code>import React, { createContext, useEffect, useMemo, useState } from 'react' import UrlPattern from 'url-pattern' import { IRoute, IRouterContext, IRoutes, IState } from './types' const getRoute = (routeName: string) =&gt; (i: { name: string }) =&gt; i.name === routeName const RouterContext = createContext&lt;IRouterContext&gt;(null!) const RouterProvider = (props: { children: JSX.Element[] | JSX.Element routes: IRoutes initialRoute?: string }) =&gt; { if (props.routes.length === 0) { throw new Error('You must provide routes') } const [currentRoute, setCurrentRoute] = useState&lt;IRoute&gt;(() =&gt; { const initialRoute = props.initialRoute ? props.routes.find(getRoute(props.initialRoute)) : props.routes.find(({ path }) =&gt; // eslint-disable-line new UrlPattern(path).match(window.location.pathname), // eslint-disable-line ) // eslint-disable-line return initialRoute || props.routes[0] }) const [currentState, setCurrentState] = useState&lt;IState&gt;(() =&gt; new UrlPattern(currentRoute.path).match(window.location.pathname), ) const goTo = useMemo( () =&gt; (toRouteName: string, toState: IState = {}) =&gt; { const toRoute: IRoute | undefined = props.routes.find( getRoute(toRouteName), ) if (!toRoute) { throw new Error(`Route ${toRouteName} does not exist`) } setCurrentRoute(toRoute) setCurrentState(toState) }, [currentRoute.name], ) useEffect(() =&gt; { const pattern = new UrlPattern(currentRoute.path) const path = pattern.stringify(currentState) if (path !== window.location.pathname) { window.history.pushState(null, '', path) } }, [currentRoute.path, currentState]) return ( &lt;RouterContext.Provider value={{ goTo, state: currentState, currentRoute }} &gt; {props.children} &lt;/RouterContext.Provider&gt; ) } export { RouterContext, RouterProvider } </code></pre> <p>Links:</p> <p><a href="https://gist.github.com/bitttttten/67c16fd35061e8fd329301911df6846b" rel="nofollow noreferrer">gist</a></p> <p><a href="https://github.com/bitttttten/simmer/blob/fdbc7f11cdd7724dae88572b247eaabba360afa2/src/router/index.tsx" rel="nofollow noreferrer">github repo</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:19:40.157", "Id": "213891", "Score": "1", "Tags": [ "javascript", "react.js" ], "Title": "Javascript router for React with hooks" }
213891
<p>I use ImageMagick to crop image, encapsulate the related code to functions.</p> <p>Here is the code:</p> <pre><code>convertc2(){ convert $1 -crop $2 &quot;two.png&quot; } converto3(){ Delimeter=&quot;placeHolder&quot; if [[ $2 == *&quot;x&quot;* ]]; then Delimeter=&quot;x&quot; else Delimeter=&quot;X&quot; fi First=&quot;${2%$Delimeter*}&quot; Fourth=&quot;${2##*+}&quot; Lhs=&quot;${2%%+*}&quot; Rhs=&quot;${2#&quot;$Lhs+&quot;}&quot; Second=&quot;${Lhs##*$Delimeter}&quot; Third=&quot;${Rhs%+*}&quot; One=$(echo &quot;scale=0 ; $First * 1.5&quot; | bc) One=${One%.*} Two=$(echo &quot;$Second * 1.5&quot; | bc) Two=${Two%.*} Three=$(echo &quot;$Third * 1.5&quot; | bc) Three=${Three%.*} Four=$(echo &quot;$Fourth * 1.5&quot; | bc) Four=${Four%.*} Final=$One&quot;X&quot;$Two&quot;+&quot;$Three&quot;+&quot;$Four echo $Final convert $1 -crop $Final &quot;three.png&quot; } </code></pre> <p>Usage like this:</p> <blockquote> <pre><code>convertc2 /Users/dengjiangzhou/Desktop/Simulator\ Screen\ Shot\ -\ iPhone\ 8\ -\ 2019-02-20\ at\ 14.39.02.png 300X300+0+0 converto3 /Users/dengjiangzhou/Desktop/Simulator\ Screen\ Shot\ -\ iPhone\ 8\ -\ 2019-02-20\ at\ 14.39.02.png 300X300+0+0 </code></pre> </blockquote> <p>I need the image size of @2X and @3X. So the function <code>converto3 </code> use <code>convertc2 </code>'s size and transform to its size.</p> <pre><code>Delimeter=&quot;placeHolder&quot; if [[ $2 == *&quot;x&quot;* ]]; then Delimeter=&quot;x&quot; else Delimeter=&quot;X&quot; fi </code></pre> <p>I really care about how to improve the above code. The &quot;x&quot; , I may type &quot;X&quot; or &quot;x&quot;.</p> <p>how to use this <code>&quot;${2%$Delimeter*}&quot;</code> insensitive?</p> <p>And the calculation code in <code> converto3()</code> is very ugly.</p>
[]
[ { "body": "<h3>Double-quote variables used as command line arguments</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>convert $1 -crop $2 \"two.png\"\n</code></pre>\n</blockquote>\n\n<p>Write like this:</p>\n\n<pre><code>convert \"$1\" -crop \"$2\" \"two.png\"\n</code></pre>\n\n<p>This is to protect from word splitting and glob expansion.</p>\n\n<h3>Double quote... naturally</h3>\n\n<p>This is hard to read and confusing:</p>\n\n<blockquote>\n<pre><code>Final=$One\"X\"$Two\"+\"$Three\"+\"$Four\n</code></pre>\n</blockquote>\n\n<p>I suggest to write like this:</p>\n\n<pre><code>Final=\"${One}X$Two+$Three+$Four\"\n</code></pre>\n\n<h3>Use better variable names</h3>\n\n<p>It's really hard to make sense of a program that uses variable names like <code>First</code>, <code>Fourth</code>, <code>Second</code>, <code>Lhs</code>, that don't reveal their purpose.</p>\n\n<p>Also, the convention is to use lowercase names, without capitalizing the first letters.</p>\n\n<h3>Chopping off characters case insensitively</h3>\n\n<p>Instead of detecting if the delimiter is <code>x</code> or <code>X</code> and storing it in a variable,\nyou could use the pattern <code>[xX]</code>, for example:</p>\n\n<pre><code>width=${spec%%[xX]*}\n</code></pre>\n\n<p>For example if you have <code>200x300</code> or <code>200X300</code> in <code>spec</code>, <code>width</code> becomes <code>200</code>.\n(Do take note of the meaningful names.)</p>\n\n<h3>Floating point math in the shell</h3>\n\n<p>Unfortunately Bash doesn't do floating point math.\nIt would give you a syntax error if you tried to multiply something by <code>1.5</code>.\nOn the other hand, if you want to multiply by <code>1.5</code>, and you don't mind truncating decimal points (as is the case here), you could multiply by 3 and divide by 2.</p>\n\n<p>That is, instead of this:</p>\n\n<pre><code>width=$(bc &lt;&lt;&lt; \"$width * 1.5\")\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>((width = width * 3 / 2))\n</code></pre>\n\n<h3>Use here strings</h3>\n\n<p>Instead of <code>echo ... | cmd</code>, write <code>cmd &lt;&lt;&lt; \"...\"</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:59:35.393", "Id": "413747", "Score": "2", "body": "An alternative approach to matching `[xX]` would be to first downcase the string with expansion: `newSize=\"${2,,}\"; width=\"${newSize%%x*}\"` etc." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:54:41.433", "Id": "213906", "ParentId": "213895", "Score": "2" } } ]
{ "AcceptedAnswerId": "213906", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T15:57:34.460", "Id": "213895", "Score": "1", "Tags": [ "image", "bash" ], "Title": "Bash function to produce variants of images at 2X and 3X resolutions" }
213895
<p>I'm looking at implementing the basic functional not-quite-Eratosthenes prime stream in Rust. I like to try it when I start learning a language.</p> <p>Here's the bog standard Haskell version:</p> <pre class="lang-hs prettyprint-override"><code>primes :: [Integer] primes = sieve (2 : [3, 5..]) where sieve (p:xs) = p : sieve [x|x &lt;- xs, x `mod` p /= 0] </code></pre> <p>in Rust, I think a reasonable transliteration is something like:</p> <pre><code>struct Primes { iter: Option&lt;Box&lt;Iterator&lt;Item=u32&gt;&gt;&gt; } impl Iterator for Primes { type Item = u32; fn next(&amp;mut self) -&gt; Option&lt;&lt;Self as Iterator&gt;::Item&gt; { let mut iter = self.iter.take().unwrap(); let res = iter.next().unwrap(); self.iter = Some(Box::new(iter.filter( move |x| x % res != 0))); Some(res) } } fn main() { let primes = Primes { iter: Some(Box::new(2..)) }; for p in primes.take(20) { println!("{}", p); } } </code></pre> <p>Leaving aside the algorithm (of course there are nicer ways to do primes!), this feels a bit verbose - is there a simpler way to construct an iterator with accumulating filters? The <code>Option</code> of <code>Box</code> feels quite clunky, but if I understand right, that's the best way to replace a field on <code>self</code>. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:07:53.737", "Id": "413733", "Score": "0", "body": "*not-quite-Eratosthenes* — thank you for recognizing that it's not actually the Sieve of Eratosthenes. It's a subtle thing." } ]
[ { "body": "<p>On a first note, your code will panic once your iterator reaches <code>std::u32::MAX</code>, which admittedly would take a long time. You can fix this by returning <code>None</code> when this happens, which can be done easily with <code>?</code>.</p>\n\n<pre><code>let mut iter = self.iter.take()?;\nlet res = iter.next()?;\n</code></pre>\n\n<p>I can't think of a better way to accumulate actual <code>filter</code> calls, but if I were to implement this sort of algorithm, I would probably do something like this instead:</p>\n\n<pre><code>struct Primes {\n found: Vec&lt;u32&gt;,\n iter: std::ops::RangeFrom&lt;u32&gt;,\n}\n\nimpl Primes {\n fn new() -&gt; Self {\n Primes {\n found: Vec::new(),\n iter: (2..),\n }\n }\n}\n\nimpl Iterator for Primes {\n type Item = u32;\n\n fn next(&amp;mut self) -&gt; Option&lt;&lt;Self as Iterator&gt;::Item&gt; {\n let Primes { found, iter } = self;\n let res = iter.find(|x| found.iter().all(|p| x % p != 0))?;\n found.push(res);\n Some(res)\n }\n}\n</code></pre>\n\n<p>Note that in your code, all the previous primes are stored in the closures, so doing it explicitly this way gives a better view of the costs of this method. Additionally, I can imagine the continuously nested dynamic dispatch adding up in costs, so this method removes any need for that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T03:45:50.680", "Id": "214000", "ParentId": "213902", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T17:50:40.667", "Id": "213902", "Score": "4", "Tags": [ "beginner", "primes", "rust", "iterator" ], "Title": "Rust version of basic functional prime stream - can this be made less clunky?" }
213902
<p>I'm working on requirement that involves creating a N x N table of blocks, with each block having a weight.</p> <p>Consider the following classes</p> <ul> <li><code>Block</code> - The fundamental unit of the table, having a weight</li> <li><code>RowBlock</code> - A set of blocks that join together one row</li> <li><code>BlockTable</code> - A set of rows that join together to form the table</li> </ul> <p>The program simulates inserting one block at a time to form the table altogether.</p> <p>I know it is <em>not</em> a C++ thing to play around with pointers but rather use <code>const</code> references, but again this is part of a bigger problem that we are trying to solve.</p> <p>This below code seems to work for now. But I'm a novice C++ programmer, want to know the potential pitfalls/vulnerabilities in the code</p> <pre><code>#include &lt;iostream&gt; #include &lt;utility&gt; #include &lt;stdint.h&gt; #include &lt;cstdlib&gt; #include &lt;map&gt; class Block { private: int m_value; public: Block(int value) { m_value = value; } void setvalue(int value); int getvalue(); }; class RowBlock { private: std::map&lt;int, Block*&gt; m_rowBlock; public: RowBlock() = default; void insertBlock(Block* newBlock); const std::map&lt;int, Block*&gt; getList(); }; class BlockTable { private: std::map&lt;int, RowBlock*&gt; m_BlockTable; public: BlockTable() = default; ~BlockTable(); void insertBlockRow(Block* newBlock); const std::map&lt;int, RowBlock*&gt; getList(); }; int Block::getvalue(void) { return(m_value); } void RowBlock::insertBlock(Block* newBlock) { m_rowBlock.emplace(newBlock-&gt;getvalue(), newBlock); } void BlockTable::insertBlockRow(Block* newBlock) { std::map &lt;int, RowBlock*&gt;::iterator iter; RowBlock *localRowBlock = NULL; iter = m_BlockTable.find( newBlock-&gt;getvalue() ); if( iter == m_BlockTable.end() ) { localRowBlock = new RowBlock; localRowBlock-&gt;insertBlock(newBlock); m_BlockTable.emplace(newBlock-&gt;getvalue(), localRowBlock); } else { localRowBlock = iter-&gt;second; localRowBlock-&gt;insertBlock(newBlock); m_BlockTable.emplace(newBlock-&gt;getvalue(), localRowBlock); } } const std::map&lt;int, RowBlock*&gt; BlockTable::getList() { return m_BlockTable; } const std::map&lt;int, Block*&gt; RowBlock::getList() { return m_rowBlock; } BlockTable::~BlockTable() { std::map&lt;int, Block*&gt;::iterator iter_1; std::map&lt;int, RowBlock*&gt;::iterator iter_2; std::map &lt;int, RowBlock*&gt; tmpList_1 = getList(); std::map &lt;int, Block*&gt; tmpList_2; for ( iter_2 = tmpList_1.begin(); iter_2 != tmpList_1.end(); iter_2++ ) { tmpList_2 = iter_2-&gt;second-&gt;getList(); for ( iter_1 = tmpList_2.begin(); iter_1 != tmpList_2.end(); iter_1++ ) delete iter_1-&gt;second; delete iter_2-&gt;second; } } int main() { BlockTable newBlockTable; for (auto i=1; i&lt;=5; i++) { Block *newBlock = new Block(i*10); newBlockTable.insertBlockRow( newBlock ); } std::map&lt;int, Block*&gt;::iterator iter_1; std::map&lt;int, RowBlock*&gt;::iterator iter_2; std::map &lt;int, RowBlock*&gt; tmpList_1 = newBlockTable.getList(); std::map &lt;int, Block*&gt; tmpList_2; for ( iter_2 = tmpList_1.begin(); iter_2 != tmpList_1.end(); iter_2++ ) { tmpList_2 = iter_2-&gt;second-&gt;getList(); for ( iter_1 = tmpList_2.begin(); iter_1 != tmpList_2.end(); iter_1++ ) printf("%d\n", iter_1-&gt;second-&gt;getvalue()); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:40:17.267", "Id": "413744", "Score": "1", "body": "It would be great to show application of general solution on a specific problem. General solution usually implies coping with weird inputs and situations, not Foo's and Bar's. As it stands now, the post is off-topic due to lacking context. The code seems to use C style programming. There should be a way to flatten inner level or better aggregate keys and values, but unfortunately I'm not sure about relationship between inner and outer levels of the structure. Applying the design approach on a more realistic problem might help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:57:10.517", "Id": "413746", "Score": "0", "body": "that and renaming symbols into something at least remotely real would make it on-topic. I see that this is a genuine problem, but am failing to understand what it asks. There was a meta post about why Foo and Bar questions are off-topic, but I am failing to find the link." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T19:06:19.793", "Id": "413750", "Score": "1", "body": "perhaps it was [this meta answer](https://codereview.meta.stackexchange.com/a/3652/120114), which includes a link to [_Why is hypothetical example code off-topic for Code Review?_](https://codereview.meta.stackexchange.com/q/1709/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T19:49:52.067", "Id": "413757", "Score": "0", "body": "@Incomputable: I've made a reasonable edit. Do let me know if its answerable now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T19:50:01.530", "Id": "413758", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ: I've made a reasonable edit. Do let me know if its answerable now." } ]
[ { "body": "<h1>General improvements</h1>\n\n<h2>Names</h2>\n\n<p>C++ member and variable declarations don't tell you the type of an object; they tell you what operations on it are legal. Prefer <code>Block *newBlock</code> (object dereferenceable to value of type <code>Block</code>) to <code>Block* newBlock</code>; the latter will only confuse you. </p>\n\n<p>Tradition is to use all lowercase and separate words with underscores, but your naming convention is fine too. </p>\n\n<h2>Do you really mean \"table\"?</h2>\n\n<p>Technically, what you've written here is not a table, but closer to a <em>jagged array</em>. You have no compile-time constraints forcing the members of each row to be of the same length, so you could have a table looking like this:\n<img src=\"https://www.baeldung.com/wp-content/uploads/2018/06/JaggedArray1.png\" alt=\"A jagged array named &lt;code&gt;jaggedArr&lt;/code&gt;, pointing to three memory blocks label &quot;0&quot;, &quot;1&quot;, and &quot;2&quot;, each themselves pointing to memory blocks labeled &quot;1&quot; and &quot;2&quot;; &quot;3&quot;, &quot;4&quot;, and &quot;5&quot;; and &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, and &quot;9&quot; (respectively).\"></p>\n\n<p>This image was pulled off the internet; the naming convention doesn't quite match your code.</p>\n\n<p>Do you mean that to be the case? </p>\n\n<p>It's not just the varying row lengths that's strange. Because each row is a <code>map</code> to the <em>values</em> of each block, the idea of each block having a fixed index is wrong. In short, make sure your data structure matches your mental image of it. </p>\n\n<p>Finally, if you do want each block to have a fixed index and you want a rectangular table, I wouldn't bother with an intermediate data type <code>RowBlock</code>. Instead, I would just have <code>BlockTable</code> manage the row/column distinction directly. This also allows you to <em>flatten</em> your table, if performance demands: instead of <code>n</code> different rows of length <code>n</code>, you have a single array of length <code>n*n</code>. What consumers of your class call the <code>(r,c)</code>th element is then internally at index <code>n*r+c</code>. This reduces memory fragmentation. I'm not going to flatten your tables for you, but it is something to consider. </p>\n\n<h2>Memory management</h2>\n\n<blockquote>\n <p>I know it is not a C++ thing to play around with pointers but rather use const references, but again this is part of a bigger problem that we are trying to solve.</p>\n</blockquote>\n\n<p>No! The important thing is to be aware of the lifetime of your memory and ensure that your code architecture manages it correctly. If you need mutable references, or just to allow <code>nullptr</code> sentinels, then pointers are the way to go. </p>\n\n<p>Better still are the stdlib's <em>smart pointers</em>; choose <code>std::unique_ptr</code> or <code>std::shared_ptr</code> as appropriate. </p>\n\n<p>A usual way to handle this is to assume that the lifetime of each block and row should be the lifetime of the enclosing row and table, respectively. If a consumer wants to preserve data beyond that time, they'll need to copy or <code>swap</code> it away. </p>\n\n<p>For example, you have lines like this: </p>\n\n<pre><code>const std::map&lt;int, Block*&gt; getList();\n</code></pre>\n\n<p><em>Never</em> return large objects (like <code>std::map</code>) by value, if you can avoid it. </p>\n\n<pre><code>const std::map&lt;int, Block*&gt; &amp;getList() const;\n</code></pre>\n\n<p>is better (and const-correct). </p>\n\n<h2>RAII</h2>\n\n<p>It should be hard to create your objects without initializing them. (Ideally, it should be <em>impossible</em>, but for some of your objects, induces undue performance limitations, so you'll have to trust your coworkers.) This means you should support brace-initializion and swapping objects, so you don't need to create them twice. For example, <code>BlockTable</code> should have lines looking something like this:</p>\n\n<pre><code>public:\n BlockTable() = default;\n BlockTable(std::initializer_list&lt;std::pair&lt;int,RowBlock&gt;&gt; &amp;&amp;elems) : \n m_BlockTable(elems)\n {}\n template&lt;typename T&gt;\n BlockTable(T start, T end) :\n m_BlockTable(start, end)\n {}\n friend std::swap&lt;BlockTable&gt;(BlockTable &amp;&amp;left, BlockTable &amp;&amp;right);\n</code></pre>\n\n<p>If you manage memory properly, using smart pointers, etc., your destructors should be trivial. The long and complex ones you've written are a code smell. </p>\n\n<h2>Const-correctness</h2>\n\n<p>Your classes offer almost no support for const-correctness. Make sure to mark procedures that do not mutate as such! A consumer of your class who cares about const-correctness will have fits if you don't. </p>\n\n<h2>ABI?</h2>\n\n<p>You may want variants of these classes for different sizes of integers, i.e. <code>long long int</code>, <code>short int</code>. The easy way to do this uses templates, but then compile-time constraints can be hidden by typos, and you do not have a consistent binary layout across compilers. I'm going to assume that you specialized to <code>int</code> on purpose; the templated version is not much more than a find-and-replace if done correctly. </p>\n\n<h2>Synchronization</h2>\n\n<p>C++ is no longer a single-threaded language, but most code is still written that way. I assume you externally synchronize any accesses to <code>BlockTable</code> objects in multithreaded contexts, in which case there is no problem. </p>\n\n<h2>I/O</h2>\n\n<p>C-style I/O (i.e. <code>printf</code>) has been superseded by <code>&lt;iostream&gt;</code>. Prefer that, but if you aren't taking user input or writing anything complicated out, it doesn't matter too much. </p>\n\n<h2>MWE</h2>\n\n<p>You forgot to define <code>Block::setvalue</code>. Did you mean</p>\n\n<pre><code>void Block::setvalue(int value)\n{\n m_value=value;\n}\n</code></pre>\n\n<p>perchance? This also shows that your test suite (which appears to be <code>main</code>) is woefully incomplete. Make sure the data structure behaves sanely with regard to inserted, non-random values! </p>\n\n<h2>Other stylistic tips</h2>\n\n<p><code>auto</code> is your friend. Use it. </p>\n\n<p>The <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based for</a> is your friend too. Use that. </p>\n\n<p>If you have to manipulate iterators by hand, prefer <code>++iter</code>. <code>iter++</code> requires the iterator to spend a lot of effort copying itself, only for the old version to get promptly thrown away. </p>\n\n<h1>Specific rewriting</h1>\n\n<p>I don't understand the exact purpose of your data structure; the <code>map</code>s don't seem to do what your documentation in the question describes. So I can't tell you how to make <code>main</code> more informative. But <em>even without understanding the most important semantics of your code</em>, I can tell you that, if you can add a few constructors and automatic memory management to your data structures so that the following mechanical rewriting of <code>main</code> is correct, your code will be better. </p>\n\n<pre><code>void main()\n{\n BlockTable newBlockTable;\n for (auto const i : {1, 2, 3, 4, 5})\n {\n newBlockTable.insertBlockRow(Block(i * 10));\n //or better:\n //newBlockTable.insertBlockRow({i * 10});\n //or maybe even:\n //newBlockTable.insertBlockRow(i * 10);\n }\n //or best of all:\n //BlockTable const newBlockTable{10, 20, 30, 40, 50};\n\n //The names of your variables were too uninformative; I've changed them\n auto const &amp;row_map{newBlockTable.getList()}; //No need for complicated iterator types! \n for (auto const &amp;key_and_row : row_map)\n {\n auto const &amp;block_map{key_and_row.second-&gt;getList()};\n for (auto const &amp;key_and_block : block_map)\n printf(\"%d\\n\", key_and_block.second-&gt;getvalue());\n }\n //If you aren't going to return anything but success, don't bother returning a value. \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:37:49.037", "Id": "213923", "ParentId": "213904", "Score": "4" } }, { "body": "<p>Why is <code>Block</code> a class? It seems to have a single - effectively public - member, (which you described as <code>weight</code> but then gave the much less meaningful name of <code>m_value</code>), so it could simply be replaced by a plain <code>int</code>.</p>\n\n<p>To use <code>printf()</code>, we need to include <code>&lt;cstdio&gt;</code> (and name it properly: <code>std::printf()</code>). Prefer C++ headers to C headers (<code>&lt;cstdint&gt;</code> rather than <code>&lt;stdint.h&gt;</code> - or just remove that include, since it's never used).</p>\n\n<p>Prefer to use smart pointers and containers to manage ownership and simplify your memory management. When <code>new</code> and/or <code>new[]</code> are unavoidable, then make sure you exercise your tests under a memory checker such as Valgrind.</p>\n\n<p>Prefer initialisers to assignment (compiler warnings should help you avoid uninitialized members):</p>\n\n<pre><code> Block(int value)\n : m_value{value}\n {\n }\n</code></pre>\n\n<p>And everything that other reviewers have mentioned.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:59:30.637", "Id": "213949", "ParentId": "213904", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T18:09:17.283", "Id": "213904", "Score": "1", "Tags": [ "c++", "beginner", "c++11" ], "Title": "Inserting an object pointer to a two-level map" }
213904
<h2>Function getMarkets</h2> <p>Makes a call to get Cryptocurrency Exchange data based on asset (USD, USDC, USDT)</p> <p>It calls the endpoint 3 times to return 3 arrays which are then returned to the callee.</p> <p><a href="https://i.stack.imgur.com/SgiQ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SgiQ8.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/QS16Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QS16Y.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/sGXoy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sGXoy.png" alt="enter image description here"></a></p> <hr> <p>I have an endpoint which hits gets <code>exchange-markets/prices</code> for any asset.</p> <p>In my case I need to check all the paired cryptocurrency listings for <code>USD</code>, <code>USDC</code> and <code>USDT</code>.</p> <p>At first I just tried calling getMarkets 3 times passing in the currency each time. I would then get an array of 3 responses from each call, however the last call would always replace the data for the 2 previous calls.</p> <p>In order to fix that I had to use this ugly <code>if</code> statement indentation hell... which defeats the purpose of using <code>async await</code>. How should this be refactored to be cleaner, or is there a better way?</p> <pre><code>const nomicsAPI = 'https://api.nomics.com/v1/'; const nomicsKey = '8feb...;' interface IParams { key: string; currency?: string; } interface IHeaders { baseURL: string, params: IParams } const headers: IHeaders = { baseURL: nomicsAPI, params: { key: nomicsKey } }; const prepHeaders = (currency: string) =&gt; { headers.params.currency = currency; return axios.create(headers); }; </code></pre> <hr> <pre><code>export const getMarkets = async (): Promise&lt;any&gt; =&gt; { try { let marketUSD; let marketUSDC; let marketUSDT; const nomicsUSD = prepHeaders('USD'); marketUSD = await nomicsUSD.get('exchange-markets/prices'); if (marketUSD) { const nomicsUSDC = prepHeaders('USDC'); marketUSDC = await nomicsUSDC.get('exchange-markets/prices'); if (marketUSDC) { const nomicsUSDT = prepHeaders('USDT'); marketUSDT = await nomicsUSDT.get('exchange-markets/prices'); return { marketUSD: marketUSD.data, marketUSDC: marketUSDC.data, marketUSDT: marketUSDT.data } } } else { throw new Error('USD Markets unavailable.'); } } catch (err) { console.error(err); } } </code></pre> <p>^ above produces the desired results:</p> <p><a href="https://i.stack.imgur.com/tqy5l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tqy5l.png" alt="enter image description here"></a></p> <hr> <p>And the actions file where this function is called from:</p> <pre><code>// Fetch USD, USDC &amp; USDT markets to filter out Exchange List. export const fetchMarketPrices = (asset: string) =&gt; (dispatch: any) =&gt; getMarkets().then((res) =&gt; { console.log('res', res); // const combinedExchanges = res[0].data.concat(res[1].data).concat(res[2].data); // console.log('combinedExchanges', combinedExchanges); // const exchangesForAsset = combinedExchanges.filter((marketAsset: IMarketAsset) =&gt; // marketAsset.base === asset); // console.log('exchangesForAsset', exchangesForAsset); // return dispatch(actionGetMarketPrices(exchangesForAsset)); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T20:05:47.827", "Id": "413762", "Score": "1", "body": "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://$SITEURL$/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." } ]
[ { "body": "<p>Improved code:</p>\n\n<p>The problem was that the headers object needed to be updated before each new <code>await</code>. This separated the calls into 3 different calls.</p>\n\n<p>When I had the all the header objects created before the <code>awaits</code> they all took the last header object created.</p>\n\n<p>Now the code can be re-written in a synchronous way and <code>if statements</code> can be avoided. </p>\n\n<pre><code>export const getMarkets = async (): Promise&lt;any&gt; =&gt; {\n try {\n const nomicsUSD = prepHeaders('USD');\n const marketUSD = await nomicsUSD.get(exchangeMarketPrices);\n const nomicsUSDC = prepHeaders('USDC');\n const marketUSDC = await nomicsUSDC.get(exchangeMarketPrices);\n const nomicsUSDT = prepHeaders('USDT');\n const marketUSDT = await nomicsUSDT.get(exchangeMarketPrices);\n\n return {\n marketUSD: marketUSD.data,\n marketUSDC: marketUSDC.data,\n marketUSDT: marketUSDT.data\n }\n } catch (err) {\n console.error(err);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T05:59:39.493", "Id": "213933", "ParentId": "213909", "Score": "-1" } }, { "body": "<p>A common convention used in TypeScript/Javascript and other C-based languages is to use all uppercase letters for constants. This makes it easy to spot values that cannot be changed. </p>\n\n<p>So instead of lowercase constants:</p>\n\n<blockquote>\n<pre><code>const nomicsAPI = 'https://api.nomics.com/v1/';\nconst nomicsKey = '8feb...;'\n</code></pre>\n</blockquote>\n\n<p>make them uppercase. The naming also could be improved - e.g. <code>NOMICS_API_BASE_URL</code> would better describe that the value is the base URL of the API than <code>NOMICS_API</code>.</p>\n\n<pre><code>const NOMICS_API_BASE_URL = 'https://api.nomics.com/v1/';\nconst NOMICS_KEY = '8feb...;' \n</code></pre>\n\n<p>You could also consider using the <a href=\"https://github.com/Microsoft/TypeScript/pull/6532\" rel=\"nofollow noreferrer\"><code>readonly</code></a> modifier with those constants.</p>\n\n<hr>\n\n<p>This code (as well as the updated code in your self-answer) is quite repetitive. It would be wise to abstract the common code. That way if something needs to be updated, it can be done in one place. This adheres to the <strong><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\"><em>Don't Repeat Yourself</em></a></strong>\n (i.e. D.R.Y.) principle.</p>\n\n<p>I would first recommend storing each currency in an array:</p>\n\n<pre><code>const currencies = ['USD', 'USDC', 'USDT']; \n</code></pre>\n\n<p>And abstract out the common code of making the request and throwing an error if the request fails: </p>\n\n<pre><code>const getCurrencyPrice = async (currency) =&gt; {\n try {\n const request = prepHeaders(currency);\n const response = await request.get(NOMICS_PRICES_ENDPOINT);\n if (!response) {\n throw new Error('USD Markets unavailable.');\n }\n return response.data;\n }\n catch(err) {\n console.error(err);\n }\n};\n</code></pre>\n\n<p>That way if any of the requests fail, the Error will be thrown immediately. Also, this function has one job and could easily lend itself to unit testing. </p>\n\n<p>Then use that function to iterate over the array of currencies - optionally with a <code>for...of</code> loop, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce()</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>Array.prototype.forEach()</code></a>, etc</p>\n\n<pre><code>const getMarkets = async _ =&gt; {\n const returnObj = {};\n for (let currency of currencies) {\n const key = 'market' + currency;\n returnObj[key] = await getCurrencyPrice(currency);\n }\n return returnObj;\n}; \n</code></pre>\n\n<p>Notice that the code above uses a new constant - <code>NOMICS_PRICES_ENDPOINT</code> - this can be defined with the other constants:</p>\n\n<pre><code>const NOMICS_PRICES_ENDPOINT = 'exchange-markets/prices';\n</code></pre>\n\n<p>That way if the endpoint needs to be updated, in can be done in one place. Additionally, if the constants were stored in a separate file, you wouldn't need to alter the file that contains all of this code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T03:42:34.313", "Id": "413932", "Score": "0", "body": "So clean! :D thanks for the tips and design pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T19:26:04.580", "Id": "213984", "ParentId": "213909", "Score": "1" } } ]
{ "AcceptedAnswerId": "213984", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T19:54:57.627", "Id": "213909", "Score": "1", "Tags": [ "async-await", "promise", "typescript" ], "Title": "Get an array of currency exchange prices based on asset" }
213909
<p>Help me with code code review. Helium is my pet project, written in Golang. Helium is a small, simple, modular constructor with some pre-built components.</p> <p><a href="https://github.com/im-kulikov/helium" rel="nofollow noreferrer">https://github.com/im-kulikov/helium</a></p> <p>Simple example how to use it </p> <pre><code>package main import ( "context" "github.com/davecgh/go-spew/spew" "github.com/im-kulikov/helium" "github.com/im-kulikov/helium/grace" "github.com/im-kulikov/helium/logger" "github.com/im-kulikov/helium/module" "github.com/im-kulikov/helium/settings" "github.com/spf13/viper" ) var mod = module.New(newApp). Append( settings.Module, logger.Module, grace.Module) // App struct type App struct { v *viper.Viper } func newApp(v *viper.Viper) helium.App { return &amp;App{v: v} } // Run application func (a App) Run(ctx context.Context) error { spew.Dump(a.v.AllSettings()) return nil } func main() { h, err := helium.New(&amp;helium.Settings{ Prefix: "demo", Name: "demo", BuildTime: "now", BuildVersion: "dev", }, mod) helium.Catch(err) helium.Catch(h.Run()) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-04T13:16:17.187", "Id": "415182", "Score": "2", "body": "\"Helium is a small, simple, modular constructor\" – Excuse my ignorance, but *what* does it construct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-05T16:08:46.690", "Id": "415343", "Score": "0", "body": "It’s provide simple way to build application in simple ways.. or make fast prototype of feature application.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-31T17:19:50.213", "Id": "418985", "Score": "0", "body": "If you want Helium to be reviewed, you'll have to copy the content of it to the actual question. Embed it directly. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>A little detail; in <code>Run</code>:</p>\n\n<pre><code>// Run application\nfunc (a App) Run(ctx context.Context) error {\n spew.Dump(a.v.AllSettings())\n\n return nil\n}\n</code></pre>\n\n<p><code>error</code> will be always null. \nAnd according <a href=\"https://godoc.org/github.com/davecgh/go-spew/spew#Dump\" rel=\"nofollow noreferrer\">go-spew/spew#Dump</a>;</p>\n\n<blockquote>\n <p><code>func Dump(a ...interface{})</code></p>\n</blockquote>\n\n<p><code>Dump</code> doesn't return a thing.\nSo seems like you should be able to a.- remove <code>error</code>from your signature, or b.- do some sanity check on <code>a.v</code> to see, for example, that those elements are not nil/etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-28T14:07:10.320", "Id": "414735", "Score": "0", "body": "That may be true fror this particular implementation, `spew.Dump`, but it is not necessarily true for all implementations. Therefore, it is not a good idea. Keep the general API form and return `error`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-28T15:22:44.880", "Id": "414756", "Score": "0", "body": "I see! should be better then add some sanity checks? and when you say 'general api form' do you know if there is a specification, design or something about that? (it makes sense, but it bothers me a little bit the error always being nil :D). thanks for your time, btw." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-05T16:04:30.547", "Id": "415341", "Score": "0", "body": "That’s was just an example.. in other ways in run can be errors" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-27T23:58:45.523", "Id": "214431", "ParentId": "213915", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T21:35:43.480", "Id": "213915", "Score": "2", "Tags": [ "go" ], "Title": "Helium written in Go" }
213915
<p>I'm wondering if this is a kind of useful way to go about implementing a well performing and generally simple pair type or is it just plain stupid?</p> <p>By 'simple', I mean in the sense that it's just plain data, no complicated C++ error diagnostics for random stuff (e.g. this is default construct-able regardless of that T1 or T2 is).</p> <p>If you could comment on the following that would be great:</p> <ul> <li>Separating memory from its type </li> <li>Using <code>emplace</code> to avoid an unnecessary copy </li> <li>Verbose interface for the sake of being explicit</li> </ul> <p><strong>Note:</strong> I'm already aware this isn't safe, and that you could end up trying to access an attribute that hasn't been constructed.</p> <pre><code>#ifndef PAIR_H #define PAIR_H #define ANAGAMI_DEBUG #ifdef ANAGAMI_DEBUG #include &lt;fmt/format.h&gt; #include &lt;cstdio&gt; #endif #include &lt;utility&gt; namespace kpl { template &lt;typename T1, typename T2&gt; class Pair { public: Pair() : mStateInfo { 0b00000000 } { } /* Move based constructor */ Pair(T1&amp;&amp; t1, T2&amp;&amp; t2) : mStateInfo { FIRST_CONSTRUCTED &amp; SECOND_CONSTRUCTED } { new ( reinterpret_cast&lt;void*&gt;( mFirstMemBlock) ) T1( std::move(t1) ); new ( reinterpret_cast&lt;void*&gt;( mSecondMemBlock) ) T2( std::move(t2) ); } /* Value based constructor */ Pair(const T1&amp; t1, const T2&amp; t2) : mStateInfo { FIRST_CONSTRUCTED &amp; SECOND_CONSTRUCTED } { new ( reinterpret_cast&lt;void*&gt;( mFirstMemBlock) ) T1( t1 ); new ( reinterpret_cast&lt;void*&gt;( mSecondMemBlock) ) T2( t2 ); } void setT1WithCopy(const T1&amp; t1) { new ( reinterpret_cast&lt;void*&gt;( mFirstMemBlock) ) T1( t1 ); } void setT2WithCopy(const T2&amp; t2) { new ( reinterpret_cast&lt;void*&gt;( mSecondMemBlock) ) T2( t2 ); } void setT1WithMove(T1&amp;&amp; t1) { new ( reinterpret_cast&lt;void*&gt;( mFirstMemBlock) ) T1( std::move(t1) ); } void setT2WithMove(T2&amp;&amp; t2) { new ( reinterpret_cast&lt;void*&gt;( mSecondMemBlock) ) T2( std::move(t2) ); } template &lt;typename... Ts&gt; void emplaceT1(Ts&amp;&amp;... args) { new ( reinterpret_cast&lt;void*&gt;( mFirstMemBlock ) ) T1( static_cast&lt;Ts&amp;&amp;&gt;(args)... ); } template &lt;typename... Ts&gt; void emplaceT2(Ts&amp;&amp;... args) { new ( reinterpret_cast&lt;void*&gt;( mSecondMemBlock ) ) T2( static_cast&lt;Ts&amp;&amp;&gt;(args)... ); } /* Getters mFirst */ const T1 * cPtr1() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; FIRST_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; FIRST_CONSTRUCTED); } #endif return reinterpret_cast&lt;const T1 *&gt;(mFirstMemBlock); } T1 * ptr1() { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; FIRST_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; FIRST_CONSTRUCTED); } #endif return reinterpret_cast&lt;T1 *&gt;(mFirstMemBlock); } T1 t1() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; FIRST_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; FIRST_CONSTRUCTED); } #endif return *(reinterpret_cast&lt;T1*&gt;(mFirstMemBlock)); } const T1 cT1() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; FIRST_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; FIRST_CONSTRUCTED); } #endif return *(reinterpret_cast&lt;const T1*&gt;(mFirstMemBlock)); } /* Getters mSecond */ const T2 * cPtr2() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; SECOND_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; SECOND_CONSTRUCTED); } #endif return reinterpret_cast&lt;const T2 *&gt;(mSecondMemBlock); } T2 * ptr2() { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; SECOND_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; SECOND_CONSTRUCTED); } #endif return reinterpret_cast&lt;T2 *&gt;(mSecondMemBlock); } T2 t2() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; SECOND_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; SECOND_CONSTRUCTED); } #endif return *(reinterpret_cast&lt;T2*&gt;(mSecondMemBlock)); } const T2 cT2() const { #ifdef ANAGAMI_DEBUG if(! (mStateInfo &amp; SECOND_CONSTRUCTED) ) { fmt::print(stderr, "Error: Trying to access unconstructed value in kpl::Pair" ); assert(mStateInfo &amp; SECOND_CONSTRUCTED); } #endif return *(reinterpret_cast&lt;const T2*&gt;(mSecondMemBlock)); } private: static constexpr uint8_t FIRST_CONSTRUCTED = 0b10000000; static constexpr uint8_t SECOND_CONSTRUCTED = 0b01000000; uint8_t mFirstMemBlock[ sizeof(T1) ]; uint8_t mSecondMemBlock[ sizeof(T2) ]; uint8_t mStateInfo; }; } #endif // PAIR_H </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T22:04:55.480", "Id": "413772", "Score": "5", "body": "How is this different from [`std::pair`](https://en.cppreference.com/w/cpp/utility/pair)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T22:32:04.080", "Id": "413775", "Score": "0", "body": "Well for one, lets say one of your types doesn't have a default constructor. You wouldn't be able to default construct the pair, or use it as the template type for any container that requires it's elements to have default constructors for internal reasons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:59:04.197", "Id": "413780", "Score": "0", "body": "To maybe a little more clear, what problem is your `Pair` attempting to solve that can't be done with `std::pair`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T00:57:50.163", "Id": "413783", "Score": "0", "body": "There are several bugs in the code. They're not blatantly obvious when looking over the code, but some of them would be apparent with even minimal testing. Test your code, fix the problems, then post the corrected code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T12:13:14.353", "Id": "413843", "Score": "0", "body": "Ok guys, sorry for the question! I don't really use the site and just came to me that it might be interesting to see what people thought of it. No, I haven't tested it, I'm still not sure whether I'd use it, I was more just referring to the general design but I can see how it's annoying to have someone ask about code that hasn't been tested properly!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T21:52:27.337", "Id": "213917", "Score": "0", "Tags": [ "c++" ], "Title": "C++ Pair Data structure" }
213917
<p>I am developing a simple taskbar for X11 using the Athena widgets. The current code is very limited: it assumes an EWMH-compliant window manager and only adds the initially running windows to the taskbar. Here is a screenshot:</p> <p><img src="https://i.stack.imgur.com/BgIsm.png" alt="screenshot"></p> <p>The program depends on the libX11, libXt and libXaw development packages. It can be compiled with:</p> <pre><code>gcc `pkg-config --cflags --libs x11 xaw7` -o xpanel xpanel.c </code></pre> <h1>xpanel.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;locale.h&gt; #include &lt;X11/Intrinsic.h&gt; #include &lt;X11/Shell.h&gt; #include &lt;X11/StringDefs.h&gt; #include &lt;X11/Xaw/Box.h&gt; #include &lt;X11/Xaw/Command.h&gt; #include &lt;X11/Xatom.h&gt; /* used as return values for functions */ enum status { SUCCESS, FAILURE }; static char *atom_names[] = { "WM_DELETE_WINDOW", "_NET_CLIENT_LIST", "_NET_WM_NAME", }; enum { WM_DELETE_WINDOW, NET_CLIENT_LIST, NET_WM_NAME, ATOM_COUNT }; /* the X server variables are kept in a global struct */ struct app_data { Display *display; XtAppContext app_context; Widget app_shell; Window root_window; Atom atoms[ATOM_COUNT]; Window main_window; }; struct app_data app_data; /* the tasks (application windows) are organized as a linked list of structs */ struct task { struct task *next_task; Window window; char *title; Widget button; }; struct task_list { struct task *first_task; struct task *last_task; }; /* this gets the list of currently open application windows */ enum status get_window_list(Window **window_list, long unsigned int *window_count) { Atom actual_type; int item_size; unsigned long leftover_byte_count; /* max. size 256L: 256 x 4-byte multiples = 1 MB */ if (XGetWindowProperty(app_data.display, app_data.root_window, app_data.atoms[NET_CLIENT_LIST], 0L, 256L, False, XA_WINDOW, &amp;actual_type, &amp;item_size, window_count, &amp;leftover_byte_count, (unsigned char **) window_list) != Success || window_count == 0) { fputs("Could not get window list property.\n", stderr); return FAILURE; } return SUCCESS; } enum status get_window_title(Window window, char **window_title) { enum status return_code = FAILURE; XTextProperty text_property; char **text_list = NULL; if (XGetTextProperty(app_data.display, window, &amp;text_property, app_data.atoms[NET_WM_NAME]) == 0) { if (XGetWMName(app_data.display, window, &amp;text_property) == 0) { fputs("Could not get window title property.\n", stderr); goto out; } } /* the text property is converted to a text list to convert it to the encoding of the current locale */ int string_count = 0; XmbTextPropertyToTextList(app_data.display, &amp;text_property, &amp;text_list, &amp;string_count); size_t buffer_size = strlen(text_list[0]) + 1; *window_title = malloc(buffer_size); if (window_title == NULL) { perror("malloc"); goto out; } memcpy(*window_title, text_list[0], buffer_size); return_code = SUCCESS; out: XFree(text_property.value); XFreeStringList(text_list); return return_code; } void button_callback(Widget button, XtPointer client_data, XtPointer call_data) { XRaiseWindow(app_data.display, (Window) client_data); XSetInputFocus(app_data.display, (Window) client_data, RevertToParent, CurrentTime); } /* this fills the variables of a task struct */ void initialize_task(Widget taskbar, Window window, struct task *task) { task-&gt;window = window; char *window_title = NULL; if (get_window_title(window, &amp;window_title) == SUCCESS) { task-&gt;title = window_title; } else { task-&gt;title = "&lt;No Title&gt;"; } task-&gt;button = XtVaCreateWidget(NULL, commandWidgetClass, taskbar, XtNlabel, window_title, NULL); XtAddCallback(task-&gt;button, XtNcallback, button_callback, (XtPointer)window); } /* this appends a task struct to the linked list */ void append_task(struct task_list *task_list, struct task *task) { task-&gt;next_task = NULL; if (task_list-&gt;first_task == NULL) { // list is empty task_list-&gt;first_task = task_list-&gt;last_task = task; } else { task_list-&gt;last_task-&gt;next_task = task; task_list-&gt;last_task = task; } } /* this gets the list of currently running windows, creates a task struct including a button widget for each of them, appends the structs to the linked list and adds the buttons to the taskbar */ enum status initialize_task_list(Widget taskbar, struct task_list *task_list) { enum status return_code = FAILURE; Window *window_list; long unsigned int window_list_size; if (get_window_list(&amp;window_list, &amp;window_list_size) == FAILURE) { fputs("Could not get window list.\n", stderr); goto out; } /* the task buttons are collected in a dynamically resized array */ int button_array_capacity = 32; Widget *button_array = malloc(button_array_capacity * sizeof *button_array); if (button_array == NULL) { perror("malloc"); goto out; } for (int i = 0; i &lt; window_list_size; i++) { struct task *new_task = malloc(sizeof *new_task); if (new_task == NULL) { perror("malloc"); goto out; } initialize_task(taskbar, window_list[i], new_task); if(i == button_array_capacity) { button_array_capacity = button_array_capacity + (button_array_capacity &gt;&gt; 1); // growth factor = 1.5 Widget *new_button_array = realloc(button_array, button_array_capacity * sizeof *button_array); if (new_button_array == NULL) { perror("realloc"); goto out; } button_array = new_button_array; } button_array[i] = new_task-&gt;button; append_task(task_list, new_task); } XtManageChildren((Widget *) button_array, window_list_size); return_code = SUCCESS; out: XFree(window_list); free(button_array); return return_code; } /* this handles window manager events (at the moment only requests for deletion of our own window) */ void wm_event_handler(Widget widget, XtPointer client_data, XEvent *event, Boolean *continue_dispatch) { if ((event-&gt;type == ClientMessage) &amp;&amp; (event-&gt;xclient.data.l[0] == app_data.atoms[WM_DELETE_WINDOW])) { exit(EXIT_SUCCESS); } } void initialize_x11(struct app_data *app_data, int *argc, char **argv) { app_data-&gt;app_shell = XtVaOpenApplication(&amp;(app_data-&gt;app_context), "XPanel", NULL, 0, argc, argv, NULL, applicationShellWidgetClass, XtNwidth, 800, XtNheight, 50, NULL); app_data-&gt;display = XtDisplay(app_data-&gt;app_shell); app_data-&gt;root_window = DefaultRootWindow(app_data-&gt;display); XInternAtoms(app_data-&gt;display, atom_names, ATOM_COUNT, False, app_data-&gt;atoms); XtRealizeWidget(app_data-&gt;app_shell); app_data-&gt;main_window = XtWindow(app_data-&gt;app_shell); XSetWMProtocols(app_data-&gt;display, app_data-&gt;main_window, &amp;(app_data-&gt;atoms[WM_DELETE_WINDOW]), 1); XtAddEventHandler(app_data-&gt;app_shell, NoEventMask, True, &amp;wm_event_handler, NULL); } int main (int argc, char **argv) { setlocale (LC_ALL, ""); initialize_x11(&amp;app_data, &amp;argc, argv); Widget taskbar = XtVaCreateManagedWidget("taskbar", boxWidgetClass, app_data.app_shell, XtNorientation, XtorientHorizontal, NULL); struct task_list task_list = {0}; initialize_task_list(taskbar, &amp;task_list); XtAppMainLoop(app_data.app_context); return EXIT_SUCCESS; } </code></pre> <h1>Questions</h1> <p>I wonder whether it is a good idea to keep the X11 variables in a global struct. Without global variables, it would be necessary to pass a struct or several independent X11 variables through the nested functions <code>initialize_task_list</code>, <code>initialize_task</code>, <code>get_window_list</code>, <code>get_window_title</code> and <code>XtAddCallback</code>. As <code>XtAddCallback</code> accepts only a single pointer to user-defined data, I would also need an additional callback data struct to pass the <code>display</code> and <code>window</code> variables to the button callback procedure.</p> <p>What else do you think about my code? What could be improved? I appreciate any comments or suggestions!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T22:36:50.197", "Id": "213919", "Score": "4", "Tags": [ "c", "gui", "x11" ], "Title": "Taskbar for X11 using Athena widgets" }
213919
<p>I'd like to create directories on a remote VM, but only if they do not exist. What's more, if creating the directory results in an error (exit status != 0) I'd like the script to exit as well, or at least print an error. Is there a more succinct way to do this than what I have below? </p> <p>UPDATE: Just to clarify, I want to <code>test -d</code> first so <code>mkdir -p</code> won't produce output about the directory already existing.</p> <pre><code>#!/bin/bash mydirs=(/var/www/files /var/www/photos /var/www/info) for d in ${mydirs[@]}; do ssh remotehost "test -d $d" res=$? test $res -ne 0 &amp;&amp; { ssh remotehost "mkdir -p $d"; res=$?; } test $res -ne 0 &amp;&amp; { echo "error during mkdir on remote"; exit 1; } done </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T01:55:50.200", "Id": "413787", "Score": "1", "body": "Normally you'd put the script on the server / VM itself, and run it after logging in through SSH. It would certainly be more efficient than running separate commands over SSH." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T02:16:25.813", "Id": "413788", "Score": "0", "body": "Thanks.This is part of a larger provisioning system which configures a VM into a specialized server. What I'm really wondering about is making it work with less code. Maybe what I have is about as trim as it gets. I can do away with the `$res` variables but as far as I see, that's about it. Just thought I'd try this forum before comitting the code in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:41:40.867", "Id": "413800", "Score": "0", "body": "@ServerFault If you are designing a system for provisioning multiple VMs, consider using proper system administration tools such as Puppet or Ansible instead of rolling your own scripts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:21:43.833", "Id": "413851", "Score": "0", "body": "@200_success Good reminder, but please stay on-topic. This question is about code review, not process review." } ]
[ { "body": "<p>Running <code>ssh</code> in a loop is not efficient. Since the script is not interactive,\nyou could pass the entire script to a remote Bash process on <code>stdin</code>,\nso that loop will run entirely on the remote server, locally:</p>\n\n<pre><code>ssh remotehost bash &lt;&lt; \"EOF\"\nmydirs=(/var/www/files /var/www/photos /var/www/info)\nfor d in ${mydirs[@]}; do\n test -d $d\n res=$?\n test $res -ne 0 &amp;&amp; { mkdir -p $d; res=$?; }\n test $res -ne 0 &amp;&amp; { echo \"error during mkdir on remote\"; exit 1; }\ndone\nEOF\n</code></pre>\n\n<p>Notice the double-quotes around the here document label, this is to avoid variable interpolation. The entire script is passed to the remote shell literally.</p>\n\n<p>I made only the minimal changes to illustrate the point. Some important improvements are well advised:</p>\n\n<ul>\n<li>All variables used as command line arguments should be double-quoted: <code>\"${mydirs[@]}\"</code>, <code>\"$d\"</code>, and so on.</li>\n<li>As a comment mentioned, when using <code>mkdir -p</code>, it's unnecessary to test if the directory exists.</li>\n<li>Now that the main operations run in a single process, the pipeline can be simplified.</li>\n<li>As another comment mentioned, consider investing in learning a proper system administration tool such as Puppet, Ansible, Chef, or similar.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:18:17.153", "Id": "413850", "Score": "0", "body": "Thanks, this is awesome. I never thought about using ssh with a HERE doc" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:50:45.997", "Id": "213937", "ParentId": "213925", "Score": "4" } }, { "body": "<p>Succinct:</p>\n\n<pre><code>#!/bin/bash -e\nssh remotehost mkdir -p /var/www/{files,photos,info}\n</code></pre>\n\n<p>Failure to create any directory will give non-zero exit for ssh, which causes the outer script to exit with error, because of the <code>-e</code> switch. </p>\n\n<p><code>mkdir</code> will print suitable error messages if it encounters errors. If you prefer the error message to appear on standard output (like <code>echo</code> would do), you can redirect standard error (aka \"filehandle 2\") to stdout (filehandle 1) by appending <code>2&gt;&amp;1</code>:</p>\n\n<pre><code>#!/bin/bash -e\nssh remotehost mkdir -p /var/www/{files,photos,info} 2&gt;&amp;1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T09:21:46.800", "Id": "413811", "Score": "1", "body": "Trading some succinctness for a little extra efficiency, we could prefix the command with `exec` since there's no need to return to the shell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:26:44.840", "Id": "413821", "Score": "0", "body": "There's a slight difference IIUC: the original stops at the first error, but `mkdir` will continue with subsequent arguments before exiting with a failure code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T10:29:35.243", "Id": "413824", "Score": "0", "body": "@TobySpeight good point and that makes `-e` unnecessary so it's only 2 extra characters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T14:24:44.310", "Id": "413854", "Score": "0", "body": "This is a great way to shorten it up but how do I get the `test -d` in there so no output (`File exists`) is produced if `mkdir -p` fails?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T17:58:34.283", "Id": "413883", "Score": "0", "body": "`mkdir -p` does not print \"file exists\" if the file exists. It does nothing." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T07:10:22.557", "Id": "213939", "ParentId": "213925", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:55:49.407", "Id": "213925", "Score": "3", "Tags": [ "bash", "linux", "ssh" ], "Title": "Creating remote directories in a bash script via ssh (with error trapping)" }
213925
<p>The official Rust book <a href="https://doc.rust-lang.org/book/ch13-01-closures.html" rel="nofollow noreferrer">chapter 13.1</a> includes an exercise to expand on the example provided in the chapter:</p> <blockquote> <p><strong>Try modifying Cacher to hold a hash map rather than a single value</strong>. The keys of the hash map will be the arg values that are passed in, and the values of the hash map will be the result of calling the closure on that key. Instead of looking at whether self.value directly has a Some or a None value, the value function will look up the arg in the hash map and return the value if it’s present. If it’s not present, the Cacher will call the closure and save the resulting value in the hash map associated with its arg value.</p> <p>The second problem with the current Cacher implementation is that it only accepts closures that take one parameter of type u32 and return a u32. We might want to cache the results of closures that take a string slice and return usize values, for example. To fix this issue, <strong>try introducing more generic parameters</strong> to increase the flexibility of the Cacher functionality.</p> </blockquote> <p>The following is what I have:</p> <pre><code>use std::thread; use std::time::Duration; use std::collections::HashMap; use std::hash::Hash; struct Cacher&lt;T, K, J&gt; where T: Fn(&amp;K) -&gt; J, K: Hash + Eq, J: Clone { calculation: T, value: HashMap&lt;K, J&gt;, } impl&lt;T, K, J&gt; Cacher&lt;T, K, J&gt; where T: Fn(&amp;K) -&gt; J, K: Hash + Eq, J: Clone { fn new(calculation: T) -&gt; Cacher&lt;T, K, J&gt; { Cacher { calculation, value: HashMap::new(), } } fn value(&amp;mut self, arg: K) -&gt; J { if let Some(v) = self.value.get(&amp;arg) { v.clone() } else { let v = (self.calculation)(&amp;arg); self.value.insert(arg, v.clone()); v } } } fn generate_workout(intensity: u32, random_number: u32) { let mut expensive_result = Cacher::new(|&amp;num| { println!(&quot;calculating slowly...&quot;); thread::sleep(Duration::from_secs(2)); num }); if intensity &lt; 25 { println!( &quot;Today, do {} pushups!&quot;, expensive_result.value(&amp;intensity) ); println!( &quot;Next, do {} situps!&quot;, expensive_result.value(&amp;intensity) ); } else { if random_number == 3 { println!(&quot;Take a break today! Remember to stay hydrated!&quot;); } else { println!( &quot;Today, run for {} minutes!&quot;, expensive_result.value(&amp;intensity) ) } } } fn main() { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout( simulated_user_specified_value, simulated_random_number ); } #[cfg(test)] mod tests { use super::*; #[test] fn call_with_different_values() { let mut c = Cacher::new(|&amp;a| a); let v1 = c.value(1); let v2 = c.value(2); assert_eq!(v1, 1); assert_eq!(v2, 2); let mut d = Cacher::new (|a: &amp;String| a.len()); let str1 = String::from(&quot;abc&quot;); let v3 = d.value(str1); assert_eq!(v3, 3); } } </code></pre> <p>I don't like the fact that my approach has the generic parameter <code>J</code> bounded by <code>Clone</code> trait. How can I make this work without the bound?</p> <p>Any other feedback is appreciated.</p>
[]
[ { "body": "<p>I like what you've done! I don't have too many comments about the content of it, since it looks good. However, you'll see below that I changed the field name <code>value</code> to <code>cache</code> and some of the generic parameter names, just to make things a little clearer. This is just a subjective preference, but I used <code>F</code> for function, <code>K</code> for key, and <code>V</code> for value.</p>\n\n<p>Another thing to note is that in many cases, you don't need to put trait bounds on the parameters for the struct itself. You just need the bounds when you are implementing functions with it, and having the bounds on the struct doesn't save you from having to write the bounds when you use it as a parameter.</p>\n\n<p>If you want to get rid of the <code>Clone</code> bound, you can return a reference to the value now stored within the cache. Here's one possible implementation of that, using <code>HashMap</code>'s entry API.</p>\n\n<pre><code>use std::collections::HashMap;\nuse std::hash::Hash;\n\nstruct Cacher&lt;F, K, V&gt; {\n calculation: F,\n cache: HashMap&lt;K, V&gt;,\n}\n\nimpl&lt;F, K, V&gt; Cacher&lt;F, K, V&gt;\nwhere\n F: Fn(&amp;K) -&gt; V,\n K: Hash + Eq,\n{\n fn new(calculation: F) -&gt; Self {\n Cacher {\n calculation,\n cache: HashMap::new(),\n }\n }\n\n fn value(&amp;mut self, arg: K) -&gt; &amp;V {\n use std::collections::hash_map::Entry;\n\n match self.cache.entry(arg) {\n Entry::Occupied(occupied) =&gt; occupied.into_mut(),\n Entry::Vacant(vacant) =&gt; {\n let value = (self.calculation)(vacant.key());\n vacant.insert(value)\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T12:36:08.577", "Id": "511385", "Score": "0", "body": "Just wanted to say a big thank you for using F for function, K for key and V for value. Seeing things like 'Z, T' with no meaning whatsoever to what they do really clouds things for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:19:54.927", "Id": "525786", "Score": "0", "body": "But this will cause the argument of the closure function to be inferred as `&{unknown}`, is there any way to solve this other than manually marking the type?\n[Screenshot](https://imgur.com/a/UsJ8Uir)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T02:31:26.880", "Id": "213999", "ParentId": "213927", "Score": "4" } } ]
{ "AcceptedAnswerId": "213999", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T01:15:06.513", "Id": "213927", "Score": "3", "Tags": [ "beginner", "generics", "rust", "cache", "closure" ], "Title": "Rust closure to be called on a cache miss" }
213927
<p>I'm currently tasked with using recursion to find pairs that add up to a given sum. How would I make the function recursiveFixedSumPairs function more efficient and truncate this code? Also, what is the current runtime? I believe it is n since it will go through the array only once always starting at the first index.</p> <pre><code>public class HW4 { public static void main(String[] args) { int[] a = {1, 5, 8, 11, 14, 15, 20, 23, 25, 28, 30, 34}; int k; k = 43; System.out.println("k = " + k); findFixedSumPairs(a, k); } public static void findFixedSumPairs(int[] a, int k) { recursiveFixedSumPairs(a, -1, 0, k); } private static void recursiveFixedSumPairs(int[] array, int subPair1, int index, int k) { // // pairs whose sum equals k are printed in this method // if ((array[subPair1] + array[subPair2]) == k) { // System.out.println("[" + array[subPair1] + ", " + array[subPair2] + "]"); // } else if ((array[subPair1] + array[subPair2]) &gt; k) { // recursiveFixedSumPairs(array, subPair1, subPair2 - 1, k); // } else { // recursiveFixedSumPairs(array, subPair1 + 1, subPair2, k); // } if (index == array.length) { return; } else if (index == array.length-1) { if (subPair1!= -1 &amp;&amp; subPair1 + array[index] == k) { System.out.println(""+subPair1 +" "+ array[index]); } else { return; } } if (subPair1 != -1) { if (array[index] == k- subPair1) { System.out.println(""+subPair1 +" "+ array[index]); return; } else { recursiveFixedSumPairs(array, subPair1, index + 1, k); } } else { recursiveFixedSumPairs(array, array[index], index+1, k); recursiveFixedSumPairs(array,-1, index+1, k); } } } </code></pre>
[]
[ { "body": "<p>Recursion is about dividing and conquering. You are going to check the first element of an array (E0) against each element in the rest of the array. Once you have checked all the elements, you pick the next element (E1) in the array and check it against all the other elements. Since you've already checked E1 against E0 in the previous iteration, you only need to check E1 against the elements after it.</p>\n\n<p>First of all, your naming is unclear. The \"fixed\" has no meaning here, so let's drop it. Single letter parameter and argiment names are only reserved for loop counters. So \"k\" must become \"expectedSum\". The entry-function to the iteration just takes the user input. It adds the initial entry parameters for the iterative function (indexes to first entry in the array and the first entry of the sub-array. Since the entry function initializes the recursive function with valid values, there is no need to check for magic -1 values in the iterative function anymore.</p>\n\n<pre><code>public static void findSumPairs(int[] array, int expectedSum) {\n recursiveSumPairs(array, expectedSum, 0, 1);\n}\n\nprivate static void recursiveSumPairs(\n int[] array,\n int expectedSum,\n int firstIndex,\n int nextIndex) {\n\n // End condition for recursion: first element to check is the last\n // element in the array. This also handles input arrays shorter than\n // two elements.\n if (firstIndex &gt;= array.length - 1) {\n return;\n }\n\n // We have exhausted the sub-array. Advance the first element to the\n // next index and compare it to the rest of the elements left in the\n // array.\n if (nextIndex &gt;= array.length) {\n recursiveSumPairs(array, expectedSum, firstIndex + 1, firstIndex + 2);\n return;\n }\n\n if (array[firstIndex] + array[nextIndex] == expectedSum) {\n System.out.println(array[firstIndex] + \" + \" + array[nextIndex]);\n }\n\n // Compare first element to the next element in the array.\n recursiveSumPairs(array, expectedSum, firstIndex, nextIndex + 1);\n}\n</code></pre>\n\n<p>My presonal preference is to use \">=\" and \"&lt;=\" instead of \"==\" when checking loop counters against end conditions. It implies that the left side of the comparison is a value that increases/decreases and guards against bugs where the counter increases by two. Although if you were really paranoid you could add special check for that and throw an IllegalStateException (the new kids on the block would probably use assertations).</p>\n\n<p>Now, if you want to go fancy with the solution, instead of burdening the algorithm with display functions (System.out.printlning the result), you could pass a BiConsumer to the function and let the caller decide what to do with the results (possibly with a nice lambda).</p>\n\n<pre><code>findSumPairs(\n array,\n sum,\n (a, b) -&gt; System.err.println(a + \" + \" + b));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:41:35.310", "Id": "413805", "Score": "0", "body": "Keep up the good work!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:02:36.167", "Id": "213934", "ParentId": "213929", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:40:57.673", "Id": "213929", "Score": "1", "Tags": [ "java", "recursion", "complexity", "k-sum" ], "Title": "Finding pairs that add up to a given sum, using recursion" }
213929
<p>I got this question during my practice interview.</p> <h2>Matrices - N Spiral Matrix</h2> <h3>Prompt</h3> <p>Given an integer N, output an N x N spiral matrix with integers 1 through N.</p> <h3>Examples:</h3> <pre><code>Input: 3 Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]] Input: 1 Output: [[1]] </code></pre> <p>My solution is below:</p> <pre><code>function spiralMatrix(n) { const matrix = []; let counter = 1, rowMin = 0, rowMax = n - 1, colMin = 0, colMax = n - 1; for (let i = 0; i &lt; n; i++) { matrix.push(new Array(n).fill(0)); } while (rowMin &lt;= rowMax &amp;&amp; colMin &lt;= colMax) { for (let col = colMin; col &lt;= colMax; col++) { matrix[rowMin][col] = counter++; } rowMin++; for (let row = rowMin; row &lt;= rowMax; row++) { matrix[row][colMax] = counter++; } colMax--; for (let col = colMax; col &gt;= colMin; col--) { matrix[rowMax][col] = counter++; } rowMax--; for (let row = rowMax; row &gt;= rowMin; row--) { matrix[row][colMin] = counter++; } colMin++; } return matrix; } console.log(spiralMatrix(10)); </code></pre>
[]
[ { "body": "<p>This code is well written;</p>\n\n<p><strong>Comments</strong></p>\n\n<ul>\n<li>You have no comments whatsoever, fortunately the code reads well</li>\n</ul>\n\n<p><strong>JSHint.com</strong></p>\n\n<ul>\n<li>Your code passes all checks, well done</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T16:59:59.863", "Id": "213975", "ParentId": "213931", "Score": "2" } }, { "body": "<p>Nice code. I have just one nitpick.</p>\n\n<p>No need to declare all variables at the top of a function.\nIt's good to declare variables right before they are used.\nIn the posted code, the filling of <code>matrix</code> could go directly after its declaration,\nand the rest of the variables could be declared right before the loop that uses them.\nI mean like this:</p>\n\n<pre><code> const matrix = [];\n for (let i = 0; i &lt; n; i++) {\n matrix.push(new Array(n).fill(0));\n }\n\n let counter = 1,\n rowMin = 0,\n rowMax = n - 1,\n colMin = 0,\n colMax = n - 1;\n\n while (rowMin &lt;= rowMax &amp;&amp; colMin &lt;= colMax) {\n // ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T16:52:58.567", "Id": "414003", "Score": "0", "body": "Do you have any references that say it is good to declare variables right before they are used? This does not seem to follow any major coding styles guide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T17:20:42.630", "Id": "414005", "Score": "0", "body": "@konijn the book Code Complete takes about *span* and *live time* of variables. See it explained here: http://www.nikola-breznjak.com/blog/books/programming/code-complete-2-steve-mcconnell-general-issues-using-variables/ . Keeping these numbers low mitigates the mental burden for readers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T19:04:37.553", "Id": "213983", "ParentId": "213931", "Score": "2" } }, { "body": "<p>Rather than use <code>row</code>, and <code>col</code>, it is common to index a 2D array with <code>x</code> and <code>y</code>. <code>x</code> is column and <code>y</code> is row. </p>\n\n<p>Rather than use <code>for</code> loops, you can reduce the noise using <code>while</code> loops inside the main loop.</p>\n\n<p>The main exit condition is a little complex. You are counting the values with <code>counter</code> so why not just check its value <code>while(counter &lt; n ** 2) {</code></p>\n\n<p><code>colMax</code> and <code>rowMax</code> can be combined to just one value, same with <code>colMin</code>, and <code>rowMin</code></p>\n\n<p>The overhead of creating and filling each array before you start is negating the benefit of avoiding sparse arrays. The code would be simpler if you just push an array literal rather then a new n item array filled with 0.</p>\n\n<p>Thus you end up with</p>\n\n<pre><code>function spiralMatrix(n) {\n var c = 1, min = 0, max = n - 1, x = 0, y = 0;\n const matrix = [];\n for (let i = 0; i &lt; n; i++) { matrix.push([]) }\n while (c &lt; n ** 2) {\n while (x &lt; max) { matrix[y][x++] = c++ }\n while (y &lt; max) { matrix[y++][x] = c++ }\n while (x &gt; min) { matrix[y][x--] = c++ }\n min++;\n while (y &gt; min) { matrix[y--][x] = c++ }\n max--;\n }\n matrix[y][x] = c;\n return matrix;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T16:34:38.140", "Id": "214046", "ParentId": "213931", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T02:01:50.290", "Id": "213931", "Score": "5", "Tags": [ "javascript", "programming-challenge", "interview-questions" ], "Title": "Print out N by N Spiral Matrix in javascript" }
213931
<p>I made a program to read the source code from a url. To reach this url I need to specify a <code>token</code>. After read the source code, I extract a url in json format, andIi redirect my domain to this url. It's not relevant to what I'm asking, but I want explain what I'm doing.</p> <p>As you can see, on my domain <code>http://localhost/test</code>, I have a query string called <code>token</code> that is used to read the source code of a different domain. After this I redirect to a page.</p> <p>I defined the domain which I will read the source code but I don't know if someone could pass a value to the <code>$_GET['token']</code> in a way that this will go to a different domain. I'm reading the source code from a url and using the result on my website, so I don't know if someone could do some kind of attack to my server. I'm not sure how these kind of attacks works, and I felt that I should ask someone that has more knowledge than I.</p> <p>What do you think about my code?</p> <p>php:</p> <pre><code> //i use this condition to make sure that nobody can access the url directly, //and later make sure that the request is from my domain if(!empty($_SERVER['HTTP_REFERER'])){ //if $_GET[] is empty then $.. is = NULL, else $.. is = $_GET[] $source = (empty($_GET['source']) ? NULL : $_GET['source']); $token = (empty($_GET['token']) ? NULL : $_GET['token']); if(!empty($source) &amp;&amp; !empty($token)){ if($source == 'player'){ //check if the request is from the same domain if(preg_match('/^http:\/\/localhost\/test/', $_SERVER['HTTP_REFERER'])){ //inside this if() i read the source //code from this url bellow $urlPost = 'https://www.player.com/?token='.$token; $url = file_get_contents($urlPost); preg_match('/CONFIG = (.*)/', $url, $matches); $jsn = json_decode($matches[1]); $streams = $jsn-&gt;streams; foreach($streams as $i){ //this variable will be used to redirect the src //iframe to a url that contains a video $vdUrl = $i-&gt;url; } //redirect to the url that i got from the source code die(header('location:'.$vdUrl)); }else{ //if the request is not from the same domain then //redirect to 404 Not Found die(header('HTTP/1.1 404 Not Found')); } }else{ die(header('HTTP/1.1 404 Not Found')); } } } </code></pre> <p>html:</p> <pre><code>&lt;iframe src="http://localhost/test/?source=player&amp;token=145215d1ww"&gt;&lt;/iframe&gt; </code></pre>
[]
[ { "body": "<p>not a php expert but I think you might improve your code a bit to make it more clean.</p>\n\n<p>the piece of code:</p>\n\n<blockquote>\n <pre class=\"lang-php prettyprint-override\"><code>if($source == 'player'){\n //check if the request is from the same domain\n if(preg_match('/^http:\\/\\/localhost\\/test/', $_SERVER['HTTP_REFERER'])){\n\n // your code...\n\n } else {\n die(header('HTTP/1.1 404 Not Found'));\n } \n} else {\n die(header('HTTP/1.1 404 Not Found'));\n}\n</code></pre>\n</blockquote>\n\n<p>might become simply</p>\n\n<pre><code>if(!$source == 'player' || !preg_match('/^http:\\/\\/localhost\\/test/', $_SERVER['HTTP_REFERER']))\n die(header('HTTP/1.1 404 Not Found'))\n\n//your code here\n</code></pre>\n\n<p>For your question I would wait for some expert</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:03:44.750", "Id": "413801", "Score": "0", "body": "Just for your info, no code that couldn't be read (because of scrolling) can be considered simple." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:25:48.557", "Id": "413802", "Score": "0", "body": "Yes i could have combined both conditions into one, thanks for the advice" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T07:52:39.047", "Id": "213941", "ParentId": "213936", "Score": "3" } }, { "body": "<h3>The Security</h3>\n<p>The main point here is your assumption that HTTP_REFERER could prevent someone from using this code. Unfortunately it doesn't. Referrer, just like any other HTTP header, is easily faked, one is setting it routinely with any software that is doing HTTP requests. So be advised that it is an ostrich-style defense.</p>\n<p>You should understand that there is <strong>absolutely no way to protect</strong> the information which is shown in the browser. The only way to restrict an access to a script is to make it password protected.</p>\n<p>Moreover, I suppose that a concerned user could easily guess the domain from which you are requesting the data, and then just bluntly <strong>take the token from the source of <em>your</em> page</strong> and then just use it at their own disposal. Consider storing the token inside your PHP code instead.</p>\n<h3>The code.</h3>\n<p>That said, your code could be <em>syntactically</em> improved as well. First of all, just like it said in the other answer, you could combine all conditions in one. <em>But it mustn't be done at the expense of readability.</em> So first define your conditions and then check them at once.</p>\n<p>After that you could just write your code without any conditions. A loop is unnecessary if there is only one value in the array</p>\n<pre><code>$referrer = $_SERVER['HTTP_REFERER'] ?? '';\n$access = preg_match('!^http://localhost/test!', $referrer);\n$token = $_GET['token'] ?? '';\n$source = $_GET['source'] ?? '';\n$source_ok = $source == 'player';\n\nif (!$referrer || !$access || !$token || !$source || !$source_ok) {\n header('HTTP/1.1 404 Not Found');\n die;\n}\n$urlPost = 'https://www.player.com/?token='.$token;\n$url = file_get_contents($urlPost);\npreg_match('/CONFIG = (.*)/', $url, $matches);\n$jsn = json_decode($matches[1]);\n$vdUrl = $jsn-&gt;streams[0]-&gt;url;\nheader('location:'.$vdUrl);\n</code></pre>\n<p>Note: if <code>$_GET['source'] ?? '';</code> operator is giving you an error, consider upgrading your PHP version immediately, because it is not supported anymore.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T18:20:04.257", "Id": "413889", "Score": "0", "body": "What is the purpose of this regex? `!^http://localhost/test!` It's not matching https://regex101.com/r/QpREDg/1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T08:43:15.320", "Id": "213944", "ParentId": "213936", "Score": "9" } } ]
{ "AcceptedAnswerId": "213944", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T06:47:56.470", "Id": "213936", "Score": "7", "Tags": [ "php", "security" ], "Title": "Reading source code and extracting json from a url" }
213936
<p>I'm creating an Angular widget which combines a dropdown with a custom input. I've made it generic and am preparing a blogpost explaining my setup, and would love to get a review before I do so.</p> <p>The most basic <em>usage</em> of this component would look like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;select-with-custom-input baseOptions="['one', 'two', 'three']" customOption="other, specify..." selectLabel="Pick something" placeholder="enter a value" required="true" classForLabel="form-label" classForSelect="form-control" classForInput="form-control mt-3" [(ngModel)]="myModelProperty" &gt;&lt;/select-with-custom-input&gt; </code></pre> <p>See <a href="https://stackblitz.com/edit/angular-55ctpf" rel="nofollow noreferrer">this StackBlitz.com example</a> for a live demo.</p> <p>You will see a dropdown, and if you select the <code>customOption</code> you get a chance to fill out a custom value in an input field. The end result of the component should be <em>one</em> string value: either one of the base options, or the custom text you provided.</p> <p>The component's code is inspired on <a href="https://github.com/angular/angular/blob/f8096d499324cf0961f092944bbaedd05364eea1/packages/forms/src/directives/default_value_accessor.ts" rel="nofollow noreferrer">the default <code>ControlValueAccessor</code> from the Angular source code</a>, and that's what I'd love to get feedback on:</p> <pre class="lang-typescript prettyprint-override"><code>import { Component, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'select-with-custom-input', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: SelectWithCustomInputComponent, multi: true, }], styles: [], template: ` &lt;label for="selectForBaseOptions" [class]="classForLabel" *ngIf="selectLabel"&gt; {{ selectLabel }} &lt;/label&gt; &lt;select [class]="classForSelect" id="selectForBaseOptions" [required]="required" [disabled]="_isDisabled" (blur)="onTouched()" (ngModelChange)="_selectChanged($event)" [(ngModel)]="_selectedOption"&gt; &lt;option value="" [selected]="_selectedOption === ''"&gt;&lt;/option&gt; &lt;option *ngFor="let option of baseOptions" [selected]="_selectedOption === option" [value]="option"&gt; {{ option }} &lt;/option&gt; &lt;option [value]="customOption" [selected]="_isCustomOptionSelected"&gt; {{ customOption }} &lt;/option&gt; &lt;/select&gt; &lt;input type="text" id="inputForCustomOption" [class]="classForInput" *ngIf="_isCustomOptionSelected" [required]="required" [disabled]="_isDisabled" [placeholder]="placeholder" (blur)="onTouched()" (ngModelChange)="_customValueChanged($event)" [(ngModel)]="_customInput"&gt; `, }) export class SelectWithCustomInputComponent implements ControlValueAccessor { @Input() selectLabel = ''; @Input() baseOptions = []; @Input() customOption = 'Other...'; @Input() placeholder = ''; @Input() required = false; // Allow frameworks like Bootstrap to style individual elements easily: @Input() classForLabel = ''; @Input() classForInput = ''; @Input() classForSelect = ''; _selectedOption = ''; _customInput = ''; _isCustomOptionSelected = false; _isDisabled = false; private onChange = (_: any) =&gt; { }; private onTouched = (_: any) =&gt; { }; _selectChanged(value: string): void { this._isCustomOptionSelected = value === this.customOption; this.onChange(this._isCustomOptionSelected ? this._customInput : value); } _customValueChanged(value: string): void { this.onChange(value); } writeValue(value: string): void { const normalizedValue = value == null ? '' : value; this._isCustomOptionSelected = normalizedValue ? this.customOption === normalizedValue || !this.baseOptions.includes(normalizedValue) : false; if (this._isCustomOptionSelected) { this._selectedOption = this.customOption; this._customInput = normalizedValue; } else { this._selectedOption = normalizedValue; this._customInput = ''; } } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState?(isDisabled: boolean): void { this._isDisabled = isDisabled; } } </code></pre> <p>I also have a test suite with component integration tests to check if the behavior is as expected, that should give (near) 100% statement coverage. If you have any comments on this spec it would also be appreciated:</p> <pre class="lang-typescript prettyprint-override"><code>import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { SelectWithCustomInputComponent } from './select-with-custom-input.component'; describe('SelectWithCustomInputComponent', () =&gt; { let fixture: ComponentFixture&lt;SelectWithCustomInputComponent&gt;; let component: SelectWithCustomInputComponent; let nativeElement: HTMLElement; let select: HTMLSelectElement; let latestValueReceivedFromComponent; let hasOnTouchedBeenCalled = false; // Has an *ngIf so need to get this element as late as possible const getInputElement = () =&gt; nativeElement.querySelector('input'); function makeFixtureStable() { fixture.detectChanges(); tick(); } beforeEach(async(() =&gt; { TestBed.configureTestingModule({ imports: [ FormsModule ], declarations: [ SelectWithCustomInputComponent ], }) .compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(SelectWithCustomInputComponent); component = fixture.componentInstance; fixture.detectChanges(); component.registerOnChange(val =&gt; latestValueReceivedFromComponent = val); component.registerOnTouched(_ =&gt; hasOnTouchedBeenCalled = true); nativeElement = fixture.nativeElement; select = nativeElement.querySelector('select'); }); it('should see null as empty string', fakeAsync(() =&gt; { component.writeValue(null); makeFixtureStable(); expect(select.value).toEqual(''); })); it('should see undefined as empty string', fakeAsync(() =&gt; { component.writeValue(undefined); makeFixtureStable(); expect(select.value).toEqual(''); })); it('should see empty string as empty string', fakeAsync(() =&gt; { component.writeValue(''); makeFixtureStable(); expect(select.value).toEqual(''); })); it('should be able to select a base option', fakeAsync(() =&gt; { component.baseOptions = ['option 1', 'option 2']; component.writeValue('option 2'); makeFixtureStable(); expect(select.value).toEqual('option 2'); })); it('should not show the input if a base option is selected', fakeAsync(() =&gt; { component.baseOptions = ['option 1']; component.writeValue('option 1'); makeFixtureStable(); expect(getInputElement()).toBeFalsy(); })); it('should be able to load custom option', fakeAsync(() =&gt; { component.baseOptions = ['option 1']; component.writeValue('my custom text'); makeFixtureStable(); expect(getInputElement().value).toEqual('my custom text'); })); it('should propagate disabled state to select', fakeAsync(() =&gt; { component.setDisabledState(true); makeFixtureStable(); expect(select.disabled).toBeTruthy(); })); it('should propagate disabled state to input', fakeAsync(() =&gt; { component.writeValue('my custom text'); component.setDisabledState(true); makeFixtureStable(); expect(getInputElement().disabled).toBeTruthy(); })); it('should propagate placeholder state to input', fakeAsync(() =&gt; { component.placeholder = 'enter your value'; component.writeValue('my custom text'); makeFixtureStable(); expect(getInputElement().getAttribute('placeholder')).toEqual('enter your value'); })); it('should register change of option', fakeAsync(() =&gt; { component.baseOptions = ['A', 'B']; makeFixtureStable(); select.value = 'B'; select.dispatchEvent(new Event('change')); makeFixtureStable(); expect(latestValueReceivedFromComponent).toEqual('B'); })); it('should register change to provided custom option', fakeAsync(() =&gt; { component.baseOptions = ['A', 'B']; component.customOption = 'Custom!'; makeFixtureStable(); select.value = 'Custom!'; select.dispatchEvent(new Event('change')); makeFixtureStable(); expect(latestValueReceivedFromComponent).toEqual(''); })); it('should register value entered in input', fakeAsync(() =&gt; { component.baseOptions = ['A']; makeFixtureStable(); select.value = 'Other...'; select.dispatchEvent(new Event('change')); makeFixtureStable(); expect(latestValueReceivedFromComponent).toEqual(''); getInputElement().value = 'custom text'; getInputElement().dispatchEvent(new Event('input')); expect(latestValueReceivedFromComponent).toEqual('custom text'); })); it('should fire touched handler on select blur', fakeAsync(() =&gt; { component.baseOptions = ['A']; select.dispatchEvent(new Event('blur')); makeFixtureStable(); expect(hasOnTouchedBeenCalled).toBeTruthy(); })); it('should fire touched handler on input blur', fakeAsync(() =&gt; { component.baseOptions = ['A']; makeFixtureStable(); select.value = 'Other...'; select.dispatchEvent(new Event('change')); makeFixtureStable(); hasOnTouchedBeenCalled = false; getInputElement().dispatchEvent(new Event('blur')); makeFixtureStable(); expect(hasOnTouchedBeenCalled).toBeTruthy(); })); }); </code></pre> <p>PS. This was built with an Angular 7 CLI project in mind.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T09:25:01.510", "Id": "213946", "Score": "1", "Tags": [ "typescript", "angular-2+" ], "Title": "Angular component for select with custom input" }
213946
<p>I'm building a procedure which compares two JSON objects and return two JSON objects with differences between each (compared keys and values). But I have relatively superficial SQL knowledge, so I need your review to avoid any simple mistakes and improve my code.</p> <p><strong>Compares "first" against "second" and returns the values in "first" that are not present in "second" OR has different value</strong></p> <pre class="lang-sql prettyprint-override"><code>DELIMITER $$ DROP PROCEDURE IF EXISTS json_diff $$ # Compares "first" against "second" and # returns the values in "first" that are not present in "second" OR has different value CREATE PROCEDURE json_diff(IN first JSON, IN second JSON, INOUT firstResult JSON, INOUT secondResult JSON) BEGIN DECLARE oldKey VARCHAR(300); DECLARE oldVal, newVal INT; DECLARE i, secondHasKey INT DEFAULT 0; DECLARE oldKeys, newKeys JSON; SELECT JSON_KEYS(first) INTO oldKeys; SELECT JSON_KEYS(second) INTO newKeys; WHILE i &lt; JSON_LENGTH(oldKeys) DO SELECT JSON_EXTRACT(oldKeys, CONCAT('$[',i,']')) INTO oldKey; SELECT JSON_EXTRACT(first, CONCAT('$.', oldKey)) INTO oldVal; SELECT JSON_CONTAINS_PATH(second, 'one', CONCAT('$.', oldKey)) INTO secondHasKey; IF secondHasKey = 1 THEN SELECT JSON_EXTRACT(second, CONCAT('$.', oldKey)) INTO newVal; IF oldVal != newVal THEN SELECT JSON_INSERT(firstResult, CONCAT('$.', oldKey), oldVal) INTO firstResult; SELECT JSON_INSERT(secondResult, CONCAT('$.',oldKey), newVal) INTO secondResult; end if; ELSE SELECT JSON_INSERT(firstResult, CONCAT('$.', oldKey), oldVal) INTO firstResult; end if; SET i = i + 1; end while; END $$ </code></pre> <p><strong>Use above PROCEDURE to make bidirectional comparison.</strong></p> <pre class="lang-sql prettyprint-override"><code>DELIMITER $$ DROP PROCEDURE IF EXISTS json_diff_both $$ CREATE PROCEDURE json_diff_both(IN first JSON, IN second JSON, INOUT firstResult JSON, INOUT secondResult JSON) BEGIN CALL json_diff(first, second, firstResult, secondResult); CALL json_diff(second, first, secondResult, firstResult); END $$ </code></pre>
[]
[ { "body": "<p>You are missing a second part of the diff.</p>\n\n<p>I've added the missing part, renamed the variables a bit to make it easier to work with, and added some comments.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS JSON_OBJECT_DIFF $$\n\nCREATE PROCEDURE JSON_OBJECT_DIFF(IN a JSON, IN b JSON, INOUT aResult JSON, INOUT bResult JSON)\nBEGIN\n DECLARE aKeys, bKeys JSON;\n DECLARE currentKey, currentKeyPath TEXT;\n DECLARE aVal, bVal JSON;\n DECLARE aKeysLength, bKeysLength, aHasKey, bHasKey INT;\n DECLARE i INT DEFAULT 0;\n\n SELECT JSON_KEYS(a) INTO aKeys;\n SELECT JSON_KEYS(b) INTO bKeys;\n SELECT JSON_LENGTH(aKeys) INTO aKeysLength;\n SELECT JSON_LENGTH(bKeys) INTO bKeysLength;\n\n # Iterate keys in `a` as `currentKey`:\n # * If exists in `b` and !=, insert `a(currentKey)` and `b(currentKey)` into `aResult` and `bResult`\n # * If does not exist in `b`, insert `a(currentKey)` into `aResult`\n\n WHILE i &lt; aKeysLength DO\n SELECT JSON_EXTRACT(aKeys, CONCAT('$[', i, ']')) INTO currentKey; /* Already quoted */\n SELECT CONCAT('$.', currentKey) INTO currentKeyPath;\n SELECT JSON_EXTRACT(a, currentKeyPath) INTO aVal;\n\n SELECT JSON_CONTAINS_PATH(b, 'one', currentKeyPath) INTO bHasKey;\n\n IF bHasKey = 1 THEN\n SELECT JSON_EXTRACT(b, currentKeyPath) INTO bVal;\n\n IF aVal != bVal THEN\n SELECT JSON_INSERT(aResult, currentKeyPath, aVal) INTO aResult;\n SELECT JSON_INSERT(bResult, currentKeyPath, bVal) INTO bResult;\n end if;\n ELSE\n SELECT JSON_INSERT(aResult, currentKeyPath, aVal) INTO aResult;\n END IF;\n\n SET i = i + 1;\n END WHILE;\n\n # Iterate keys in `b` as `currentKey`:\n # * If does not exist in `a`, insert `b(currentKey)` into `bResult`\n\n SET i = 0;\n WHILE i &lt; bKeysLength DO\n SELECT JSON_EXTRACT(bKeys, CONCAT('$[', i, ']')) INTO currentKey; /* Already quoted */\n SELECT CONCAT('$.', currentKey) INTO currentKeyPath;\n\n SELECT JSON_CONTAINS_PATH(a, 'one', currentKeyPath) INTO aHasKey;\n\n IF aHasKey = 0 THEN\n SELECT JSON_EXTRACT(b, currentKeyPath) INTO bVal;\n SELECT JSON_INSERT(bResult, currentKeyPath, bVal) INTO bResult;\n END IF;\n\n SET i = i + 1;\n END WHILE;\nEND $$\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T15:08:37.927", "Id": "462841", "Score": "0", "body": "Keep in mind on code review, the code has to work as expected, so the second part of the diff wasn't necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:19:06.230", "Id": "462923", "Score": "0", "body": "@pacmaninbw Got it, thanks :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T14:51:53.290", "Id": "236236", "ParentId": "213951", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:27:40.033", "Id": "213951", "Score": "4", "Tags": [ "sql", "mysql", "json", "edit-distance", "stored-procedure" ], "Title": "MySQL JSON diff procedure" }
213951
<p>I just figured out how to do a building menu with a progression feature in c++ console application.</p> <p>What this code does:</p> <p>It simply offers you a choice to build a building and then prints the progression like: 1% - 9% erasing and printing one number at a time (Which is the kind of the core feature that I struggled a lot with).</p> <p>then prints "Building done".</p> <p>I would like to have some thoughts and comments on how to:</p> <ol> <li>Make this code simpler in any way .</li> <li>Did someone else make the same feature and how did you implement it?</li> <li>General thoughts on the code</li> <li>How would you structure it?</li> </ol> <hr> <pre><code>std::string building; std::cout &lt;&lt; "-CONSTRUCTION MENU-" &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; "1. Barrack" &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; "Build: "; std::cin &gt;&gt; building; if (building == "1" || building == "Barrack" || building == "barrack") { std::string sentence[10] = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" }; for (int index = 0; sentence[index] != sentence[9]; index++) { std::cout &lt;&lt; sentence[index] &lt;&lt; std::flush; std::cout &lt;&lt; "\b\b"; Sleep(150); if (index == 8) { system("cls"); std::cout &lt;&lt; "Building done" &lt;&lt; std::endl; system("pause"); break; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T13:13:30.403", "Id": "413846", "Score": "1", "body": "This kind of implies that 10% means that it's done, or that the remaining 90% progresses instantaneously." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T13:59:47.300", "Id": "413848", "Score": "0", "body": "\"How would you structure it?\" Well, that depends on what else you're planning to add. Is this going to be a CLI interface to a Red Alert game? How many buildings are you going to support? Are you going to support more than just buildings? You're in desperate need of some kind of mapping, something to be able to select the next building as well without the program shutting down on you and a decoupling of the input validation to the rest of the program. But at the moment there's not much of a feature yet, so I'm wondering what you mean with point 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T19:28:53.853", "Id": "413896", "Score": "0", "body": "I bet you only go up to 9% because you delete exactly two characters. Why not print `\\b` for each character you wrote? `std::string` has a nice `size()` function... Also, you should consider sleeping *before* deleting, now you print and delete immediately, then pause, so you can't really see what was printed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T21:02:51.637", "Id": "413903", "Score": "0", "body": "@200_success yes it is supponera to implicerar that 10% is done but can easiky be changed. Was convenient for testing. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T21:10:23.577", "Id": "413904", "Score": "0", "body": "@Mast Hmm im thinking of making a CLI game. But my next thing would be to have the building-progression going on and be able to go back to Other menus and do other stuff at the same time, then go back to the ”building menu” and check the progression. Any suggestions there? ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T21:17:26.733", "Id": "413905", "Score": "0", "body": "@Cris Luengo Yes exactly i could add 10% and ”\\b\\b\\b” but adding \\b for each character is actually a great Idea. Thanks for that! I Will check out the size() function. What would you use the size() function for? :) changing the placement of sleep is also a really good Idea, Thanks! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T21:53:27.983", "Id": "413908", "Score": "0", "body": "You can do something like `std::cout << std::string(sentence[index].size(), '\\b')` to erase exactly the number of characters in `sentence[index]`." } ]
[ { "body": "<p>There are several things you can do to improve this code.</p>\n\n<p>First of all the code above isn't a valid C++ code. To run it you need to add:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;Windows.h&gt;\n\nint main()\n{\n ... // your code posted above\n}\n</code></pre>\n\n<p>Please next time you ask a question post the full code.</p>\n\n<p>Then your Menu:</p>\n\n<pre><code>std::cout &lt;&lt; \"-CONSTRUCTION MENU-\" &lt;&lt; std::endl &lt;&lt; std::endl;\n\nstd::cout &lt;&lt; \"1. Barrack\" &lt;&lt; std::endl &lt;&lt; std::endl;\n\nstd::cout &lt;&lt; \"Build: \";\n</code></pre>\n\n<p>Consider writing it like this:</p>\n\n<pre><code>std::cout &lt;&lt; \"-CONSTRUCTION MENU-\\n\\n\"\n&lt;&lt; \"1. Barrack\\n\\n\"\n&lt;&lt; \"Build: \";\n</code></pre>\n\n<ul>\n<li><p><code>\\n</code> should be used instead of <code>std::endl</code>. The reason is <code>std::endl</code>\nnot only gives you a new line, it also does an expensive buffer\nflushing operation which is rarely necessary.</p></li>\n<li><p>No need to call <code>std::cout</code> several times after each other. Statements\ncan be chained.</p></li>\n</ul>\n\n<p>Then your Percentage display:</p>\n\n<pre><code>std::string sentence[10] = { \"1%\", \"2%\",\"3%\", \"4%\", \"5%\", \"6%\", \"7%\", \"8%\", \"9%\" };\n\nfor (int index = 0; sentence[index] != sentence[9]; index++)\n{\n ...// statements inside\n}\n</code></pre>\n\n<p>Several things are wrong here:</p>\n\n<ul>\n<li>You are using a plain C array to hold the sentence variables. This is\nvery bad because a C array does not know about its size. Instead you\nuse the magic number '9' to finish iterating over the strings.\nPlease study the default C++ containers <code>std::array</code> or\n<code>std::vector</code>. In this case I would go for array since you don't want\nto add more values at run time.</li>\n<li>The size is wrong. You declared space for 10 elements but only put\nin 9.</li>\n<li><code>sentence</code> is a very bad name. You don't store sentences. Consider\nusing <code>percentages</code> instead.</li>\n</ul>\n\n<p>Now we can write this instead:</p>\n\n<pre><code>std::array&lt;std::string, 9&gt; percentages = { \"1%\", \"2%\",\"3%\", \"4%\", \"5%\", \"6%\", \"7%\", \"8%\", \"9%\" };\n\nfor (const auto&amp; sentence : sentences)\n{\n ...// statements inside\n}\n</code></pre>\n\n<p>So the world is OK now? Not at all. You shouldn't use an array for numbers in the first place. Consider building the numbers in a loop instead:</p>\n\n<pre><code>for (int i = 1; i &lt;= 9; ++i) {\n std::cout &lt;&lt; std::to_string(i) &lt;&lt; '%' &lt;&lt; \"\\b\\b\";\n Sleep(150);\n}\n</code></pre>\n\n<p>I removed the <code>std::flush</code> here since I don't see its purpose.</p>\n\n<p>As a side hint it is a good practice to use <code>++i</code> instead of <code>i++</code>. If you use objects later instead of ints you save an expensive copy.</p>\n\n<p>Now we come to another dark chapter of your snippet. Your program is mixed with non-portable statements:</p>\n\n<pre><code>Sleep(150);\n</code></pre>\n\n<p>Consider using std facilities here:</p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;thread&gt;\n\n...\n\n\nstd::this_thread::sleep_for(std::chrono::milliseconds(150));\n</code></pre>\n\n<p>The big advantage here is that this is portable now.</p>\n\n<p>The next candidate is:</p>\n\n<pre><code>system(\"pause\");\n</code></pre>\n\n<p>Since you just want the program to wait with a message at the end you can do this:</p>\n\n<pre><code>std::cout &lt;&lt; \"Press any key...\";\nstd::cin.get();\n</code></pre>\n\n<p>The last statement we get to is this:</p>\n\n<pre><code>system(\"cls\");\n</code></pre>\n\n<p>No easy answer here. The fact is that the standard does not provide a portable solution here. You could wrap the statement in a function and make it portable for different platforms like this:</p>\n\n<pre><code>void clear_screen()\n{\n#if defined _WIN32\n std::system(\"cls\");\n#elif defined __unix__\n std::system(\"clear\");\n#elif defined (__APPLE__)\n std::system(\"clear\");\n#endif\n}\n</code></pre>\n\n<p>We should also replace the </p>\n\n<pre><code>#include &lt;windows.h&gt; \n</code></pre>\n\n<p>with </p>\n\n<pre><code>#include &lt;cstdlib&gt;\n</code></pre>\n\n<p>So now also on Linux / MAC the clear should work.</p>\n\n<p>As a last word. A function should only do one thing. You should separate the program in well defined parts. Here is my reworked solution with all the improvements already mentioned, dividing the program into parts:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;chrono&gt;\n#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;thread&gt;\n\nvoid clear_screen()\n{\n#if defined _WIN32\n std::system(\"cls\");\n#elif defined (__unix__) \n std::system(\"clear\");\n#elif defined (__APPLE__)\n std::system(\"clear\");\n#endif\n}\n\nstd::string get_user_choice()\n{\n std::string choice;\n std::cout &lt;&lt; \"-CONSTRUCTION MENU-\\n\\n\"\n &lt;&lt; \"1. Barrack\\n\\n\"\n &lt;&lt; \"Build: \";\n std::cin &gt;&gt; choice;\n return choice;\n}\n\nvoid print_progress(int start, int end)\n{\n for (auto i = start; i &lt;= end; ++i) {\n std::cout &lt;&lt; std::to_string(i) &lt;&lt; '%' &lt;&lt; \"\\b\\b\";\n std::this_thread::sleep_for(std::chrono::milliseconds(150));\n }\n}\n\nvoid print_building_completed()\n{\n clear_screen();\n std::cout &lt;&lt; \"Building done\\n\";\n std::cout &lt;&lt; \"Press any key...\";\n std::cin.get();\n}\n\nint main()\n{\n auto building = get_user_choice();\n if (building == \"1\" || building == \"Barrack\" || building == \"barrack\"){\n print_progress(0, 100);\n print_building_completed();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T16:24:14.820", "Id": "221003", "ParentId": "213952", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:59:49.130", "Id": "213952", "Score": "3", "Tags": [ "c++", "game", "console", "animation", "windows" ], "Title": "C++ console progress display" }
213952